10 #ifdef HAVE_SYS_TIME_H
11 # include <sys/time.h> // gettimeofday
16 #include <sys/types.h>
21 #include <simgear/nasal/nasal.h>
22 #include <simgear/props/props.hxx>
23 #include <simgear/math/sg_random.h>
24 #include <simgear/misc/sg_path.hxx>
25 #include <simgear/misc/sg_dir.hxx>
26 #include <simgear/misc/interpolator.hxx>
27 #include <simgear/structure/commands.hxx>
28 #include <simgear/math/sg_geodesy.hxx>
29 #include <simgear/structure/event_mgr.hxx>
30 #include <simgear/debug/BufferedLogCallback.hxx>
32 #include "NasalSys.hxx"
33 #include "NasalPositioned.hxx"
34 #include "NasalCanvas.hxx"
35 #include "NasalClipboard.hxx"
36 #include "NasalCondition.hxx"
37 #include "NasalString.hxx"
39 #include <Main/globals.hxx>
40 #include <Main/util.hxx>
41 #include <Main/fg_props.hxx>
46 void postinitNasalGUI(naRef globals, naContext c);
48 static FGNasalSys* nasalSys = 0;
50 // Listener class for loading Nasal modules on demand
51 class FGNasalModuleListener : public SGPropertyChangeListener
54 FGNasalModuleListener(SGPropertyNode* node);
56 virtual void valueChanged(SGPropertyNode* node);
59 SGPropertyNode_ptr _node;
62 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
66 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
68 if (_node->getBoolValue("enabled",false)&&
69 !_node->getBoolValue("loaded",true))
71 nasalSys->loadPropertyScripts(_node);
76 // Read and return file contents in a single buffer. Note use of
77 // stat() to get the file size. This is a win32 function, believe it
78 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
79 // Text mode brain damage will kill us if we're trying to do bytewise
81 static char* readfile(const char* file, int* lenOut)
84 if(stat(file, &data) != 0) return 0;
85 FILE* f = fopen(file, "rb");
87 char* buf = new char[data.st_size];
88 *lenOut = fread(buf, 1, data.st_size, f);
90 if(*lenOut != data.st_size) {
91 // Shouldn't happen, but warn anyway since it represents a
92 // platform bug and not a typical runtime error (missing file,
94 SG_LOG(SG_NASAL, SG_ALERT,
95 "ERROR in Nasal initialization: " <<
96 "short count returned from fread() of " << file <<
97 ". Check your C library!");
104 FGNasalSys::FGNasalSys()
111 _nextGCKey = 0; // Any value will do
114 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
115 _log->truncateAt(255);
116 sglog().addCallback(_log);
119 // Utility. Sets a named key in a hash by C string, rather than nasal
121 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
123 naRef s = naNewString(_context);
124 naStr_fromdata(s, (char*)key, strlen(key));
125 naHash_set(hash, s, val);
128 void FGNasalSys::globalsSet(const char* key, naRef val)
130 hashset(_globals, key, val);
133 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
135 return callMethod(code, naNil(), argc, args, locals);
138 // Does a naCall() in a new context. Wrapped here to make lock
139 // tracking easier. Extension functions are called with the lock, but
140 // we have to release it before making a new naCall(). So rather than
141 // drop the lock in every extension function that might call back into
142 // Nasal, we keep a stack depth counter here and only unlock/lock
143 // around the naCall if it isn't the first one.
145 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
147 naContext ctx = naNewContext();
148 if(_callCount) naModUnlock();
150 naRef result = naCall(ctx, code, argc, args, self, locals);
154 if(_callCount) naModLock();
159 FGNasalSys::~FGNasalSys()
162 map<int, FGNasalListener *>::iterator it, end = _listener.end();
163 for(it = _listener.begin(); it != end; ++it)
166 naFreeContext(_context);
171 bool FGNasalSys::parseAndRun(const char* sourceCode)
173 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
177 call(code, 0, 0, naNil());
181 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
183 FGNasalScript* script = new FGNasalScript();
184 script->_gcKey = -1; // important, if we delete it on a parse
185 script->_nas = this; // error, don't clobber a real handle!
189 sprintf(buf, "FGNasalScript@%p", (void *)script);
193 script->_code = parse(name, src, strlen(src));
194 if(naIsNil(script->_code)) {
199 script->_gcKey = gcSave(script->_code);
203 // The get/setprop functions accept a *list* of strings and walk
204 // through the property tree with them to find the appropriate node.
205 // This allows a Nasal object to hold onto a property path and use it
206 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
207 // is the utility function that walks the property tree.
208 // Future enhancement: support integer arguments to specify array
210 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
212 SGPropertyNode* p = globals->get_props();
214 for(int i=0; i<len; i++) {
216 if(!naIsString(a)) return 0;
217 p = p->getNode(naStr_data(a));
220 } catch (const string& err) {
221 naRuntimeError(c, (char *)err.c_str());
227 // getprop() extension function. Concatenates its string arguments as
228 // property names and returns the value of the specified property. Or
229 // nil if it doesn't exist.
230 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
232 using namespace simgear;
233 const SGPropertyNode* p = findnode(c, args, argc);
234 if(!p) return naNil();
236 switch(p->getType()) {
237 case props::BOOL: case props::INT:
238 case props::LONG: case props::FLOAT:
241 double dv = p->getDoubleValue();
242 if (SGMisc<double>::isNaN(dv)) {
243 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
251 case props::UNSPECIFIED:
253 naRef nastr = naNewString(c);
254 const char* val = p->getStringValue();
255 naStr_fromdata(nastr, (char*)val, strlen(val));
258 case props::ALIAS: // <--- FIXME, recurse?
264 // setprop() extension function. Concatenates its string arguments as
265 // property names and sets the value of the specified property to the
267 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
270 char buf[BUFLEN + 1];
274 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
275 for(int i=0; i<argc-1; i++) {
276 naRef s = naStringValue(c, args[i]);
277 if(naIsNil(s)) return naNil();
278 strncpy(p, naStr_data(s), buflen);
280 buflen = BUFLEN - (p - buf);
281 if(i < (argc-2) && buflen > 0) {
287 SGPropertyNode* props = globals->get_props();
288 naRef val = args[argc-1];
291 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
293 naRef n = naNumValue(val);
295 naRuntimeError(c, "setprop() value is not string or number");
297 if (SGMisc<double>::isNaN(n.num)) {
298 naRuntimeError(c, "setprop() passed a NaN");
301 result = props->setDoubleValue(buf, n.num);
303 } catch (const string& err) {
304 naRuntimeError(c, (char *)err.c_str());
306 return naNum(result);
310 // print() extension function. Concatenates and prints its arguments
311 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
312 // make sure it appears. Is there better way to do this?
313 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
317 for(int i=0; i<n; i++) {
318 naRef s = naStringValue(c, args[i]);
319 if(naIsNil(s)) continue;
320 buf += naStr_data(s);
322 SG_LOG(SG_NASAL, SG_ALERT, buf);
323 return naNum(buf.length());
326 // logprint() extension function. Same as above, all arguments after the
327 // first argument are concatenated. Argument 0 is the log-level, matching
329 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
332 naRuntimeError(c, "no prioirty argument to logprint()");
334 naRef priority = args[0];
337 for(int i=1; i<n; i++) {
338 naRef s = naStringValue(c, args[i]);
339 if(naIsNil(s)) continue;
340 buf += naStr_data(s);
342 SG_LOG(SG_NASAL, (sgDebugPriority)(int) priority.num, buf);
343 return naNum(buf.length());
347 // fgcommand() extension function. Executes a named command via the
348 // FlightGear command manager. Takes a single property node name as
350 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
352 naRef cmd = argc > 0 ? args[0] : naNil();
353 naRef props = argc > 1 ? args[1] : naNil();
354 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
355 naRuntimeError(c, "bad arguments to fgcommand()");
356 SGPropertyNode_ptr tmp, *node;
358 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
360 tmp = new SGPropertyNode();
363 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
366 // settimer(func, dt, simtime) extension function. Falls through to
367 // FGNasalSys::setTimer(). See there for docs.
368 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
370 nasalSys->setTimer(c, argc, args);
374 // setlistener(func, property, bool) extension function. Falls through to
375 // FGNasalSys::setListener(). See there for docs.
376 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
378 return nasalSys->setListener(c, argc, args);
381 // removelistener(int) extension function. Falls through to
382 // FGNasalSys::removeListener(). See there for docs.
383 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
385 return nasalSys->removeListener(c, argc, args);
388 // Returns a ghost handle to the argument to the currently executing
390 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
392 return nasalSys->cmdArgGhost();
395 // Sets up a property interpolation. The first argument is either a
396 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
397 // interpolate. The second argument is a vector of pairs of
398 // value/delta numbers.
399 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
401 SGPropertyNode* node;
402 naRef prop = argc > 0 ? args[0] : naNil();
403 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
404 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
407 naRef curve = argc > 1 ? args[1] : naNil();
408 if(!naIsVector(curve)) return naNil();
409 int nPoints = naVec_size(curve) / 2;
410 double* values = new double[nPoints];
411 double* deltas = new double[nPoints];
412 for(int i=0; i<nPoints; i++) {
413 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
414 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
417 ((SGInterpolator*)globals->get_subsystem_mgr()
418 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
419 ->interpolate(node, nPoints, values, deltas);
426 // This is a better RNG than the one in the default Nasal distribution
427 // (which is based on the C library rand() implementation). It will
429 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
431 return naNum(sg_random());
434 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
440 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
446 // Return an array listing of all files in a directory
447 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
449 if(argc != 1 || !naIsString(args[0]))
450 naRuntimeError(c, "bad arguments to directory()");
452 simgear::Dir d(SGPath(naStr_data(args[0])));
453 if(!d.exists()) return naNil();
454 naRef result = naNewVector(c);
456 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
457 for (unsigned int i=0; i<paths.size(); ++i) {
458 std::string p = paths[i].file();
459 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
466 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
468 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
470 if(argc != 1 || !naIsString(args[0]))
471 naRuntimeError(c, "bad arguments to resolveDataPath()");
473 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
474 const char* pdata = p.c_str();
475 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
479 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
481 // <path> ... absolute path to an XML file
482 // <start-tag> ... callback function with two args: tag name, attribute hash
483 // <end-tag> ... callback function with one arg: tag name
484 // <data> ... callback function with one arg: data
485 // <pi> ... callback function with two args: target, data
486 // (pi = "processing instruction")
487 // All four callback functions are optional and default to nil.
488 // The function returns nil on error, or the validated file name otherwise.
489 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
491 if(argc < 1 || !naIsString(args[0]))
492 naRuntimeError(c, "parsexml(): path argument missing or not a string");
493 if(argc > 5) argc = 5;
494 for(int i=1; i<argc; i++)
495 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
496 naRuntimeError(c, "parsexml(): callback argument not a function");
498 const char* file = fgValidatePath(naStr_data(args[0]), false);
500 naRuntimeError(c, "parsexml(): reading '%s' denied "
501 "(unauthorized access)", naStr_data(args[0]));
504 std::ifstream input(file);
505 NasalXMLVisitor visitor(c, argc, args);
507 readXML(input, visitor);
508 } catch (const sg_exception& e) {
509 naRuntimeError(c, "parsexml(): file '%s' %s",
510 file, e.getFormattedMessage().c_str());
513 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
516 // Return UNIX epoch time in seconds.
517 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
521 GetSystemTimeAsFileTime(&ft);
522 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
523 // Converts from 100ns units in 1601 epoch to unix epoch in sec
524 return naNum((t * 1e-7) - 11644473600.0);
527 gettimeofday(&td, 0);
528 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
532 // Table of extension functions. Terminate with zeros.
533 static struct { const char* name; naCFunction func; } funcs[] = {
534 { "getprop", f_getprop },
535 { "setprop", f_setprop },
536 { "print", f_print },
537 { "logprint", f_logprint },
538 { "_fgcommand", f_fgcommand },
539 { "settimer", f_settimer },
540 { "_setlistener", f_setlistener },
541 { "removelistener", f_removelistener },
542 { "_cmdarg", f_cmdarg },
543 { "_interpolate", f_interpolate },
545 { "srand", f_srand },
546 { "abort", f_abort },
547 { "directory", f_directory },
548 { "resolvepath", f_resolveDataPath },
549 { "parsexml", f_parsexml },
550 { "systime", f_systime },
554 naRef FGNasalSys::cmdArgGhost()
556 return propNodeGhost(_cmdArg);
559 void FGNasalSys::init()
563 _context = naNewContext();
565 // Start with globals. Add it to itself as a recursive
566 // sub-reference under the name "globals". This gives client-code
567 // write access to the namespace if someone wants to do something
569 _globals = naInit_std(_context);
570 naSave(_context, _globals);
571 hashset(_globals, "globals", _globals);
573 hashset(_globals, "math", naInit_math(_context));
574 hashset(_globals, "bits", naInit_bits(_context));
575 hashset(_globals, "io", naInit_io(_context));
576 hashset(_globals, "thread", naInit_thread(_context));
577 hashset(_globals, "utf8", naInit_utf8(_context));
579 // Add our custom extension functions:
580 for(i=0; funcs[i].name; i++)
581 hashset(_globals, funcs[i].name,
582 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
584 // And our SGPropertyNode wrapper
585 hashset(_globals, "props", genPropsModule());
587 // Make a "__gcsave" hash to hold the naRef objects which get
588 // passed to handles outside the interpreter (to protect them from
589 // begin garbage-collected).
590 _gcHash = naNewHash(_context);
591 hashset(_globals, "__gcsave", _gcHash);
593 // Add string methods
594 _string = naInit_string(_context);
595 naSave(_context, _string);
596 initNasalString(_globals, _string, _context, _gcHash);
598 initNasalPositioned(_globals, _context, _gcHash);
599 NasalClipboard::init(this);
600 initNasalCanvas(_globals, _context, _gcHash);
601 initNasalCondition(_globals, _context, _gcHash);
603 // Now load the various source files in the Nasal directory
604 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
605 loadScriptDirectory(nasalDir);
607 // Add modules in Nasal subdirectories to property tree
608 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
609 simgear::Dir::NO_DOT_OR_DOTDOT, "");
610 for (unsigned int i=0; i<directories.size(); ++i) {
611 simgear::Dir dir(directories[i]);
612 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
613 addModule(directories[i].file(), scripts);
616 // set signal and remove node to avoid restoring at reinit
617 const char *s = "nasal-dir-initialized";
618 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
619 signal->setBoolValue(s, true);
620 signal->removeChildren(s, false);
622 // Pull scripts out of the property tree, too
623 loadPropertyScripts();
625 // now Nasal modules are loaded, we can do some delayed work
626 postinitNasalPositioned(_globals, _context);
627 postinitNasalGUI(_globals, _context);
630 void FGNasalSys::update(double)
632 if( NasalClipboard::getInstance() )
633 NasalClipboard::getInstance()->update();
635 if(!_dead_listener.empty()) {
636 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
637 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
638 _dead_listener.clear();
641 if (!_loadList.empty())
643 // process Nasal load hook (only one per update loop to avoid excessive lags)
644 _loadList.pop()->load();
647 if (!_unloadList.empty())
649 // process pending Nasal unload hooks after _all_ load hooks were processed
650 // (only unload one per update loop to avoid excessive lags)
651 _unloadList.pop()->unload();
654 // The global context is a legacy thing. We use dynamically
655 // created contexts for naCall() now, so that we can call them
656 // recursively. But there are still spots that want to use it for
657 // naNew*() calls, which end up leaking memory because the context
658 // only clears out its temporary vector when it's *used*. So just
659 // junk it and fetch a new/reinitialized one every frame. This is
660 // clumsy: the right solution would use the dynamic context in all
661 // cases and eliminate _context entirely. But that's more work,
662 // and this works fine (yes, they say "New" and "Free", but
663 // they're very fast, just trust me). -Andy
664 naFreeContext(_context);
665 _context = naNewContext();
668 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
670 return p1.file() < p2.file();
673 // Loads all scripts in given directory
674 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
676 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
677 // Note: simgear::Dir already reports file entries in a deterministic order,
678 // so a fixed loading sequence is guaranteed (same for every user)
679 for (unsigned int i=0; i<scripts.size(); ++i) {
680 SGPath fullpath(scripts[i]);
681 SGPath file = fullpath.file();
682 loadModule(fullpath, file.base().c_str());
686 // Create module with list of scripts
687 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
689 if (scripts.size()>0)
691 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
692 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
693 for (unsigned int i=0; i<scripts.size(); ++i) {
694 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
695 pFileNode->setStringValue(scripts[i].c_str());
697 if (!module_node->hasChild("enabled",0))
699 SGPropertyNode* node = module_node->getChild("enabled",0,true);
700 node->setBoolValue(true);
701 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
706 // Loads the scripts found under /nasal in the global tree
707 void FGNasalSys::loadPropertyScripts()
709 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
712 for(int i=0; i<nasal->nChildren(); i++)
714 SGPropertyNode* n = nasal->getChild(i);
715 loadPropertyScripts(n);
719 // Loads the scripts found under /nasal in the global tree
720 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
722 bool is_loaded = false;
724 const char* module = n->getName();
725 if(n->hasChild("module"))
726 module = n->getStringValue("module");
727 if (n->getBoolValue("enabled",true))
729 // allow multiple files to be specified within a single
733 bool file_specified = false;
735 while((fn = n->getChild("file", j)) != NULL) {
736 file_specified = true;
737 const char* file = fn->getStringValue();
739 if (!p.isAbsolute() || !p.exists())
741 p = globals->resolve_maybe_aircraft_path(file);
744 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
745 file << "' for module '" << module << "'.");
748 ok &= p.isNull() ? false : loadModule(p, module);
752 const char* src = n->getStringValue("script");
753 if(!n->hasChild("script")) src = 0; // Hrm...
755 createModule(module, n->getPath().c_str(), src, strlen(src));
757 if(!file_specified && !src)
759 // module no longer exists - clear the archived "enable" flag
760 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
761 SGPropertyNode* node = n->getChild("enabled",0,false);
763 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
765 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
766 "no <file> or <script> defined in " <<
767 "/nasal/" << module);
774 SGPropertyNode* enable = n->getChild("enabled");
777 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
778 enable->addChangeListener(listener, false);
781 SGPropertyNode* loaded = n->getChild("loaded",0,true);
782 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
783 loaded->setBoolValue(is_loaded);
786 // Logs a runtime error, with stack trace, to the FlightGear log stream
787 void FGNasalSys::logError(naContext context)
789 SG_LOG(SG_NASAL, SG_ALERT,
790 "Nasal runtime error: " << naGetError(context));
791 SG_LOG(SG_NASAL, SG_ALERT,
792 " at " << naStr_data(naGetSourceFile(context, 0)) <<
793 ", line " << naGetLine(context, 0));
794 for(int i=1; i<naStackDepth(context); i++)
795 SG_LOG(SG_NASAL, SG_ALERT,
796 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
797 ", line " << naGetLine(context, i));
800 // Reads a script file, executes it, and places the resulting
801 // namespace into the global namespace under the specified module
803 bool FGNasalSys::loadModule(SGPath file, const char* module)
806 char* buf = readfile(file.c_str(), &len);
808 SG_LOG(SG_NASAL, SG_ALERT,
809 "Nasal error: could not read script file " << file.c_str()
810 << " into module " << module);
814 bool ok = createModule(module, file.c_str(), buf, len);
819 // Parse and run. Save the local variables namespace, as it will
820 // become a sub-object of globals. The optional "arg" argument can be
821 // used to pass an associated property node to the module, which can then
822 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
823 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
824 const char* src, int len,
825 const SGPropertyNode* cmdarg,
826 int argc, naRef* args)
828 naRef code = parse(fileName, src, len);
832 // See if we already have a module hash to use. This allows the
833 // user to, for example, add functions to the built-in math
834 // module. Make a new one if necessary.
836 naRef modname = naNewString(_context);
837 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
838 if(!naHash_get(_globals, modname, &locals))
839 locals = naNewHash(_context);
841 _cmdArg = (SGPropertyNode*)cmdarg;
843 call(code, argc, args, locals);
844 hashset(_globals, moduleName, locals);
848 void FGNasalSys::deleteModule(const char* moduleName)
850 naRef modname = naNewString(_context);
851 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
852 naHash_delete(_globals, modname);
855 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
858 naRef srcfile = naNewString(_context);
859 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
860 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
862 SG_LOG(SG_NASAL, SG_ALERT,
863 "Nasal parse error: " << naGetError(_context) <<
864 " in "<< filename <<", line " << errLine);
868 // Bind to the global namespace before returning
869 return naBindFunction(_context, code, _globals);
872 bool FGNasalSys::handleCommand( const char* moduleName,
873 const char* fileName,
875 const SGPropertyNode* arg )
877 naRef code = parse(fileName, src, strlen(src));
878 if(naIsNil(code)) return false;
880 // Commands can be run "in" a module. Make sure that module
881 // exists, and set it up as the local variables hash for the
883 naRef locals = naNil();
885 naRef modname = naNewString(_context);
886 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
887 if(!naHash_get(_globals, modname, &locals)) {
888 locals = naNewHash(_context);
889 naHash_set(_globals, modname, locals);
893 // Cache this command's argument for inspection via cmdarg(). For
894 // performance reasons, we won't bother with it if the invoked
895 // code doesn't need it.
896 _cmdArg = (SGPropertyNode*)arg;
898 call(code, 0, 0, locals);
902 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
904 const char* src = arg->getStringValue("script");
905 const char* moduleName = arg->getStringValue("module");
907 return handleCommand( moduleName,
908 arg ? arg->getPath(true).c_str() : moduleName,
913 // settimer(func, dt, simtime) extension function. The first argument
914 // is a Nasal function to call, the second is a delta time (from now),
915 // in seconds. The third, if present, is a boolean value indicating
916 // that "real world" time (rather than simulator time) is to be used.
918 // Implementation note: the FGTimer objects don't live inside the
919 // garbage collector, so the Nasal handler functions have to be
920 // "saved" somehow lest they be inadvertently cleaned. In this case,
921 // they are inserted into a globals.__gcsave hash and removed on
923 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
925 // Extract the handler, delta, and simtime arguments:
926 naRef handler = argc > 0 ? args[0] : naNil();
927 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
928 naRuntimeError(c, "settimer() with invalid function argument");
932 naRef delta = argc > 1 ? args[1] : naNil();
934 naRuntimeError(c, "settimer() with invalid time argument");
938 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
940 // Generate and register a C++ timer handler
941 NasalTimer* t = new NasalTimer;
942 t->handler = handler;
943 t->gcKey = gcSave(handler);
946 globals->get_event_mgr()->addEvent("NasalTimer",
947 t, &NasalTimer::timerExpired,
951 void FGNasalSys::handleTimer(NasalTimer* t)
953 call(t->handler, 0, 0, naNil());
957 int FGNasalSys::gcSave(naRef r)
959 int key = _nextGCKey++;
960 naHash_set(_gcHash, naNum(key), r);
964 void FGNasalSys::gcRelease(int key)
966 naHash_delete(_gcHash, naNum(key));
969 void FGNasalSys::NasalTimer::timerExpired()
971 nasal->handleTimer(this);
975 int FGNasalSys::_listenerId = 0;
977 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
978 // Attaches a callback function to a property (specified as a global
979 // property path string or a SGPropertyNode_ptr* ghost). If the third,
980 // optional argument (default=0) is set to 1, then the function is also
981 // called initially. If the fourth, optional argument is set to 0, then the
982 // function is only called when the property node value actually changes.
983 // Otherwise it's called independent of the value whenever the node is
984 // written to (default). The setlistener() function returns a unique
985 // id number, which is to be used as argument to the removelistener()
987 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
989 SGPropertyNode_ptr node;
990 naRef prop = argc > 0 ? args[0] : naNil();
991 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
992 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
994 naRuntimeError(c, "setlistener() with invalid property argument");
999 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1002 naRef code = argc > 1 ? args[1] : naNil();
1003 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1004 naRuntimeError(c, "setlistener() with invalid function argument");
1008 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1009 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1010 FGNasalListener *nl = new FGNasalListener(node, code, this,
1011 gcSave(code), _listenerId, init, type);
1013 node->addChangeListener(nl, init != 0);
1015 _listener[_listenerId] = nl;
1016 return naNum(_listenerId++);
1019 // removelistener(int) extension function. The argument is the id of
1020 // a listener as returned by the setlistener() function.
1021 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1023 naRef id = argc > 0 ? args[0] : naNil();
1024 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1026 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1027 naRuntimeError(c, "removelistener() with invalid listener id");
1031 it->second->_dead = true;
1032 _dead_listener.push_back(it->second);
1033 _listener.erase(it);
1034 return naNum(_listener.size());
1039 // FGNasalListener class.
1041 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1042 FGNasalSys* nasal, int key, int id,
1043 int init, int type) :
1056 if(_type == 0 && !_init)
1060 FGNasalListener::~FGNasalListener()
1062 _node->removeChangeListener(this);
1063 _nas->gcRelease(_gcKey);
1066 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1068 if(_active || _dead) return;
1069 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1072 arg[0] = _nas->propNodeGhost(which);
1073 arg[1] = _nas->propNodeGhost(_node);
1074 arg[2] = mode; // value changed, child added/removed
1075 arg[3] = naNum(_node != which); // child event?
1076 _nas->call(_code, 4, arg, naNil());
1080 void FGNasalListener::valueChanged(SGPropertyNode* node)
1082 if(_type < 2 && node != _node) return; // skip child events
1083 if(_type > 0 || changed(_node) || _init)
1084 call(node, naNum(0));
1089 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1091 if(_type == 2) call(child, naNum(1));
1094 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1096 if(_type == 2) call(child, naNum(-1));
1099 bool FGNasalListener::changed(SGPropertyNode* node)
1101 using namespace simgear;
1102 props::Type type = node->getType();
1103 if(type == props::NONE) return false;
1104 if(type == props::UNSPECIFIED) return true;
1112 long l = node->getLongValue();
1113 result = l != _last_int;
1120 double d = node->getDoubleValue();
1121 result = d != _last_float;
1127 string s = node->getStringValue();
1128 result = s != _last_string;
1137 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1138 // such a class, then it lets modelLoaded() run the <load> script, and the
1139 // destructor the <unload> script. The latter happens when the model branch
1140 // is removed from the scene graph.
1142 unsigned int FGNasalModelData::_module_id = 0;
1144 void FGNasalModelData::load()
1146 std::stringstream m;
1147 m << "__model" << _module_id++;
1150 SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1152 const char *s = _load ? _load->getStringValue() : "";
1155 arg[0] = nasalSys->propNodeGhost(_root);
1156 arg[1] = nasalSys->propNodeGhost(_prop);
1157 nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1161 void FGNasalModelData::unload()
1163 if (_module.empty())
1167 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1168 "without Nasal subsystem present.");
1172 SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1176 const char *s = _unload->getStringValue();
1177 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1180 nasalSys->deleteModule(_module.c_str());
1183 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1187 SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1188 "without Nasal subsystem present.");
1195 SGPropertyNode *nasal = prop->getNode("nasal");
1199 SGPropertyNode* load = nasal->getNode("load");
1200 SGPropertyNode* unload = nasal->getNode("unload");
1202 if ((!load) && (!unload))
1205 _data = new FGNasalModelData(_root, path, prop, load, unload);
1207 // register Nasal module to be created and loaded in the main thread.
1208 nasalSys->registerToLoad(_data);
1211 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1213 // when necessary, register Nasal module to be destroyed/unloaded
1214 // in the main thread.
1215 if ((_data.valid())&&(nasalSys))
1216 nasalSys->registerToUnload(_data);
1219 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1221 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1222 _c(naSubContext(c)),
1223 _start_element(argc > 1 ? args[1] : naNil()),
1224 _end_element(argc > 2 ? args[2] : naNil()),
1225 _data(argc > 3 ? args[3] : naNil()),
1226 _pi(argc > 4 ? args[4] : naNil())
1230 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1232 if(naIsNil(_start_element)) return;
1233 naRef attr = naNewHash(_c);
1234 for(int i=0; i<a.size(); i++) {
1235 naRef name = make_string(a.getName(i));
1236 naRef value = make_string(a.getValue(i));
1237 naHash_set(attr, name, value);
1239 call(_start_element, 2, make_string(tag), attr);
1242 void NasalXMLVisitor::endElement(const char* tag)
1244 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1247 void NasalXMLVisitor::data(const char* str, int len)
1249 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1252 void NasalXMLVisitor::pi(const char* target, const char* data)
1254 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1257 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1262 naCall(_c, func, num, args, naNil(), naNil());
1267 naRef NasalXMLVisitor::make_string(const char* s, int n)
1269 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1270 n < 0 ? strlen(s) : n);