7 # include <sys/time.h> // gettimeofday
12 #include <sys/types.h>
16 #include <algorithm> // for std::sort
18 #include <simgear/nasal/nasal.h>
19 #include <simgear/props/props.hxx>
20 #include <simgear/math/sg_random.h>
21 #include <simgear/misc/sg_path.hxx>
22 #include <simgear/misc/sg_dir.hxx>
23 #include <simgear/misc/interpolator.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/structure/event_mgr.hxx>
28 #include "NasalSys.hxx"
29 #include "NasalPositioned.hxx"
30 #include "NasalCanvas.hxx"
32 #include <Main/globals.hxx>
33 #include <Main/util.hxx>
34 #include <Main/fg_props.hxx>
38 static FGNasalSys* nasalSys = 0;
40 // Listener class for loading Nasal modules on demand
41 class FGNasalModuleListener : public SGPropertyChangeListener
44 FGNasalModuleListener(SGPropertyNode* node);
46 virtual void valueChanged(SGPropertyNode* node);
49 SGPropertyNode_ptr _node;
52 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
56 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
58 if (_node->getBoolValue("enabled",false)&&
59 !_node->getBoolValue("loaded",true))
61 nasalSys->loadPropertyScripts(_node);
66 // Read and return file contents in a single buffer. Note use of
67 // stat() to get the file size. This is a win32 function, believe it
68 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
69 // Text mode brain damage will kill us if we're trying to do bytewise
71 static char* readfile(const char* file, int* lenOut)
74 if(stat(file, &data) != 0) return 0;
75 FILE* f = fopen(file, "rb");
77 char* buf = new char[data.st_size];
78 *lenOut = fread(buf, 1, data.st_size, f);
80 if(*lenOut != data.st_size) {
81 // Shouldn't happen, but warn anyway since it represents a
82 // platform bug and not a typical runtime error (missing file,
84 SG_LOG(SG_NASAL, SG_ALERT,
85 "ERROR in Nasal initialization: " <<
86 "short count returned from fread() of " << file <<
87 ". Check your C library!");
94 FGNasalSys::FGNasalSys()
100 _nextGCKey = 0; // Any value will do
104 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
106 return callMethod(code, naNil(), argc, args, locals);
109 // Does a naCall() in a new context. Wrapped here to make lock
110 // tracking easier. Extension functions are called with the lock, but
111 // we have to release it before making a new naCall(). So rather than
112 // drop the lock in every extension function that might call back into
113 // Nasal, we keep a stack depth counter here and only unlock/lock
114 // around the naCall if it isn't the first one.
116 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
118 naContext ctx = naNewContext();
119 if(_callCount) naModUnlock();
121 naRef result = naCall(ctx, code, argc, args, self, locals);
125 if(_callCount) naModLock();
130 FGNasalSys::~FGNasalSys()
133 map<int, FGNasalListener *>::iterator it, end = _listener.end();
134 for(it = _listener.begin(); it != end; ++it)
137 naFreeContext(_context);
141 bool FGNasalSys::parseAndRun(const char* sourceCode)
143 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
147 call(code, 0, 0, naNil());
151 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
153 FGNasalScript* script = new FGNasalScript();
154 script->_gcKey = -1; // important, if we delete it on a parse
155 script->_nas = this; // error, don't clobber a real handle!
159 sprintf(buf, "FGNasalScript@%p", (void *)script);
163 script->_code = parse(name, src, strlen(src));
164 if(naIsNil(script->_code)) {
169 script->_gcKey = gcSave(script->_code);
173 // Utility. Sets a named key in a hash by C string, rather than nasal
175 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
177 naRef s = naNewString(_context);
178 naStr_fromdata(s, (char*)key, strlen(key));
179 naHash_set(hash, s, val);
182 // The get/setprop functions accept a *list* of strings and walk
183 // through the property tree with them to find the appropriate node.
184 // This allows a Nasal object to hold onto a property path and use it
185 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
186 // is the utility function that walks the property tree.
187 // Future enhancement: support integer arguments to specify array
189 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
191 SGPropertyNode* p = globals->get_props();
193 for(int i=0; i<len; i++) {
195 if(!naIsString(a)) return 0;
196 p = p->getNode(naStr_data(a));
199 } catch (const string& err) {
200 naRuntimeError(c, (char *)err.c_str());
206 // getprop() extension function. Concatenates its string arguments as
207 // property names and returns the value of the specified property. Or
208 // nil if it doesn't exist.
209 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
211 using namespace simgear;
212 const SGPropertyNode* p = findnode(c, args, argc);
213 if(!p) return naNil();
215 switch(p->getType()) {
216 case props::BOOL: case props::INT:
217 case props::LONG: case props::FLOAT:
220 double dv = p->getDoubleValue();
221 if (osg::isNaN(dv)) {
222 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
230 case props::UNSPECIFIED:
232 naRef nastr = naNewString(c);
233 const char* val = p->getStringValue();
234 naStr_fromdata(nastr, (char*)val, strlen(val));
237 case props::ALIAS: // <--- FIXME, recurse?
243 // setprop() extension function. Concatenates its string arguments as
244 // property names and sets the value of the specified property to the
246 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
249 char buf[BUFLEN + 1];
253 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
254 for(int i=0; i<argc-1; i++) {
255 naRef s = naStringValue(c, args[i]);
256 if(naIsNil(s)) return naNil();
257 strncpy(p, naStr_data(s), buflen);
259 buflen = BUFLEN - (p - buf);
260 if(i < (argc-2) && buflen > 0) {
266 SGPropertyNode* props = globals->get_props();
267 naRef val = args[argc-1];
270 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
272 naRef n = naNumValue(val);
274 naRuntimeError(c, "setprop() value is not string or number");
276 if (osg::isNaN(n.num)) {
277 naRuntimeError(c, "setprop() passed a NaN");
280 result = props->setDoubleValue(buf, n.num);
282 } catch (const string& err) {
283 naRuntimeError(c, (char *)err.c_str());
285 return naNum(result);
289 // print() extension function. Concatenates and prints its arguments
290 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
291 // make sure it appears. Is there better way to do this?
292 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
296 for(int i=0; i<n; i++) {
297 naRef s = naStringValue(c, args[i]);
298 if(naIsNil(s)) continue;
299 buf += naStr_data(s);
301 SG_LOG(SG_NASAL, SG_ALERT, buf);
302 return naNum(buf.length());
305 // fgcommand() extension function. Executes a named command via the
306 // FlightGear command manager. Takes a single property node name as
308 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
310 naRef cmd = argc > 0 ? args[0] : naNil();
311 naRef props = argc > 1 ? args[1] : naNil();
312 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
313 naRuntimeError(c, "bad arguments to fgcommand()");
314 SGPropertyNode_ptr tmp, *node;
316 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
318 tmp = new SGPropertyNode();
321 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
324 // settimer(func, dt, simtime) extension function. Falls through to
325 // FGNasalSys::setTimer(). See there for docs.
326 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
328 nasalSys->setTimer(c, argc, args);
332 // setlistener(func, property, bool) extension function. Falls through to
333 // FGNasalSys::setListener(). See there for docs.
334 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
336 return nasalSys->setListener(c, argc, args);
339 // removelistener(int) extension function. Falls through to
340 // FGNasalSys::removeListener(). See there for docs.
341 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
343 return nasalSys->removeListener(c, argc, args);
346 // Returns a ghost handle to the argument to the currently executing
348 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
350 return nasalSys->cmdArgGhost();
353 // Sets up a property interpolation. The first argument is either a
354 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
355 // interpolate. The second argument is a vector of pairs of
356 // value/delta numbers.
357 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
359 SGPropertyNode* node;
360 naRef prop = argc > 0 ? args[0] : naNil();
361 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
362 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
365 naRef curve = argc > 1 ? args[1] : naNil();
366 if(!naIsVector(curve)) return naNil();
367 int nPoints = naVec_size(curve) / 2;
368 double* values = new double[nPoints];
369 double* deltas = new double[nPoints];
370 for(int i=0; i<nPoints; i++) {
371 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
372 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
375 ((SGInterpolator*)globals->get_subsystem_mgr()
376 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
377 ->interpolate(node, nPoints, values, deltas);
384 // This is a better RNG than the one in the default Nasal distribution
385 // (which is based on the C library rand() implementation). It will
387 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
389 return naNum(sg_random());
392 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
398 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
404 // Return an array listing of all files in a directory
405 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
407 if(argc != 1 || !naIsString(args[0]))
408 naRuntimeError(c, "bad arguments to directory()");
410 simgear::Dir d(SGPath(naStr_data(args[0])));
411 if(!d.exists()) return naNil();
412 naRef result = naNewVector(c);
414 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
415 for (unsigned int i=0; i<paths.size(); ++i) {
416 std::string p = paths[i].file();
417 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
424 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
426 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
428 if(argc != 1 || !naIsString(args[0]))
429 naRuntimeError(c, "bad arguments to resolveDataPath()");
431 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
432 const char* pdata = p.c_str();
433 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
437 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
439 // <path> ... absolute path to an XML file
440 // <start-tag> ... callback function with two args: tag name, attribute hash
441 // <end-tag> ... callback function with one arg: tag name
442 // <data> ... callback function with one arg: data
443 // <pi> ... callback function with two args: target, data
444 // (pi = "processing instruction")
445 // All four callback functions are optional and default to nil.
446 // The function returns nil on error, or the validated file name otherwise.
447 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
449 if(argc < 1 || !naIsString(args[0]))
450 naRuntimeError(c, "parsexml(): path argument missing or not a string");
451 if(argc > 5) argc = 5;
452 for(int i=1; i<argc; i++)
453 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
454 naRuntimeError(c, "parsexml(): callback argument not a function");
456 const char* file = fgValidatePath(naStr_data(args[0]), false);
458 naRuntimeError(c, "parsexml(): reading '%s' denied "
459 "(unauthorized access)", naStr_data(args[0]));
462 std::ifstream input(file);
463 NasalXMLVisitor visitor(c, argc, args);
465 readXML(input, visitor);
466 } catch (const sg_exception& e) {
467 naRuntimeError(c, "parsexml(): file '%s' %s",
468 file, e.getFormattedMessage().c_str());
471 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
474 // Return UNIX epoch time in seconds.
475 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
479 GetSystemTimeAsFileTime(&ft);
480 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
481 // Converts from 100ns units in 1601 epoch to unix epoch in sec
482 return naNum((t * 1e-7) - 11644473600.0);
485 gettimeofday(&td, 0);
486 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
490 // Table of extension functions. Terminate with zeros.
491 static struct { const char* name; naCFunction func; } funcs[] = {
492 { "getprop", f_getprop },
493 { "setprop", f_setprop },
494 { "print", f_print },
495 { "_fgcommand", f_fgcommand },
496 { "settimer", f_settimer },
497 { "_setlistener", f_setlistener },
498 { "removelistener", f_removelistener },
499 { "_cmdarg", f_cmdarg },
500 { "_interpolate", f_interpolate },
502 { "srand", f_srand },
503 { "abort", f_abort },
504 { "directory", f_directory },
505 { "resolvepath", f_resolveDataPath },
506 { "parsexml", f_parsexml },
507 { "systime", f_systime },
511 naRef FGNasalSys::cmdArgGhost()
513 return propNodeGhost(_cmdArg);
516 void FGNasalSys::init()
520 _context = naNewContext();
522 // Start with globals. Add it to itself as a recursive
523 // sub-reference under the name "globals". This gives client-code
524 // write access to the namespace if someone wants to do something
526 _globals = naInit_std(_context);
527 naSave(_context, _globals);
528 hashset(_globals, "globals", _globals);
530 hashset(_globals, "math", naInit_math(_context));
531 hashset(_globals, "bits", naInit_bits(_context));
532 hashset(_globals, "io", naInit_io(_context));
533 hashset(_globals, "thread", naInit_thread(_context));
534 hashset(_globals, "utf8", naInit_utf8(_context));
536 // Add our custom extension functions:
537 for(i=0; funcs[i].name; i++)
538 hashset(_globals, funcs[i].name,
539 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
543 // And our SGPropertyNode wrapper
544 hashset(_globals, "props", genPropsModule());
546 // Make a "__gcsave" hash to hold the naRef objects which get
547 // passed to handles outside the interpreter (to protect them from
548 // begin garbage-collected).
549 _gcHash = naNewHash(_context);
550 hashset(_globals, "__gcsave", _gcHash);
552 initNasalPositioned(_globals, _context, _gcHash);
553 initNasalCanvas(_globals, _context, _gcHash);
555 // Now load the various source files in the Nasal directory
556 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
557 loadScriptDirectory(nasalDir);
559 // Add modules in Nasal subdirectories to property tree
560 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
561 simgear::Dir::NO_DOT_OR_DOTDOT, "");
562 for (unsigned int i=0; i<directories.size(); ++i) {
563 simgear::Dir dir(directories[i]);
564 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
565 addModule(directories[i].file(), scripts);
568 // set signal and remove node to avoid restoring at reinit
569 const char *s = "nasal-dir-initialized";
570 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
571 signal->setBoolValue(s, true);
572 signal->removeChildren(s, false);
574 // Pull scripts out of the property tree, too
575 loadPropertyScripts();
577 // now Nasal modules are loaded, we can do some delayed work
578 postinitNasalPositioned(_globals, _context);
581 void FGNasalSys::update(double)
583 if(!_dead_listener.empty()) {
584 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
585 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
586 _dead_listener.clear();
589 if (!_loadList.empty())
591 // process Nasal load hook (only one per update loop to avoid excessive lags)
592 _loadList.pop()->load();
595 if (!_unloadList.empty())
597 // process pending Nasal unload hooks after _all_ load hooks were processed
598 // (only unload one per update loop to avoid excessive lags)
599 _unloadList.pop()->unload();
602 // The global context is a legacy thing. We use dynamically
603 // created contexts for naCall() now, so that we can call them
604 // recursively. But there are still spots that want to use it for
605 // naNew*() calls, which end up leaking memory because the context
606 // only clears out its temporary vector when it's *used*. So just
607 // junk it and fetch a new/reinitialized one every frame. This is
608 // clumsy: the right solution would use the dynamic context in all
609 // cases and eliminate _context entirely. But that's more work,
610 // and this works fine (yes, they say "New" and "Free", but
611 // they're very fast, just trust me). -Andy
612 naFreeContext(_context);
613 _context = naNewContext();
616 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
618 return p1.file() < p2.file();
621 // Loads all scripts in given directory
622 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
624 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
625 // sort scripts, avoid loading sequence effects due to file system's
626 // random directory order
627 std::sort(scripts.begin(), scripts.end(), pathSortPredicate);
629 for (unsigned int i=0; i<scripts.size(); ++i) {
630 SGPath fullpath(scripts[i]);
631 SGPath file = fullpath.file();
632 loadModule(fullpath, file.base().c_str());
636 // Create module with list of scripts
637 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
639 if (scripts.size()>0)
641 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
642 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
643 for (unsigned int i=0; i<scripts.size(); ++i) {
644 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
645 pFileNode->setStringValue(scripts[i].c_str());
647 if (!module_node->hasChild("enabled",0))
649 SGPropertyNode* node = module_node->getChild("enabled",0,true);
650 node->setBoolValue(true);
651 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
656 // Loads the scripts found under /nasal in the global tree
657 void FGNasalSys::loadPropertyScripts()
659 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
662 for(int i=0; i<nasal->nChildren(); i++)
664 SGPropertyNode* n = nasal->getChild(i);
665 loadPropertyScripts(n);
669 // Loads the scripts found under /nasal in the global tree
670 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
672 bool is_loaded = false;
674 const char* module = n->getName();
675 if(n->hasChild("module"))
676 module = n->getStringValue("module");
677 if (n->getBoolValue("enabled",true))
679 // allow multiple files to be specified within a single
683 bool file_specified = false;
685 while((fn = n->getChild("file", j)) != NULL) {
686 file_specified = true;
687 const char* file = fn->getStringValue();
689 if (!p.isAbsolute() || !p.exists())
691 p = globals->resolve_maybe_aircraft_path(file);
694 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
695 file << "' for module '" << module << "'.");
698 ok &= p.isNull() ? false : loadModule(p, module);
702 const char* src = n->getStringValue("script");
703 if(!n->hasChild("script")) src = 0; // Hrm...
705 createModule(module, n->getPath().c_str(), src, strlen(src));
707 if(!file_specified && !src)
709 // module no longer exists - clear the archived "enable" flag
710 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
711 SGPropertyNode* node = n->getChild("enabled",0,false);
713 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
715 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
716 "no <file> or <script> defined in " <<
717 "/nasal/" << module);
724 SGPropertyNode* enable = n->getChild("enabled");
727 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
728 enable->addChangeListener(listener, false);
731 SGPropertyNode* loaded = n->getChild("loaded",0,true);
732 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
733 loaded->setBoolValue(is_loaded);
736 // Logs a runtime error, with stack trace, to the FlightGear log stream
737 void FGNasalSys::logError(naContext context)
739 SG_LOG(SG_NASAL, SG_ALERT,
740 "Nasal runtime error: " << naGetError(context));
741 SG_LOG(SG_NASAL, SG_ALERT,
742 " at " << naStr_data(naGetSourceFile(context, 0)) <<
743 ", line " << naGetLine(context, 0));
744 for(int i=1; i<naStackDepth(context); i++)
745 SG_LOG(SG_NASAL, SG_ALERT,
746 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
747 ", line " << naGetLine(context, i));
750 // Reads a script file, executes it, and places the resulting
751 // namespace into the global namespace under the specified module
753 bool FGNasalSys::loadModule(SGPath file, const char* module)
756 char* buf = readfile(file.c_str(), &len);
758 SG_LOG(SG_NASAL, SG_ALERT,
759 "Nasal error: could not read script file " << file.c_str()
760 << " into module " << module);
764 bool ok = createModule(module, file.c_str(), buf, len);
769 // Parse and run. Save the local variables namespace, as it will
770 // become a sub-object of globals. The optional "arg" argument can be
771 // used to pass an associated property node to the module, which can then
772 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
773 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
774 const char* src, int len,
775 const SGPropertyNode* cmdarg,
776 int argc, naRef* args)
778 naRef code = parse(fileName, src, len);
782 // See if we already have a module hash to use. This allows the
783 // user to, for example, add functions to the built-in math
784 // module. Make a new one if necessary.
786 naRef modname = naNewString(_context);
787 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
788 if(!naHash_get(_globals, modname, &locals))
789 locals = naNewHash(_context);
791 _cmdArg = (SGPropertyNode*)cmdarg;
793 call(code, argc, args, locals);
794 hashset(_globals, moduleName, locals);
798 void FGNasalSys::deleteModule(const char* moduleName)
800 naRef modname = naNewString(_context);
801 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
802 naHash_delete(_globals, modname);
805 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
808 naRef srcfile = naNewString(_context);
809 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
810 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
812 SG_LOG(SG_NASAL, SG_ALERT,
813 "Nasal parse error: " << naGetError(_context) <<
814 " in "<< filename <<", line " << errLine);
818 // Bind to the global namespace before returning
819 return naBindFunction(_context, code, _globals);
822 bool FGNasalSys::handleCommand( const char* moduleName,
823 const char* fileName,
825 const SGPropertyNode* arg )
827 naRef code = parse(fileName, src, strlen(src));
828 if(naIsNil(code)) return false;
830 // Commands can be run "in" a module. Make sure that module
831 // exists, and set it up as the local variables hash for the
833 naRef locals = naNil();
835 naRef modname = naNewString(_context);
836 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
837 if(!naHash_get(_globals, modname, &locals)) {
838 locals = naNewHash(_context);
839 naHash_set(_globals, modname, locals);
843 // Cache this command's argument for inspection via cmdarg(). For
844 // performance reasons, we won't bother with it if the invoked
845 // code doesn't need it.
846 _cmdArg = (SGPropertyNode*)arg;
848 call(code, 0, 0, locals);
852 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
854 const char* src = arg->getStringValue("script");
855 const char* moduleName = arg->getStringValue("module");
857 return handleCommand( moduleName,
858 arg ? arg->getPath(true).c_str() : moduleName,
863 // settimer(func, dt, simtime) extension function. The first argument
864 // is a Nasal function to call, the second is a delta time (from now),
865 // in seconds. The third, if present, is a boolean value indicating
866 // that "real world" time (rather than simulator time) is to be used.
868 // Implementation note: the FGTimer objects don't live inside the
869 // garbage collector, so the Nasal handler functions have to be
870 // "saved" somehow lest they be inadvertently cleaned. In this case,
871 // they are inserted into a globals.__gcsave hash and removed on
873 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
875 // Extract the handler, delta, and simtime arguments:
876 naRef handler = argc > 0 ? args[0] : naNil();
877 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
878 naRuntimeError(c, "settimer() with invalid function argument");
882 naRef delta = argc > 1 ? args[1] : naNil();
884 naRuntimeError(c, "settimer() with invalid time argument");
888 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
890 // Generate and register a C++ timer handler
891 NasalTimer* t = new NasalTimer;
892 t->handler = handler;
893 t->gcKey = gcSave(handler);
896 globals->get_event_mgr()->addEvent("NasalTimer",
897 t, &NasalTimer::timerExpired,
901 void FGNasalSys::handleTimer(NasalTimer* t)
903 call(t->handler, 0, 0, naNil());
907 int FGNasalSys::gcSave(naRef r)
909 int key = _nextGCKey++;
910 naHash_set(_gcHash, naNum(key), r);
914 void FGNasalSys::gcRelease(int key)
916 naHash_delete(_gcHash, naNum(key));
919 void FGNasalSys::NasalTimer::timerExpired()
921 nasal->handleTimer(this);
925 int FGNasalSys::_listenerId = 0;
927 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
928 // Attaches a callback function to a property (specified as a global
929 // property path string or a SGPropertyNode_ptr* ghost). If the third,
930 // optional argument (default=0) is set to 1, then the function is also
931 // called initially. If the fourth, optional argument is set to 0, then the
932 // function is only called when the property node value actually changes.
933 // Otherwise it's called independent of the value whenever the node is
934 // written to (default). The setlistener() function returns a unique
935 // id number, which is to be used as argument to the removelistener()
937 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
939 SGPropertyNode_ptr node;
940 naRef prop = argc > 0 ? args[0] : naNil();
941 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
942 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
944 naRuntimeError(c, "setlistener() with invalid property argument");
949 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
952 naRef code = argc > 1 ? args[1] : naNil();
953 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
954 naRuntimeError(c, "setlistener() with invalid function argument");
958 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
959 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
960 FGNasalListener *nl = new FGNasalListener(node, code, this,
961 gcSave(code), _listenerId, init, type);
963 node->addChangeListener(nl, init != 0);
965 _listener[_listenerId] = nl;
966 return naNum(_listenerId++);
969 // removelistener(int) extension function. The argument is the id of
970 // a listener as returned by the setlistener() function.
971 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
973 naRef id = argc > 0 ? args[0] : naNil();
974 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
976 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
977 naRuntimeError(c, "removelistener() with invalid listener id");
981 it->second->_dead = true;
982 _dead_listener.push_back(it->second);
984 return naNum(_listener.size());
989 // FGNasalListener class.
991 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
992 FGNasalSys* nasal, int key, int id,
993 int init, int type) :
1006 if(_type == 0 && !_init)
1010 FGNasalListener::~FGNasalListener()
1012 _node->removeChangeListener(this);
1013 _nas->gcRelease(_gcKey);
1016 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1018 if(_active || _dead) return;
1019 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1022 arg[0] = _nas->propNodeGhost(which);
1023 arg[1] = _nas->propNodeGhost(_node);
1024 arg[2] = mode; // value changed, child added/removed
1025 arg[3] = naNum(_node != which); // child event?
1026 _nas->call(_code, 4, arg, naNil());
1030 void FGNasalListener::valueChanged(SGPropertyNode* node)
1032 if(_type < 2 && node != _node) return; // skip child events
1033 if(_type > 0 || changed(_node) || _init)
1034 call(node, naNum(0));
1039 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1041 if(_type == 2) call(child, naNum(1));
1044 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1046 if(_type == 2) call(child, naNum(-1));
1049 bool FGNasalListener::changed(SGPropertyNode* node)
1051 using namespace simgear;
1052 props::Type type = node->getType();
1053 if(type == props::NONE) return false;
1054 if(type == props::UNSPECIFIED) return true;
1062 long l = node->getLongValue();
1063 result = l != _last_int;
1070 double d = node->getDoubleValue();
1071 result = d != _last_float;
1077 string s = node->getStringValue();
1078 result = s != _last_string;
1087 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1088 // such a class, then it lets modelLoaded() run the <load> script, and the
1089 // destructor the <unload> script. The latter happens when the model branch
1090 // is removed from the scene graph.
1092 unsigned int FGNasalModelData::_module_id = 0;
1094 void FGNasalModelData::load()
1096 std::stringstream m;
1097 m << "__model" << _module_id++;
1100 SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1102 const char *s = _load ? _load->getStringValue() : "";
1105 arg[0] = nasalSys->propNodeGhost(_root);
1106 arg[1] = nasalSys->propNodeGhost(_prop);
1107 nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1111 void FGNasalModelData::unload()
1113 if (_module.empty())
1117 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1118 "without Nasal subsystem present.");
1122 SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1126 const char *s = _unload->getStringValue();
1127 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1130 nasalSys->deleteModule(_module.c_str());
1133 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1137 SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1138 "without Nasal subsystem present.");
1145 SGPropertyNode *nasal = prop->getNode("nasal");
1149 SGPropertyNode* load = nasal->getNode("load");
1150 SGPropertyNode* unload = nasal->getNode("unload");
1152 if ((!load) && (!unload))
1155 _data = new FGNasalModelData(_root, path, prop, load, unload);
1157 // register Nasal module to be created and loaded in the main thread.
1158 nasalSys->registerToLoad(_data);
1161 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1163 // when necessary, register Nasal module to be destroyed/unloaded
1164 // in the main thread.
1165 if ((_data.valid())&&(nasalSys))
1166 nasalSys->registerToUnload(_data);
1169 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1171 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1172 _c(naSubContext(c)),
1173 _start_element(argc > 1 ? args[1] : naNil()),
1174 _end_element(argc > 2 ? args[2] : naNil()),
1175 _data(argc > 3 ? args[3] : naNil()),
1176 _pi(argc > 4 ? args[4] : naNil())
1180 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1182 if(naIsNil(_start_element)) return;
1183 naRef attr = naNewHash(_c);
1184 for(int i=0; i<a.size(); i++) {
1185 naRef name = make_string(a.getName(i));
1186 naRef value = make_string(a.getValue(i));
1187 naHash_set(attr, name, value);
1189 call(_start_element, 2, make_string(tag), attr);
1192 void NasalXMLVisitor::endElement(const char* tag)
1194 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1197 void NasalXMLVisitor::data(const char* str, int len)
1199 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1202 void NasalXMLVisitor::pi(const char* target, const char* data)
1204 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1207 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1212 naCall(_c, func, num, args, naNil(), naNil());
1217 naRef NasalXMLVisitor::make_string(const char* s, int n)
1219 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1220 n < 0 ? strlen(s) : n);