7 # include <sys/time.h> // gettimeofday
12 #include <sys/types.h>
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>
27 #include <Main/globals.hxx>
28 #include <Main/fg_props.hxx>
29 #include <Scenery/scenery.hxx>
31 #include "NasalSys.hxx"
33 static FGNasalSys* nasalSys = 0;
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
41 static char* readfile(const char* file, int* lenOut)
44 if(stat(file, &data) != 0) return 0;
45 FILE* f = fopen(file, "rb");
47 char* buf = new char[data.st_size];
48 *lenOut = fread(buf, 1, data.st_size, 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,
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!");
64 FGNasalSys::FGNasalSys()
70 _nextGCKey = 0; // Any value will do
72 _purgeListeners = false;
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)
83 naContext ctx = naNewContext();
84 if(_callCount) naModUnlock();
86 naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
90 if(_callCount) naModLock();
95 FGNasalSys::~FGNasalSys()
98 map<int, FGNasalListener *>::iterator it, end = _listener.end();
99 for(it = _listener.begin(); it != end; ++it)
102 naFreeContext(_context);
106 bool FGNasalSys::parseAndRun(const char* sourceCode)
108 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
116 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
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!
124 sprintf(buf, "FGNasalScript@%p", (void *)script);
128 script->_code = parse(name, src, strlen(src));
129 if(naIsNil(script->_code)) {
134 script->_gcKey = gcSave(script->_code);
138 // Utility. Sets a named key in a hash by C string, rather than nasal
140 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
142 naRef s = naNewString(_context);
143 naStr_fromdata(s, (char*)key, strlen(key));
144 naHash_set(hash, s, val);
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
154 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
156 SGPropertyNode* p = globals->get_props();
158 for(int i=0; i<len; i++) {
160 if(!naIsString(a)) return 0;
161 p = p->getNode(naStr_data(a));
164 } catch (const string& err) {
165 naRuntimeError(c, (char *)err.c_str());
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)
176 const SGPropertyNode* p = findnode(c, args, argc);
177 if(!p) return naNil();
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());
185 case SGPropertyNode::STRING:
186 case SGPropertyNode::UNSPECIFIED:
188 naRef nastr = naNewString(c);
189 const char* val = p->getStringValue();
190 naStr_fromdata(nastr, (char*)val, strlen(val));
193 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
199 // setprop() extension function. Concatenates its string arguments as
200 // property names and sets the value of the specified property to the
202 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
205 char buf[BUFLEN + 1];
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);
214 buflen = BUFLEN - (p - buf);
215 if(i < (argc-2) && buflen > 0) {
221 SGPropertyNode* props = globals->get_props();
222 naRef val = args[argc-1];
224 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
226 naRef n = naNumValue(val);
228 naRuntimeError(c, "setprop() value is not string or number");
229 props->setDoubleValue(buf, n.num);
231 } catch (const string& err) {
232 naRuntimeError(c, (char *)err.c_str());
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)
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);
250 SG_LOG(SG_GENERAL, SG_ALERT, buf);
251 return naNum(buf.length());
254 // fgcommand() extension function. Executes a named command via the
255 // FlightGear command manager. Takes a single property node name as
257 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
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;
265 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
267 tmp = new SGPropertyNode();
270 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
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)
277 nasalSys->setTimer(c, argc, args);
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)
285 return nasalSys->setListener(c, argc, args);
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)
292 return nasalSys->removeListener(c, argc, args);
295 // Returns a ghost handle to the argument to the currently executing
297 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
299 return nasalSys->cmdArgGhost();
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)
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);
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;
324 ((SGInterpolator*)globals->get_subsystem_mgr()
325 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
326 ->interpolate(node, nPoints, values, deltas);
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
334 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
336 return naNum(sg_random());
339 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
345 // Return an array listing of all files in a directory
346 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
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);
355 while((dent = ulReadDir(dir)))
356 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
357 strlen(dent->d_name)));
363 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
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)
375 if(argc < 1 || !naIsString(args[0]))
376 naRuntimeError(c, "bad/missing argument to parsexml()");
378 const char* file = naStr_data(args[0]);
379 std::ifstream input(file);
380 NasalXMLVisitor visitor(c, argc, args);
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());
392 // Return UNIX epoch time in seconds.
393 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
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);
404 do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
405 return naNum(t + 1e-6 * td.tv_usec);
410 // Convert a cartesian point to a geodetic lat/lon/altitude.
411 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
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);
421 naRef vec = naNewVector(c);
422 naVec_append(vec, naNum(lat));
423 naVec_append(vec, naNum(lon));
424 naVec_append(vec, naNum(alt));
428 // Convert a geodetic lat/lon/altitude to a cartesian point.
429 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
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;
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]));
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
449 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
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;
456 const SGMaterial *mat;
457 if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
459 naRef vec = naNewVector(c);
460 naVec_append(vec, naNum(elev));
461 naRef matdata = naNil();
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()));
477 naVec_append(vec, matdata);
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 },
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 },
504 naRef FGNasalSys::cmdArgGhost()
506 return propNodeGhost(_cmdArg);
509 void FGNasalSys::init()
513 _context = naNewContext();
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
519 _globals = naInit_std(_context);
520 naSave(_context, _globals);
521 hashset(_globals, "globals", _globals);
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));
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)));
534 // And our SGPropertyNode wrapper
535 hashset(_globals, "props", genPropsModule());
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);
543 // Now load the various source files in the Nasal directory
544 SGPath p(globals->get_fg_root());
547 ulDir* dir = ulOpenDir(p.c_str());
548 while(dir && (dent = ulReadDir(dir)) != 0) {
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());
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);
563 // Pull scripts out of the property tree, too
564 loadPropertyScripts();
567 void FGNasalSys::update(double)
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;
575 _listener.erase(it++);
584 // Loads the scripts found under /nasal in the global tree
585 void FGNasalSys::loadPropertyScripts()
587 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
590 for(int i=0; i<nasal->nChildren(); i++) {
591 SGPropertyNode* n = nasal->getChild(i);
593 const char* module = n->getName();
594 if(n->hasChild("module"))
595 module = n->getStringValue("module");
597 // allow multiple files to be specified within in a single
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());
607 loadModule(p, module);
611 // Old code which only allowed a single file to be specified per module
613 const char* file = n->getStringValue("file");
614 if(!n->hasChild("file")) file = 0; // Hrm...
616 SGPath p(globals->get_fg_root());
618 loadModule(p, module);
622 const char* src = n->getStringValue("script");
623 if(!n->hasChild("script")) src = 0; // Hrm...
625 createModule(module, n->getPath(), src, strlen(src));
627 if(!file_specified && !src)
628 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
629 "no <file> or <script> defined in " <<
630 "/nasal/" << module);
634 // Logs a runtime error, with stack trace, to the FlightGear log stream
635 void FGNasalSys::logError(naContext context)
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));
648 // Reads a script file, executes it, and places the resulting
649 // namespace into the global namespace under the specified module
651 void FGNasalSys::loadModule(SGPath file, const char* module)
654 char* buf = readfile(file.c_str(), &len);
656 SG_LOG(SG_NASAL, SG_ALERT,
657 "Nasal error: could not read script file " << file.c_str()
658 << " into module " << module);
662 createModule(module, file.c_str(), buf, len);
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)
673 naRef code = parse(fileName, src, len);
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.
681 naRef modname = naNewString(_context);
682 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
683 if(!naHash_get(_globals, modname, &locals))
684 locals = naNewHash(_context);
686 _cmdArg = (SGPropertyNode*)arg;
689 hashset(_globals, moduleName, locals);
692 void FGNasalSys::deleteModule(const char* moduleName)
694 naRef modname = naNewString(_context);
695 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
696 naHash_delete(_globals, modname);
699 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
702 naRef srcfile = naNewString(_context);
703 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
704 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
706 SG_LOG(SG_NASAL, SG_ALERT,
707 "Nasal parse error: " << naGetError(_context) <<
708 " in "<< filename <<", line " << errLine);
712 // Bind to the global namespace before returning
713 return naBindFunction(_context, code, _globals);
716 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
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;
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
726 naRef locals = naNil();
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);
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;
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.
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
755 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
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");
764 naRef delta = argc > 1 ? args[1] : naNil();
766 naRuntimeError(c, "settimer() with invalid time argument");
770 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
772 // Generate and register a C++ timer handler
773 NasalTimer* t = new NasalTimer;
774 t->handler = handler;
775 t->gcKey = gcSave(handler);
778 globals->get_event_mgr()->addEvent("NasalTimer",
779 t, &NasalTimer::timerExpired,
783 void FGNasalSys::handleTimer(NasalTimer* t)
785 call(t->handler, naNil());
789 int FGNasalSys::gcSave(naRef r)
791 int key = _nextGCKey++;
792 naHash_set(_gcHash, naNum(key), r);
796 void FGNasalSys::gcRelease(int key)
798 naHash_delete(_gcHash, naNum(key));
801 void FGNasalSys::NasalTimer::timerExpired()
803 nasal->handleTimer(this);
807 int FGNasalSys::_listenerId = 0;
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)
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);
822 naRuntimeError(c, "setlistener() with invalid property argument");
827 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
830 naRef handler = argc > 1 ? args[1] : naNil();
831 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
832 naRuntimeError(c, "setlistener() with invalid function argument");
836 bool initial = argc > 2 && naTrue(args[2]);
838 FGNasalListener *nl = new FGNasalListener(node, handler, this,
839 gcSave(handler), _listenerId);
840 node->addChangeListener(nl, initial);
842 _listener[_listenerId] = nl;
843 return naNum(_listenerId++);
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)
850 naRef id = argc > 0 ? args[0] : naNil();
851 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
853 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
854 naRuntimeError(c, "removelistener() with invalid listener id");
858 FGNasalListener *nl = it->second;
861 _purgeListeners = true;
867 return naNum(_listener.size());
872 // FGNasalListener class.
874 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
875 FGNasalSys* nasal, int key, int id) :
886 FGNasalListener::~FGNasalListener()
888 _node->removeChangeListener(this);
889 _nas->gcRelease(_gcKey);
892 void FGNasalListener::valueChanged(SGPropertyNode* node)
894 // drop recursive listener calls
898 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
900 _nas->_cmdArg = node;
901 _nas->call(_handler, naNil());
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.
913 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
916 SGPropertyNode *n = prop->getNode("nasal"), *load;
920 load = n->getNode("load");
921 _unload = n->getNode("unload");
922 if(!load && !_unload)
926 const char *s = load ? load->getStringValue() : "";
927 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
930 FGNasalModelData::~FGNasalModelData()
936 SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
937 "without Nasal subsystem present.");
942 const char *s = _unload->getStringValue();
943 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
945 nasalSys->deleteModule(_module.c_str());
950 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
952 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
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())
961 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
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);
970 call(_start_element, 2, make_string(tag), attr);
973 void NasalXMLVisitor::endElement(const char* tag)
975 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
978 void NasalXMLVisitor::data(const char* str, int len)
980 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
983 void NasalXMLVisitor::pi(const char* target, const char* data)
985 if (!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
988 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
992 naCall(_c, func, num, _arg, naNil(), naNil());
997 naRef NasalXMLVisitor::make_string(const char* s, int n)
999 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1000 n < 0 ? strlen(s) : n);