]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
- fix carttogeod() function (don't convert the altitude from radian to degree ;-)
[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
369 // <pi>        ... callback function with two args: target, data
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, "parsexml(): path argument missing or not a string");
377     if(argc > 5) argc = 5;
378     for(int i=1; i<argc; i++)
379         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
380             naRuntimeError(c, "parsexml(): callback argument not a function");
381
382     const char* file = naStr_data(args[0]);
383     std::ifstream input(file);
384     NasalXMLVisitor visitor(c, argc, args);
385     try {
386         readXML(input, visitor);
387     } catch (const sg_exception& e) {
388         string msg = string("parsexml(): file '") + file + "' "
389                      + e.getFormattedMessage();
390         naRuntimeError(c, msg.c_str());
391         return naNil();
392     }
393     return args[0];
394 }
395
396 // Return UNIX epoch time in seconds.
397 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
398 {
399 #ifdef WIN32
400     FILETIME ft;
401     GetSystemTimeAsFileTime(&ft);
402     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
403     // Converts from 100ns units in 1601 epoch to unix epoch in sec
404     return naNum((t * 1e-7) - 11644473600.0);
405 #else
406     time_t t;
407     struct timeval td;
408     do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
409     return naNum(t + 1e-6 * td.tv_usec);
410 #endif
411
412 }
413
414 // Convert a cartesian point to a geodetic lat/lon/altitude.
415 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
416 {
417     double lat, lon, alt, xyz[3];
418     if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
419     for(int i=0; i<3; i++)
420         xyz[i] = naNumValue(args[i]).num;
421     sgCartToGeod(xyz, &lat, &lon, &alt);
422     lat *= SG_RADIANS_TO_DEGREES;
423     lon *= SG_RADIANS_TO_DEGREES;
424     naRef vec = naNewVector(c);
425     naVec_append(vec, naNum(lat));
426     naVec_append(vec, naNum(lon));
427     naVec_append(vec, naNum(alt));
428     return vec;
429 }
430
431 // Convert a geodetic lat/lon/altitude to a cartesian point.
432 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
433 {
434     if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
435     double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
436     double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
437     double alt = naNumValue(args[2]).num;
438     double xyz[3];
439     sgGeodToCart(lat, lon, alt, xyz);
440     naRef vec = naNewVector(c);
441     naVec_append(vec, naNum(xyz[0]));
442     naVec_append(vec, naNum(xyz[1]));
443     naVec_append(vec, naNum(xyz[2]));
444     return vec;
445 }
446
447 // For given geodetic point return array with elevation, and a material data
448 // hash, or nil if there's no information available (tile not loaded). If
449 // information about the material isn't available, then nil is returned instead
450 // of the hash.
451 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
452 {
453 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
454     if(argc != 2) naRuntimeError(c, "geodinfo() expects 2 arguments: lat, lon");
455     double lat = naNumValue(args[0]).num;
456     double lon = naNumValue(args[1]).num;
457     double elev;
458     const SGMaterial *mat;
459     if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
460         return naNil();
461     naRef vec = naNewVector(c);
462     naVec_append(vec, naNum(elev));
463     naRef matdata = naNil();
464     if(mat) {
465         matdata = naNewHash(c);
466         naRef names = naNewVector(c);
467         const vector<string> n = mat->get_names();
468         for(unsigned int i=0; i<n.size(); i++)
469             naVec_append(names, naStr_fromdata(naNewString(c),
470                     const_cast<char*>(n[i].c_str()), n[i].size()));
471         HASHSET("names", 5, names);
472         HASHSET("solid", 5, naNum(mat->get_solid()));
473         HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
474         HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
475         HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
476         HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
477         HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
478     }
479     naVec_append(vec, matdata);
480     return vec;
481 #undef HASHSET
482 }
483
484 // Table of extension functions.  Terminate with zeros.
485 static struct { char* name; naCFunction func; } funcs[] = {
486     { "getprop",   f_getprop },
487     { "setprop",   f_setprop },
488     { "print",     f_print },
489     { "_fgcommand", f_fgcommand },
490     { "settimer",  f_settimer },
491     { "_setlistener", f_setlistener },
492     { "removelistener", f_removelistener },
493     { "_cmdarg",  f_cmdarg },
494     { "_interpolate",  f_interpolate },
495     { "rand",  f_rand },
496     { "srand",  f_srand },
497     { "directory", f_directory },
498     { "parsexml", f_parsexml },
499     { "systime", f_systime },
500     { "carttogeod", f_carttogeod },
501     { "geodtocart", f_geodtocart },
502     { "geodinfo", f_geodinfo },
503     { 0, 0 }
504 };
505
506 naRef FGNasalSys::cmdArgGhost()
507 {
508     return propNodeGhost(_cmdArg);
509 }
510
511 void FGNasalSys::init()
512 {
513     int i;
514
515     _context = naNewContext();
516
517     // Start with globals.  Add it to itself as a recursive
518     // sub-reference under the name "globals".  This gives client-code
519     // write access to the namespace if someone wants to do something
520     // fancy.
521     _globals = naInit_std(_context);
522     naSave(_context, _globals);
523     hashset(_globals, "globals", _globals);
524
525     hashset(_globals, "math", naInit_math(_context));
526     hashset(_globals, "bits", naInit_bits(_context));
527     hashset(_globals, "io", naInit_io(_context));
528     hashset(_globals, "thread", naInit_thread(_context));
529     hashset(_globals, "utf8", naInit_utf8(_context));
530
531     // Add our custom extension functions:
532     for(i=0; funcs[i].name; i++)
533         hashset(_globals, funcs[i].name,
534                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
535
536     // And our SGPropertyNode wrapper
537     hashset(_globals, "props", genPropsModule());
538
539     // Make a "__gcsave" hash to hold the naRef objects which get
540     // passed to handles outside the interpreter (to protect them from
541     // begin garbage-collected).
542     _gcHash = naNewHash(_context);
543     hashset(_globals, "__gcsave", _gcHash);
544
545     // Now load the various source files in the Nasal directory
546     SGPath p(globals->get_fg_root());
547     p.append("Nasal");
548     ulDirEnt* dent;
549     ulDir* dir = ulOpenDir(p.c_str());
550     while(dir && (dent = ulReadDir(dir)) != 0) {
551         SGPath fullpath(p);
552         fullpath.append(dent->d_name);
553         SGPath file(dent->d_name);
554         if(file.extension() != "nas") continue;
555         loadModule(fullpath, file.base().c_str());
556     }
557     ulCloseDir(dir);
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);
564
565     // Pull scripts out of the property tree, too
566     loadPropertyScripts();
567 }
568
569 void FGNasalSys::update(double)
570 {
571     if(_purgeListeners) {
572         _purgeListeners = false;
573         map<int, FGNasalListener *>::iterator it;
574         for(it = _listener.begin(); it != _listener.end();) {
575             FGNasalListener *nl = it->second;
576             if(nl->_dead) {
577                 _listener.erase(it++);
578                 delete nl;
579             } else {
580                 ++it;
581             }
582         }
583     }
584 }
585
586 // Loads the scripts found under /nasal in the global tree
587 void FGNasalSys::loadPropertyScripts()
588 {
589     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
590     if(!nasal) return;
591
592     for(int i=0; i<nasal->nChildren(); i++) {
593         SGPropertyNode* n = nasal->getChild(i);
594
595         const char* module = n->getName();
596         if(n->hasChild("module"))
597             module = n->getStringValue("module");
598
599         // allow multiple files to be specified within in a single
600         // Nasal module tag
601         int j = 0;
602         SGPropertyNode *fn;
603         bool file_specified = false;
604         while ( (fn = n->getChild("file", j)) != NULL ) {
605             file_specified = true;
606             const char* file = fn->getStringValue();
607             SGPath p(globals->get_fg_root());
608             p.append(file);
609             loadModule(p, module);
610             j++;
611         }
612
613         // Old code which only allowed a single file to be specified per module
614         /*
615         const char* file = n->getStringValue("file");
616         if(!n->hasChild("file")) file = 0; // Hrm...
617         if(file) {
618             SGPath p(globals->get_fg_root());
619             p.append(file);
620             loadModule(p, module);
621         }
622         */
623
624         const char* src = n->getStringValue("script");
625         if(!n->hasChild("script")) src = 0; // Hrm...
626         if(src)
627             createModule(module, n->getPath(), src, strlen(src));
628
629         if(!file_specified && !src)
630             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
631                    "no <file> or <script> defined in " <<
632                    "/nasal/" << module);
633     }
634 }
635
636 // Logs a runtime error, with stack trace, to the FlightGear log stream
637 void FGNasalSys::logError(naContext context)
638 {
639     SG_LOG(SG_NASAL, SG_ALERT,
640            "Nasal runtime error: " << naGetError(context));
641     SG_LOG(SG_NASAL, SG_ALERT,
642            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
643            ", line " << naGetLine(context, 0));
644     for(int i=1; i<naStackDepth(context); i++)
645         SG_LOG(SG_NASAL, SG_ALERT,
646                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
647                ", line " << naGetLine(context, i));
648 }
649
650 // Reads a script file, executes it, and places the resulting
651 // namespace into the global namespace under the specified module
652 // name.
653 void FGNasalSys::loadModule(SGPath file, const char* module)
654 {
655     int len = 0;
656     char* buf = readfile(file.c_str(), &len);
657     if(!buf) {
658         SG_LOG(SG_NASAL, SG_ALERT,
659                "Nasal error: could not read script file " << file.c_str()
660                << " into module " << module);
661         return;
662     }
663
664     createModule(module, file.c_str(), buf, len);
665     delete[] buf;
666 }
667
668 // Parse and run.  Save the local variables namespace, as it will
669 // become a sub-object of globals.  The optional "arg" argument can be
670 // used to pass an associated property node to the module, which can then
671 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
672 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
673                               const char* src, int len, const SGPropertyNode* arg)
674 {
675     naRef code = parse(fileName, src, len);
676     if(naIsNil(code))
677         return;
678
679     // See if we already have a module hash to use.  This allows the
680     // user to, for example, add functions to the built-in math
681     // module.  Make a new one if necessary.
682     naRef locals;
683     naRef modname = naNewString(_context);
684     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
685     if(!naHash_get(_globals, modname, &locals))
686         locals = naNewHash(_context);
687
688     _cmdArg = (SGPropertyNode*)arg;
689
690     call(code, locals);
691     hashset(_globals, moduleName, locals);
692 }
693
694 void FGNasalSys::deleteModule(const char* moduleName)
695 {
696     naRef modname = naNewString(_context);
697     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
698     naHash_delete(_globals, modname);
699 }
700
701 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
702 {
703     int errLine = -1;
704     naRef srcfile = naNewString(_context);
705     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
706     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
707     if(naIsNil(code)) {
708         SG_LOG(SG_NASAL, SG_ALERT,
709                "Nasal parse error: " << naGetError(_context) <<
710                " in "<< filename <<", line " << errLine);
711         return naNil();
712     }
713
714     // Bind to the global namespace before returning
715     return naBindFunction(_context, code, _globals);
716 }
717
718 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
719 {
720     const char* nasal = arg->getStringValue("script");
721     const char* moduleName = arg->getStringValue("module");
722     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
723     if(naIsNil(code)) return false;
724
725     // Commands can be run "in" a module.  Make sure that module
726     // exists, and set it up as the local variables hash for the
727     // command.
728     naRef locals = naNil();
729     if(moduleName[0]) {
730         naRef modname = naNewString(_context);
731         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
732         if(!naHash_get(_globals, modname, &locals)) {
733             locals = naNewHash(_context);
734             naHash_set(_globals, modname, locals);
735         }
736     }
737
738     // Cache this command's argument for inspection via cmdarg().  For
739     // performance reasons, we won't bother with it if the invoked
740     // code doesn't need it.
741     _cmdArg = (SGPropertyNode*)arg;
742
743     call(code, locals);
744     return true;
745 }
746
747 // settimer(func, dt, simtime) extension function.  The first argument
748 // is a Nasal function to call, the second is a delta time (from now),
749 // in seconds.  The third, if present, is a boolean value indicating
750 // that "real world" time (rather than simulator time) is to be used.
751 //
752 // Implementation note: the FGTimer objects don't live inside the
753 // garbage collector, so the Nasal handler functions have to be
754 // "saved" somehow lest they be inadvertently cleaned.  In this case,
755 // they are inserted into a globals.__gcsave hash and removed on
756 // expiration.
757 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
758 {
759     // Extract the handler, delta, and simtime arguments:
760     naRef handler = argc > 0 ? args[0] : naNil();
761     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
762         naRuntimeError(c, "settimer() with invalid function argument");
763         return;
764     }
765
766     naRef delta = argc > 1 ? args[1] : naNil();
767     if(naIsNil(delta)) {
768         naRuntimeError(c, "settimer() with invalid time argument");
769         return;
770     }
771
772     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
773
774     // Generate and register a C++ timer handler
775     NasalTimer* t = new NasalTimer;
776     t->handler = handler;
777     t->gcKey = gcSave(handler);
778     t->nasal = this;
779
780     globals->get_event_mgr()->addEvent("NasalTimer",
781                                        t, &NasalTimer::timerExpired,
782                                        delta.num, simtime);
783 }
784
785 void FGNasalSys::handleTimer(NasalTimer* t)
786 {
787     call(t->handler, naNil());
788     gcRelease(t->gcKey);
789 }
790
791 int FGNasalSys::gcSave(naRef r)
792 {
793     int key = _nextGCKey++;
794     naHash_set(_gcHash, naNum(key), r);
795     return key;
796 }
797
798 void FGNasalSys::gcRelease(int key)
799 {
800     naHash_delete(_gcHash, naNum(key));
801 }
802
803 void FGNasalSys::NasalTimer::timerExpired()
804 {
805     nasal->handleTimer(this);
806     delete this;
807 }
808
809 int FGNasalSys::_listenerId = 0;
810
811 // setlistener(property, func, bool) extension function.  The first argument
812 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
813 // path), the second is a Nasal function, the optional third one a bool.
814 // If the bool is true, then the listener is executed initially. The
815 // setlistener() function returns a unique id number, that can be used
816 // as argument to the removelistener() function.
817 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
818 {
819     SGPropertyNode_ptr node;
820     naRef prop = argc > 0 ? args[0] : naNil();
821     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
822     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
823     else {
824         naRuntimeError(c, "setlistener() with invalid property argument");
825         return naNil();
826     }
827
828     if(node->isTied())
829         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
830                 node->getPath());
831
832     naRef handler = argc > 1 ? args[1] : naNil();
833     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
834         naRuntimeError(c, "setlistener() with invalid function argument");
835         return naNil();
836     }
837
838     bool initial = argc > 2 && naTrue(args[2]);
839
840     FGNasalListener *nl = new FGNasalListener(node, handler, this,
841             gcSave(handler), _listenerId);
842     node->addChangeListener(nl, initial);
843
844     _listener[_listenerId] = nl;
845     return naNum(_listenerId++);
846 }
847
848 // removelistener(int) extension function. The argument is the id of
849 // a listener as returned by the setlistener() function.
850 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
851 {
852     naRef id = argc > 0 ? args[0] : naNil();
853     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
854
855     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
856         naRuntimeError(c, "removelistener() with invalid listener id");
857         return naNil();
858     }
859
860     FGNasalListener *nl = it->second;
861     if(nl->_active) {
862         nl->_dead = true;
863         _purgeListeners = true;
864         return naNum(-1);
865     }
866
867     _listener.erase(it);
868     delete nl;
869     return naNum(_listener.size());
870 }
871
872
873
874 // FGNasalListener class.
875
876 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
877                                  FGNasalSys* nasal, int key, int id) :
878     _node(node),
879     _handler(handler),
880     _gcKey(key),
881     _id(id),
882     _nas(nasal),
883     _active(0),
884     _dead(false)
885 {
886 }
887
888 FGNasalListener::~FGNasalListener()
889 {
890     _node->removeChangeListener(this);
891     _nas->gcRelease(_gcKey);
892 }
893
894 void FGNasalListener::valueChanged(SGPropertyNode* node)
895 {
896     // drop recursive listener calls
897     if(_active || _dead)
898         return;
899
900     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
901     _active++;
902     _nas->_cmdArg = node;
903     _nas->call(_handler, naNil());
904     _active--;
905 }
906
907
908
909
910 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
911 // such a class, then it lets modelLoaded() run the <load> script, and the
912 // destructor the <unload> script. The latter happens when the model branch
913 // is removed from the scene graph.
914
915 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
916                                    osg::Node *)
917 {
918     SGPropertyNode *n = prop->getNode("nasal"), *load;
919     if(!n)
920         return;
921
922     load = n->getNode("load");
923     _unload = n->getNode("unload");
924     if(!load && !_unload)
925         return;
926
927     _module = path;
928     const char *s = load ? load->getStringValue() : "";
929     nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
930 }
931
932 FGNasalModelData::~FGNasalModelData()
933 {
934     if(_module.empty())
935         return;
936
937     if(!nasalSys) {
938         SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
939                 "without Nasal subsystem present.");
940         return;
941     }
942
943     if(_unload) {
944         const char *s = _unload->getStringValue();
945         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
946     }
947     nasalSys->deleteModule(_module.c_str());
948 }
949
950
951
952 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
953 //
954 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
955     _c(naSubContext(c)),
956     _start_element(argc > 1 ? args[1] : naNil()),
957     _end_element(argc > 2 ? args[2] : naNil()),
958     _data(argc > 3 ? args[3] : naNil()),
959     _pi(argc > 4 ? args[4] : naNil())
960 {
961 }
962
963 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
964 {
965     if(naIsNil(_start_element)) return;
966     naRef attr = naNewHash(_c);
967     for(int i=0; i<a.size(); i++) {
968         naRef name = make_string(a.getName(i));
969         naRef value = make_string(a.getValue(i));
970         naHash_set(attr, name, value);
971     }
972     call(_start_element, 2, make_string(tag), attr);
973 }
974
975 void NasalXMLVisitor::endElement(const char* tag)
976 {
977     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
978 }
979
980 void NasalXMLVisitor::data(const char* str, int len)
981 {
982     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
983 }
984
985 void NasalXMLVisitor::pi(const char* target, const char* data)
986 {
987     if (!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
988 }
989
990 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
991 {
992     naRef args[2];
993     args[0] = a;
994     args[1] = b;
995     naCall(_c, func, num, args, naNil(), naNil());
996     if(naGetError(_c))
997         naRethrowError(_c);
998 }
999
1000 naRef NasalXMLVisitor::make_string(const char* s, int n)
1001 {
1002     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1003                           n < 0 ? strlen(s) : n);
1004 }
1005
1006