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 <simgear/nasal/cppbind/from_nasal.hxx>
33 #include <simgear/nasal/cppbind/to_nasal.hxx>
34 #include <simgear/nasal/cppbind/Ghost.hxx>
35 #include <simgear/nasal/cppbind/NasalHash.hxx>
37 #include "NasalSys.hxx"
38 #include "NasalSys_private.hxx"
39 #include "NasalModelData.hxx"
40 #include "NasalPositioned.hxx"
41 #include "NasalCanvas.hxx"
42 #include "NasalClipboard.hxx"
43 #include "NasalCondition.hxx"
44 #include "NasalString.hxx"
46 #include <Main/globals.hxx>
47 #include <Main/util.hxx>
48 #include <Main/fg_props.hxx>
53 void postinitNasalGUI(naRef globals, naContext c);
55 static FGNasalSys* nasalSys = 0;
57 // Listener class for loading Nasal modules on demand
58 class FGNasalModuleListener : public SGPropertyChangeListener
61 FGNasalModuleListener(SGPropertyNode* node);
63 virtual void valueChanged(SGPropertyNode* node);
66 SGPropertyNode_ptr _node;
69 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
73 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
75 if (_node->getBoolValue("enabled",false)&&
76 !_node->getBoolValue("loaded",true))
78 nasalSys->loadPropertyScripts(_node);
82 //////////////////////////////////////////////////////////////////////////
85 class TimerObj : public SGReferenced
88 TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
97 snprintf(nm, 128, "nasal-timer-%p", this);
99 _gcRoot = sys->gcSave(f);
100 _gcSelf = sys->gcSave(self);
106 _sys->gcRelease(_gcRoot);
107 _sys->gcRelease(_gcSelf);
113 globals->get_event_mgr()->removeTask(_name);
126 globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
128 globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke, _interval);
132 // stop and then start -
133 void restart(double newInterval)
135 _interval = newInterval;
143 _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
146 void setSingleShot(bool aSingleShot)
148 _singleShot = aSingleShot;
151 bool isSingleShot() const
152 { return _singleShot; }
157 int _gcRoot, _gcSelf;
163 typedef SGSharedPtr<TimerObj> TimerObjRef;
164 typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
166 ///////////////////////////////////////////////////////////////////////////
168 // Read and return file contents in a single buffer. Note use of
169 // stat() to get the file size. This is a win32 function, believe it
170 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
171 // Text mode brain damage will kill us if we're trying to do bytewise
173 static char* readfile(const char* file, int* lenOut)
176 if(stat(file, &data) != 0) return 0;
177 FILE* f = fopen(file, "rb");
179 char* buf = new char[data.st_size];
180 *lenOut = fread(buf, 1, data.st_size, f);
182 if(*lenOut != data.st_size) {
183 // Shouldn't happen, but warn anyway since it represents a
184 // platform bug and not a typical runtime error (missing file,
186 SG_LOG(SG_NASAL, SG_ALERT,
187 "ERROR in Nasal initialization: " <<
188 "short count returned from fread() of " << file <<
189 ". Check your C library!");
196 FGNasalSys::FGNasalSys()
203 _nextGCKey = 0; // Any value will do
206 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
207 _log->truncateAt(255);
208 sglog().addCallback(_log);
211 // Utility. Sets a named key in a hash by C string, rather than nasal
213 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
215 naRef s = naNewString(_context);
216 naStr_fromdata(s, (char*)key, strlen(key));
217 naHash_set(hash, s, val);
220 void FGNasalSys::globalsSet(const char* key, naRef val)
222 hashset(_globals, key, val);
225 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
227 return callMethod(code, naNil(), argc, args, locals);
230 // Does a naCall() in a new context. Wrapped here to make lock
231 // tracking easier. Extension functions are called with the lock, but
232 // we have to release it before making a new naCall(). So rather than
233 // drop the lock in every extension function that might call back into
234 // Nasal, we keep a stack depth counter here and only unlock/lock
235 // around the naCall if it isn't the first one.
237 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
239 naContext ctx = naNewContext();
240 if(_callCount) naModUnlock();
242 naRef result = naCall(ctx, code, argc, args, self, locals);
246 if(_callCount) naModLock();
251 FGNasalSys::~FGNasalSys()
254 map<int, FGNasalListener *>::iterator it, end = _listener.end();
255 for(it = _listener.begin(); it != end; ++it)
258 naFreeContext(_context);
263 bool FGNasalSys::parseAndRun(const char* sourceCode)
265 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
269 call(code, 0, 0, naNil());
274 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
276 FGNasalScript* script = new FGNasalScript();
277 script->_gcKey = -1; // important, if we delete it on a parse
278 script->_nas = this; // error, don't clobber a real handle!
282 sprintf(buf, "FGNasalScript@%p", (void *)script);
286 script->_code = parse(name, src, strlen(src));
287 if(naIsNil(script->_code)) {
292 script->_gcKey = gcSave(script->_code);
297 // The get/setprop functions accept a *list* of strings and walk
298 // through the property tree with them to find the appropriate node.
299 // This allows a Nasal object to hold onto a property path and use it
300 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
301 // is the utility function that walks the property tree.
302 // Future enhancement: support integer arguments to specify array
304 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
306 SGPropertyNode* p = globals->get_props();
308 for(int i=0; i<len; i++) {
310 if(!naIsString(a)) return 0;
311 p = p->getNode(naStr_data(a));
314 } catch (const string& err) {
315 naRuntimeError(c, (char *)err.c_str());
321 // getprop() extension function. Concatenates its string arguments as
322 // property names and returns the value of the specified property. Or
323 // nil if it doesn't exist.
324 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
326 using namespace simgear;
327 const SGPropertyNode* p = findnode(c, args, argc);
328 if(!p) return naNil();
330 switch(p->getType()) {
331 case props::BOOL: case props::INT:
332 case props::LONG: case props::FLOAT:
335 double dv = p->getDoubleValue();
336 if (SGMisc<double>::isNaN(dv)) {
337 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
345 case props::UNSPECIFIED:
347 naRef nastr = naNewString(c);
348 const char* val = p->getStringValue();
349 naStr_fromdata(nastr, (char*)val, strlen(val));
352 case props::ALIAS: // <--- FIXME, recurse?
358 // setprop() extension function. Concatenates its string arguments as
359 // property names and sets the value of the specified property to the
361 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
364 char buf[BUFLEN + 1];
368 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
369 for(int i=0; i<argc-1; i++) {
370 naRef s = naStringValue(c, args[i]);
371 if(naIsNil(s)) return naNil();
372 strncpy(p, naStr_data(s), buflen);
374 buflen = BUFLEN - (p - buf);
375 if(i < (argc-2) && buflen > 0) {
381 SGPropertyNode* props = globals->get_props();
382 naRef val = args[argc-1];
385 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
387 naRef n = naNumValue(val);
389 naRuntimeError(c, "setprop() value is not string or number");
391 if (SGMisc<double>::isNaN(n.num)) {
392 naRuntimeError(c, "setprop() passed a NaN");
395 result = props->setDoubleValue(buf, n.num);
397 } catch (const string& err) {
398 naRuntimeError(c, (char *)err.c_str());
400 return naNum(result);
404 // print() extension function. Concatenates and prints its arguments
405 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
406 // make sure it appears. Is there better way to do this?
407 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
411 for(int i=0; i<n; i++) {
412 naRef s = naStringValue(c, args[i]);
413 if(naIsNil(s)) continue;
414 buf += naStr_data(s);
416 SG_LOG(SG_NASAL, SG_ALERT, buf);
417 return naNum(buf.length());
420 // logprint() extension function. Same as above, all arguments after the
421 // first argument are concatenated. Argument 0 is the log-level, matching
423 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
426 naRuntimeError(c, "no prioirty argument to logprint()");
428 naRef priority = args[0];
431 for(int i=1; i<n; i++) {
432 naRef s = naStringValue(c, args[i]);
433 if(naIsNil(s)) continue;
434 buf += naStr_data(s);
436 // use the nasal source file and line for the message location, since
437 // that's more useful than the location here!
438 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
439 naStr_data(naGetSourceFile(c, 0)),
440 naGetLine(c, 0), buf);
441 return naNum(buf.length());
445 // fgcommand() extension function. Executes a named command via the
446 // FlightGear command manager. Takes a single property node name as
448 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
450 naRef cmd = argc > 0 ? args[0] : naNil();
451 naRef props = argc > 1 ? args[1] : naNil();
452 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
453 naRuntimeError(c, "bad arguments to fgcommand()");
454 SGPropertyNode_ptr tmp, *node;
456 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
458 tmp = new SGPropertyNode();
461 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
464 // settimer(func, dt, simtime) extension function. Falls through to
465 // FGNasalSys::setTimer(). See there for docs.
466 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
468 nasalSys->setTimer(c, argc, args);
472 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
474 if (!naIsNum(args[0])) {
475 naRuntimeError(c, "bad interval argument to maketimer");
478 naRef func, self = naNil();
479 if (naIsFunc(args[1])) {
481 } else if ((argc == 3) && naIsFunc(args[2])) {
486 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
487 return NasalTimerObj::create(c, timerObj);
490 // setlistener(func, property, bool) extension function. Falls through to
491 // FGNasalSys::setListener(). See there for docs.
492 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
494 return nasalSys->setListener(c, argc, args);
497 // removelistener(int) extension function. Falls through to
498 // FGNasalSys::removeListener(). See there for docs.
499 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
501 return nasalSys->removeListener(c, argc, args);
504 // Returns a ghost handle to the argument to the currently executing
506 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
508 return nasalSys->cmdArgGhost();
511 // Sets up a property interpolation. The first argument is either a
512 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
513 // interpolate. The second argument is a vector of pairs of
514 // value/delta numbers.
515 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
517 SGPropertyNode* node;
518 naRef prop = argc > 0 ? args[0] : naNil();
519 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
520 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
523 naRef curve = argc > 1 ? args[1] : naNil();
524 if(!naIsVector(curve)) return naNil();
525 int nPoints = naVec_size(curve) / 2;
526 double* values = new double[nPoints];
527 double* deltas = new double[nPoints];
528 for(int i=0; i<nPoints; i++) {
529 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
530 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
533 ((SGInterpolator*)globals->get_subsystem_mgr()
534 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
535 ->interpolate(node, nPoints, values, deltas);
542 // This is a better RNG than the one in the default Nasal distribution
543 // (which is based on the C library rand() implementation). It will
545 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
547 return naNum(sg_random());
550 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
556 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
562 // Return an array listing of all files in a directory
563 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
565 if(argc != 1 || !naIsString(args[0]))
566 naRuntimeError(c, "bad arguments to directory()");
568 simgear::Dir d(SGPath(naStr_data(args[0])));
569 if(!d.exists()) return naNil();
570 naRef result = naNewVector(c);
572 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
573 for (unsigned int i=0; i<paths.size(); ++i) {
574 std::string p = paths[i].file();
575 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
582 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
584 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
586 if(argc != 1 || !naIsString(args[0]))
587 naRuntimeError(c, "bad arguments to resolveDataPath()");
589 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
590 const char* pdata = p.c_str();
591 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
594 class NasalCommand : public SGCommandMgr::Command
597 NasalCommand(FGNasalSys* sys, naRef f) :
601 _gcRoot = sys->gcSave(f);
604 virtual ~NasalCommand()
606 _sys->gcRelease(_gcRoot);
609 virtual bool operator()(const SGPropertyNode* aNode)
611 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
613 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
615 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
626 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
628 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
629 naRuntimeError(c, "bad arguments to addcommand()");
631 naRef func = args[1];
632 NasalCommand* cmd = new NasalCommand(nasalSys, func);
633 globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
637 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
639 SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
641 // SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
649 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
651 // <path> ... absolute path to an XML file
652 // <start-tag> ... callback function with two args: tag name, attribute hash
653 // <end-tag> ... callback function with one arg: tag name
654 // <data> ... callback function with one arg: data
655 // <pi> ... callback function with two args: target, data
656 // (pi = "processing instruction")
657 // All four callback functions are optional and default to nil.
658 // The function returns nil on error, or the validated file name otherwise.
659 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
661 if(argc < 1 || !naIsString(args[0]))
662 naRuntimeError(c, "parsexml(): path argument missing or not a string");
663 if(argc > 5) argc = 5;
664 for(int i=1; i<argc; i++)
665 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
666 naRuntimeError(c, "parsexml(): callback argument not a function");
668 const char* file = fgValidatePath(naStr_data(args[0]), false);
670 naRuntimeError(c, "parsexml(): reading '%s' denied "
671 "(unauthorized access)", naStr_data(args[0]));
674 std::ifstream input(file);
675 NasalXMLVisitor visitor(c, argc, args);
677 readXML(input, visitor);
678 } catch (const sg_exception& e) {
679 naRuntimeError(c, "parsexml(): file '%s' %s",
680 file, e.getFormattedMessage().c_str());
683 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
686 // Return UNIX epoch time in seconds.
687 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
691 GetSystemTimeAsFileTime(&ft);
692 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
693 // Converts from 100ns units in 1601 epoch to unix epoch in sec
694 return naNum((t * 1e-7) - 11644473600.0);
697 gettimeofday(&td, 0);
698 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
702 // Table of extension functions. Terminate with zeros.
703 static struct { const char* name; naCFunction func; } funcs[] = {
704 { "getprop", f_getprop },
705 { "setprop", f_setprop },
706 { "print", f_print },
707 { "logprint", f_logprint },
708 { "_fgcommand", f_fgcommand },
709 { "settimer", f_settimer },
710 { "maketimer", f_makeTimer },
711 { "_setlistener", f_setlistener },
712 { "removelistener", f_removelistener },
713 { "addcommand", f_addCommand },
714 { "removecommand", f_removeCommand },
715 { "_cmdarg", f_cmdarg },
716 { "_interpolate", f_interpolate },
718 { "srand", f_srand },
719 { "abort", f_abort },
720 { "directory", f_directory },
721 { "resolvepath", f_resolveDataPath },
722 { "parsexml", f_parsexml },
723 { "systime", f_systime },
727 naRef FGNasalSys::cmdArgGhost()
729 return propNodeGhost(_cmdArg);
732 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
737 void FGNasalSys::init()
741 _context = naNewContext();
743 // Start with globals. Add it to itself as a recursive
744 // sub-reference under the name "globals". This gives client-code
745 // write access to the namespace if someone wants to do something
747 _globals = naInit_std(_context);
748 naSave(_context, _globals);
749 hashset(_globals, "globals", _globals);
751 hashset(_globals, "math", naInit_math(_context));
752 hashset(_globals, "bits", naInit_bits(_context));
753 hashset(_globals, "io", naInit_io(_context));
754 hashset(_globals, "thread", naInit_thread(_context));
755 hashset(_globals, "utf8", naInit_utf8(_context));
757 // Add our custom extension functions:
758 for(i=0; funcs[i].name; i++)
759 hashset(_globals, funcs[i].name,
760 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
762 // And our SGPropertyNode wrapper
763 hashset(_globals, "props", genPropsModule());
765 // Make a "__gcsave" hash to hold the naRef objects which get
766 // passed to handles outside the interpreter (to protect them from
767 // begin garbage-collected).
768 _gcHash = naNewHash(_context);
769 hashset(_globals, "__gcsave", _gcHash);
771 // Add string methods
772 _string = naInit_string(_context);
773 naSave(_context, _string);
774 initNasalString(_globals, _string, _context, _gcHash);
776 initNasalPositioned(_globals, _context, _gcHash);
777 initNasalPositioned_cppbind(_globals, _context, _gcHash);
778 NasalClipboard::init(this);
779 initNasalCanvas(_globals, _context, _gcHash);
780 initNasalCondition(_globals, _context, _gcHash);
782 NasalTimerObj::init("Timer")
783 .method("start", &TimerObj::start)
784 .method("stop", &TimerObj::stop)
785 .method("restart", &TimerObj::restart)
786 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot);
788 // Now load the various source files in the Nasal directory
789 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
790 loadScriptDirectory(nasalDir);
792 // Add modules in Nasal subdirectories to property tree
793 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
794 simgear::Dir::NO_DOT_OR_DOTDOT, "");
795 for (unsigned int i=0; i<directories.size(); ++i) {
796 simgear::Dir dir(directories[i]);
797 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
798 addModule(directories[i].file(), scripts);
801 // set signal and remove node to avoid restoring at reinit
802 const char *s = "nasal-dir-initialized";
803 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
804 signal->setBoolValue(s, true);
805 signal->removeChildren(s, false);
807 // Pull scripts out of the property tree, too
808 loadPropertyScripts();
810 // now Nasal modules are loaded, we can do some delayed work
811 postinitNasalPositioned(_globals, _context);
812 postinitNasalGUI(_globals, _context);
815 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
817 static naRef wrapNodeFunc = naNil();
818 if (naIsNil(wrapNodeFunc)) {
819 nasal::Hash g(_globals, _context);
820 nasal::Hash props = g.get<nasal::Hash>("props");
821 wrapNodeFunc = props.get("wrapNode");
825 args[0] = propNodeGhost(aProps);
826 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
829 void FGNasalSys::update(double)
831 if( NasalClipboard::getInstance() )
832 NasalClipboard::getInstance()->update();
834 if(!_dead_listener.empty()) {
835 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
836 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
837 _dead_listener.clear();
840 if (!_loadList.empty())
842 // process Nasal load hook (only one per update loop to avoid excessive lags)
843 _loadList.pop()->load();
846 if (!_unloadList.empty())
848 // process pending Nasal unload hooks after _all_ load hooks were processed
849 // (only unload one per update loop to avoid excessive lags)
850 _unloadList.pop()->unload();
853 // The global context is a legacy thing. We use dynamically
854 // created contexts for naCall() now, so that we can call them
855 // recursively. But there are still spots that want to use it for
856 // naNew*() calls, which end up leaking memory because the context
857 // only clears out its temporary vector when it's *used*. So just
858 // junk it and fetch a new/reinitialized one every frame. This is
859 // clumsy: the right solution would use the dynamic context in all
860 // cases and eliminate _context entirely. But that's more work,
861 // and this works fine (yes, they say "New" and "Free", but
862 // they're very fast, just trust me). -Andy
863 naFreeContext(_context);
864 _context = naNewContext();
867 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
869 return p1.file() < p2.file();
872 // Loads all scripts in given directory
873 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
875 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
876 // Note: simgear::Dir already reports file entries in a deterministic order,
877 // so a fixed loading sequence is guaranteed (same for every user)
878 for (unsigned int i=0; i<scripts.size(); ++i) {
879 SGPath fullpath(scripts[i]);
880 SGPath file = fullpath.file();
881 loadModule(fullpath, file.base().c_str());
885 // Create module with list of scripts
886 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
888 if (scripts.size()>0)
890 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
891 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
892 for (unsigned int i=0; i<scripts.size(); ++i) {
893 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
894 pFileNode->setStringValue(scripts[i].c_str());
896 if (!module_node->hasChild("enabled",0))
898 SGPropertyNode* node = module_node->getChild("enabled",0,true);
899 node->setBoolValue(true);
900 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
905 // Loads the scripts found under /nasal in the global tree
906 void FGNasalSys::loadPropertyScripts()
908 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
911 for(int i=0; i<nasal->nChildren(); i++)
913 SGPropertyNode* n = nasal->getChild(i);
914 loadPropertyScripts(n);
918 // Loads the scripts found under /nasal in the global tree
919 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
921 bool is_loaded = false;
923 const char* module = n->getName();
924 if(n->hasChild("module"))
925 module = n->getStringValue("module");
926 if (n->getBoolValue("enabled",true))
928 // allow multiple files to be specified within a single
932 bool file_specified = false;
934 while((fn = n->getChild("file", j)) != NULL) {
935 file_specified = true;
936 const char* file = fn->getStringValue();
938 if (!p.isAbsolute() || !p.exists())
940 p = globals->resolve_maybe_aircraft_path(file);
943 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
944 file << "' for module '" << module << "'.");
947 ok &= p.isNull() ? false : loadModule(p, module);
951 const char* src = n->getStringValue("script");
952 if(!n->hasChild("script")) src = 0; // Hrm...
954 createModule(module, n->getPath().c_str(), src, strlen(src));
956 if(!file_specified && !src)
958 // module no longer exists - clear the archived "enable" flag
959 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
960 SGPropertyNode* node = n->getChild("enabled",0,false);
962 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
964 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
965 "no <file> or <script> defined in " <<
966 "/nasal/" << module);
973 SGPropertyNode* enable = n->getChild("enabled");
976 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
977 enable->addChangeListener(listener, false);
980 SGPropertyNode* loaded = n->getChild("loaded",0,true);
981 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
982 loaded->setBoolValue(is_loaded);
985 // Logs a runtime error, with stack trace, to the FlightGear log stream
986 void FGNasalSys::logError(naContext context)
988 SG_LOG(SG_NASAL, SG_ALERT,
989 "Nasal runtime error: " << naGetError(context));
990 SG_LOG(SG_NASAL, SG_ALERT,
991 " at " << naStr_data(naGetSourceFile(context, 0)) <<
992 ", line " << naGetLine(context, 0));
993 for(int i=1; i<naStackDepth(context); i++)
994 SG_LOG(SG_NASAL, SG_ALERT,
995 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
996 ", line " << naGetLine(context, i));
999 // Reads a script file, executes it, and places the resulting
1000 // namespace into the global namespace under the specified module
1002 bool FGNasalSys::loadModule(SGPath file, const char* module)
1005 char* buf = readfile(file.c_str(), &len);
1007 SG_LOG(SG_NASAL, SG_ALERT,
1008 "Nasal error: could not read script file " << file.c_str()
1009 << " into module " << module);
1013 bool ok = createModule(module, file.c_str(), buf, len);
1018 // Parse and run. Save the local variables namespace, as it will
1019 // become a sub-object of globals. The optional "arg" argument can be
1020 // used to pass an associated property node to the module, which can then
1021 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1022 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1023 const char* src, int len,
1024 const SGPropertyNode* cmdarg,
1025 int argc, naRef* args)
1027 naRef code = parse(fileName, src, len);
1031 // See if we already have a module hash to use. This allows the
1032 // user to, for example, add functions to the built-in math
1033 // module. Make a new one if necessary.
1035 naRef modname = naNewString(_context);
1036 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1037 if(!naHash_get(_globals, modname, &locals))
1038 locals = naNewHash(_context);
1040 _cmdArg = (SGPropertyNode*)cmdarg;
1042 call(code, argc, args, locals);
1043 hashset(_globals, moduleName, locals);
1047 void FGNasalSys::deleteModule(const char* moduleName)
1049 naRef modname = naNewString(_context);
1050 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1051 naHash_delete(_globals, modname);
1054 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1057 naRef srcfile = naNewString(_context);
1058 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1059 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1061 SG_LOG(SG_NASAL, SG_ALERT,
1062 "Nasal parse error: " << naGetError(_context) <<
1063 " in "<< filename <<", line " << errLine);
1067 // Bind to the global namespace before returning
1068 return naBindFunction(_context, code, _globals);
1071 bool FGNasalSys::handleCommand( const char* moduleName,
1072 const char* fileName,
1074 const SGPropertyNode* arg )
1076 naRef code = parse(fileName, src, strlen(src));
1077 if(naIsNil(code)) return false;
1079 // Commands can be run "in" a module. Make sure that module
1080 // exists, and set it up as the local variables hash for the
1082 naRef locals = naNil();
1084 naRef modname = naNewString(_context);
1085 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1086 if(!naHash_get(_globals, modname, &locals)) {
1087 locals = naNewHash(_context);
1088 naHash_set(_globals, modname, locals);
1092 // Cache this command's argument for inspection via cmdarg(). For
1093 // performance reasons, we won't bother with it if the invoked
1094 // code doesn't need it.
1095 _cmdArg = (SGPropertyNode*)arg;
1097 call(code, 0, 0, locals);
1101 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1103 const char* src = arg->getStringValue("script");
1104 const char* moduleName = arg->getStringValue("module");
1106 return handleCommand( moduleName,
1107 arg ? arg->getPath(true).c_str() : moduleName,
1112 // settimer(func, dt, simtime) extension function. The first argument
1113 // is a Nasal function to call, the second is a delta time (from now),
1114 // in seconds. The third, if present, is a boolean value indicating
1115 // that "real world" time (rather than simulator time) is to be used.
1117 // Implementation note: the FGTimer objects don't live inside the
1118 // garbage collector, so the Nasal handler functions have to be
1119 // "saved" somehow lest they be inadvertently cleaned. In this case,
1120 // they are inserted into a globals.__gcsave hash and removed on
1122 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1124 // Extract the handler, delta, and simtime arguments:
1125 naRef handler = argc > 0 ? args[0] : naNil();
1126 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1127 naRuntimeError(c, "settimer() with invalid function argument");
1131 naRef delta = argc > 1 ? args[1] : naNil();
1132 if(naIsNil(delta)) {
1133 naRuntimeError(c, "settimer() with invalid time argument");
1137 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1139 // Generate and register a C++ timer handler
1140 NasalTimer* t = new NasalTimer;
1141 t->handler = handler;
1142 t->gcKey = gcSave(handler);
1145 globals->get_event_mgr()->addEvent("NasalTimer",
1146 t, &NasalTimer::timerExpired,
1147 delta.num, simtime);
1150 void FGNasalSys::handleTimer(NasalTimer* t)
1152 call(t->handler, 0, 0, naNil());
1153 gcRelease(t->gcKey);
1156 int FGNasalSys::gcSave(naRef r)
1158 int key = _nextGCKey++;
1159 naHash_set(_gcHash, naNum(key), r);
1163 void FGNasalSys::gcRelease(int key)
1165 naHash_delete(_gcHash, naNum(key));
1168 void FGNasalSys::NasalTimer::timerExpired()
1170 nasal->handleTimer(this);
1174 int FGNasalSys::_listenerId = 0;
1176 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1177 // Attaches a callback function to a property (specified as a global
1178 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1179 // optional argument (default=0) is set to 1, then the function is also
1180 // called initially. If the fourth, optional argument is set to 0, then the
1181 // function is only called when the property node value actually changes.
1182 // Otherwise it's called independent of the value whenever the node is
1183 // written to (default). The setlistener() function returns a unique
1184 // id number, which is to be used as argument to the removelistener()
1186 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1188 SGPropertyNode_ptr node;
1189 naRef prop = argc > 0 ? args[0] : naNil();
1190 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1191 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1193 naRuntimeError(c, "setlistener() with invalid property argument");
1198 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1201 naRef code = argc > 1 ? args[1] : naNil();
1202 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1203 naRuntimeError(c, "setlistener() with invalid function argument");
1207 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1208 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1209 FGNasalListener *nl = new FGNasalListener(node, code, this,
1210 gcSave(code), _listenerId, init, type);
1212 node->addChangeListener(nl, init != 0);
1214 _listener[_listenerId] = nl;
1215 return naNum(_listenerId++);
1218 // removelistener(int) extension function. The argument is the id of
1219 // a listener as returned by the setlistener() function.
1220 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1222 naRef id = argc > 0 ? args[0] : naNil();
1223 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1225 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1226 naRuntimeError(c, "removelistener() with invalid listener id");
1230 it->second->_dead = true;
1231 _dead_listener.push_back(it->second);
1232 _listener.erase(it);
1233 return naNum(_listener.size());
1236 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1238 _loadList.push(data);
1241 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1243 _unloadList.push(data);
1246 //////////////////////////////////////////////////////////////////////////
1247 // FGNasalListener class.
1249 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1250 FGNasalSys* nasal, int key, int id,
1251 int init, int type) :
1264 if(_type == 0 && !_init)
1268 FGNasalListener::~FGNasalListener()
1270 _node->removeChangeListener(this);
1271 _nas->gcRelease(_gcKey);
1274 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1276 if(_active || _dead) return;
1277 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1280 arg[0] = _nas->propNodeGhost(which);
1281 arg[1] = _nas->propNodeGhost(_node);
1282 arg[2] = mode; // value changed, child added/removed
1283 arg[3] = naNum(_node != which); // child event?
1284 _nas->call(_code, 4, arg, naNil());
1288 void FGNasalListener::valueChanged(SGPropertyNode* node)
1290 if(_type < 2 && node != _node) return; // skip child events
1291 if(_type > 0 || changed(_node) || _init)
1292 call(node, naNum(0));
1297 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1299 if(_type == 2) call(child, naNum(1));
1302 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1304 if(_type == 2) call(child, naNum(-1));
1307 bool FGNasalListener::changed(SGPropertyNode* node)
1309 using namespace simgear;
1310 props::Type type = node->getType();
1311 if(type == props::NONE) return false;
1312 if(type == props::UNSPECIFIED) return true;
1320 long l = node->getLongValue();
1321 result = l != _last_int;
1328 double d = node->getDoubleValue();
1329 result = d != _last_float;
1335 string s = node->getStringValue();
1336 result = s != _last_string;
1343 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1345 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1346 _c(naSubContext(c)),
1347 _start_element(argc > 1 ? args[1] : naNil()),
1348 _end_element(argc > 2 ? args[2] : naNil()),
1349 _data(argc > 3 ? args[3] : naNil()),
1350 _pi(argc > 4 ? args[4] : naNil())
1354 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1356 if(naIsNil(_start_element)) return;
1357 naRef attr = naNewHash(_c);
1358 for(int i=0; i<a.size(); i++) {
1359 naRef name = make_string(a.getName(i));
1360 naRef value = make_string(a.getValue(i));
1361 naHash_set(attr, name, value);
1363 call(_start_element, 2, make_string(tag), attr);
1366 void NasalXMLVisitor::endElement(const char* tag)
1368 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1371 void NasalXMLVisitor::data(const char* str, int len)
1373 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1376 void NasalXMLVisitor::pi(const char* target, const char* data)
1378 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1381 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1386 naCall(_c, func, num, args, naNil(), naNil());
1391 naRef NasalXMLVisitor::make_string(const char* s, int n)
1393 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1394 n < 0 ? strlen(s) : n);