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/structure/commands.hxx>
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/structure/event_mgr.hxx>
29 #include <simgear/debug/BufferedLogCallback.hxx>
31 #include <simgear/nasal/cppbind/from_nasal.hxx>
32 #include <simgear/nasal/cppbind/to_nasal.hxx>
33 #include <simgear/nasal/cppbind/Ghost.hxx>
34 #include <simgear/nasal/cppbind/NasalHash.hxx>
36 #include "NasalSys.hxx"
37 #include "NasalSys_private.hxx"
38 #include "NasalModelData.hxx"
39 #include "NasalPositioned.hxx"
40 #include "NasalCanvas.hxx"
41 #include "NasalClipboard.hxx"
42 #include "NasalCondition.hxx"
43 #include "NasalHTTP.hxx"
44 #include "NasalString.hxx"
46 #include <Main/globals.hxx>
47 #include <Main/util.hxx>
48 #include <Main/fg_props.hxx>
52 void postinitNasalGUI(naRef globals, naContext c);
54 static FGNasalSys* nasalSys = 0;
56 // Listener class for loading Nasal modules on demand
57 class FGNasalModuleListener : public SGPropertyChangeListener
60 FGNasalModuleListener(SGPropertyNode* node);
62 virtual void valueChanged(SGPropertyNode* node);
65 SGPropertyNode_ptr _node;
68 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
72 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
74 if (_node->getBoolValue("enabled",false)&&
75 !_node->getBoolValue("loaded",true))
77 nasalSys->loadPropertyScripts(_node);
81 //////////////////////////////////////////////////////////////////////////
84 class TimerObj : public SGReferenced
87 TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
96 snprintf(nm, 128, "nasal-timer-%p", this);
98 _gcRoot = sys->gcSave(f);
99 _gcSelf = sys->gcSave(self);
105 _sys->gcRelease(_gcRoot);
106 _sys->gcRelease(_gcSelf);
109 bool isRunning() const { return _isRunning; }
114 globals->get_event_mgr()->removeTask(_name);
127 globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
129 globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke,
130 _interval, _interval /* delay */);
134 // stop and then start -
135 void restart(double newInterval)
137 _interval = newInterval;
145 _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
151 void setSingleShot(bool aSingleShot)
153 _singleShot = aSingleShot;
156 bool isSingleShot() const
157 { return _singleShot; }
162 int _gcRoot, _gcSelf;
168 typedef SGSharedPtr<TimerObj> TimerObjRef;
169 typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
171 ///////////////////////////////////////////////////////////////////////////
173 // Read and return file contents in a single buffer. Note use of
174 // stat() to get the file size. This is a win32 function, believe it
175 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
176 // Text mode brain damage will kill us if we're trying to do bytewise
178 static char* readfile(const char* file, int* lenOut)
181 if(stat(file, &data) != 0) return 0;
182 FILE* f = fopen(file, "rb");
184 char* buf = new char[data.st_size];
185 *lenOut = fread(buf, 1, data.st_size, f);
187 if(*lenOut != data.st_size) {
188 // Shouldn't happen, but warn anyway since it represents a
189 // platform bug and not a typical runtime error (missing file,
191 SG_LOG(SG_NASAL, SG_ALERT,
192 "ERROR in Nasal initialization: " <<
193 "short count returned from fread() of " << file <<
194 ". Check your C library!");
201 FGNasalSys::FGNasalSys()
208 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
209 _log->truncateAt(255);
210 sglog().addCallback(_log);
212 naSetErrorHandler(&logError);
215 // Utility. Sets a named key in a hash by C string, rather than nasal
217 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
219 naRef s = naNewString(_context);
220 naStr_fromdata(s, (char*)key, strlen(key));
221 naHash_set(hash, s, val);
224 void FGNasalSys::globalsSet(const char* key, naRef val)
226 hashset(_globals, key, val);
229 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
231 return callMethod(code, naNil(), argc, args, locals);
234 // Does a naCall() in a new context. Wrapped here to make lock
235 // tracking easier. Extension functions are called with the lock, but
236 // we have to release it before making a new naCall(). So rather than
237 // drop the lock in every extension function that might call back into
238 // Nasal, we keep a stack depth counter here and only unlock/lock
239 // around the naCall if it isn't the first one.
241 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
243 return naCallMethod(code, self, argc, args, locals);
246 FGNasalSys::~FGNasalSys()
249 map<int, FGNasalListener *>::iterator it, end = _listener.end();
250 for(it = _listener.begin(); it != end; ++it)
253 naFreeContext(_context);
258 bool FGNasalSys::parseAndRun(const char* sourceCode)
260 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
264 call(code, 0, 0, naNil());
269 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
271 FGNasalScript* script = new FGNasalScript();
272 script->_gcKey = -1; // important, if we delete it on a parse
273 script->_nas = this; // error, don't clobber a real handle!
277 sprintf(buf, "FGNasalScript@%p", (void *)script);
281 script->_code = parse(name, src, strlen(src));
282 if(naIsNil(script->_code)) {
287 script->_gcKey = gcSave(script->_code);
292 // The get/setprop functions accept a *list* of strings and walk
293 // through the property tree with them to find the appropriate node.
294 // This allows a Nasal object to hold onto a property path and use it
295 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
296 // is the utility function that walks the property tree.
297 // Future enhancement: support integer arguments to specify array
299 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
301 SGPropertyNode* p = globals->get_props();
303 for(int i=0; i<len; i++) {
305 if(!naIsString(a)) return 0;
306 p = p->getNode(naStr_data(a));
309 } catch (const string& err) {
310 naRuntimeError(c, (char *)err.c_str());
316 // getprop() extension function. Concatenates its string arguments as
317 // property names and returns the value of the specified property. Or
318 // nil if it doesn't exist.
319 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
321 using namespace simgear;
322 const SGPropertyNode* p = findnode(c, args, argc);
323 if(!p) return naNil();
325 switch(p->getType()) {
326 case props::BOOL: case props::INT:
327 case props::LONG: case props::FLOAT:
330 double dv = p->getDoubleValue();
331 if (SGMisc<double>::isNaN(dv)) {
332 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
340 case props::UNSPECIFIED:
342 naRef nastr = naNewString(c);
343 const char* val = p->getStringValue();
344 naStr_fromdata(nastr, (char*)val, strlen(val));
347 case props::ALIAS: // <--- FIXME, recurse?
353 // setprop() extension function. Concatenates its string arguments as
354 // property names and sets the value of the specified property to the
356 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
359 char buf[BUFLEN + 1];
363 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
364 for(int i=0; i<argc-1; i++) {
365 naRef s = naStringValue(c, args[i]);
366 if(naIsNil(s)) return naNil();
367 strncpy(p, naStr_data(s), buflen);
369 buflen = BUFLEN - (p - buf);
370 if(i < (argc-2) && buflen > 0) {
376 SGPropertyNode* props = globals->get_props();
377 naRef val = args[argc-1];
380 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
382 naRef n = naNumValue(val);
384 naRuntimeError(c, "setprop() value is not string or number");
386 if (SGMisc<double>::isNaN(n.num)) {
387 naRuntimeError(c, "setprop() passed a NaN");
390 result = props->setDoubleValue(buf, n.num);
392 } catch (const string& err) {
393 naRuntimeError(c, (char *)err.c_str());
395 return naNum(result);
399 // print() extension function. Concatenates and prints its arguments
400 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
401 // make sure it appears. Is there better way to do this?
402 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
406 for(int i=0; i<n; i++) {
407 naRef s = naStringValue(c, args[i]);
408 if(naIsNil(s)) continue;
409 buf += naStr_data(s);
411 SG_LOG(SG_NASAL, SG_ALERT, buf);
412 return naNum(buf.length());
415 // logprint() extension function. Same as above, all arguments after the
416 // first argument are concatenated. Argument 0 is the log-level, matching
418 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
421 naRuntimeError(c, "no prioirty argument to logprint()");
423 naRef priority = args[0];
426 for(int i=1; i<n; i++) {
427 naRef s = naStringValue(c, args[i]);
428 if(naIsNil(s)) continue;
429 buf += naStr_data(s);
431 // use the nasal source file and line for the message location, since
432 // that's more useful than the location here!
433 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
434 naStr_data(naGetSourceFile(c, 0)),
435 naGetLine(c, 0), buf);
436 return naNum(buf.length());
440 // fgcommand() extension function. Executes a named command via the
441 // FlightGear command manager. Takes a single property node name as
443 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
445 naRef cmd = argc > 0 ? args[0] : naNil();
446 naRef props = argc > 1 ? args[1] : naNil();
447 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
448 naRuntimeError(c, "bad arguments to fgcommand()");
449 SGPropertyNode_ptr tmp, *node;
451 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
453 tmp = new SGPropertyNode();
456 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
459 // settimer(func, dt, simtime) extension function. Falls through to
460 // FGNasalSys::setTimer(). See there for docs.
461 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
463 nasalSys->setTimer(c, argc, args);
467 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
469 if (!naIsNum(args[0])) {
470 naRuntimeError(c, "bad interval argument to maketimer");
473 naRef func, self = naNil();
474 if (naIsFunc(args[1])) {
476 } else if ((argc == 3) && naIsFunc(args[2])) {
481 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
482 return NasalTimerObj::create(c, timerObj);
485 // setlistener(func, property, bool) extension function. Falls through to
486 // FGNasalSys::setListener(). See there for docs.
487 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
489 return nasalSys->setListener(c, argc, args);
492 // removelistener(int) extension function. Falls through to
493 // FGNasalSys::removeListener(). See there for docs.
494 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
496 return nasalSys->removeListener(c, argc, args);
499 // Returns a ghost handle to the argument to the currently executing
501 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
503 return nasalSys->cmdArgGhost();
506 // Sets up a property interpolation. The first argument is either a
507 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
508 // interpolate. The second argument is a vector of pairs of
509 // value/delta numbers.
510 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
512 SGPropertyNode* node;
513 naRef prop = argc > 0 ? args[0] : naNil();
514 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
515 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
518 naRef curve = argc > 1 ? args[1] : naNil();
519 if(!naIsVector(curve)) return naNil();
520 int nPoints = naVec_size(curve) / 2;
522 simgear::PropertyList value_nodes;
523 value_nodes.reserve(nPoints);
525 deltas.reserve(nPoints);
527 for( int i = 0; i < nPoints; ++i )
529 SGPropertyNode* val = new SGPropertyNode;
530 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
531 value_nodes.push_back(val);
532 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
535 node->interpolate("numeric", value_nodes, deltas, "linear");
539 // This is a better RNG than the one in the default Nasal distribution
540 // (which is based on the C library rand() implementation). It will
542 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
544 return naNum(sg_random());
547 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
553 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
559 // Return an array listing of all files in a directory
560 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
562 if(argc != 1 || !naIsString(args[0]))
563 naRuntimeError(c, "bad arguments to directory()");
565 simgear::Dir d(SGPath(naStr_data(args[0])));
566 if(!d.exists()) return naNil();
567 naRef result = naNewVector(c);
569 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
570 for (unsigned int i=0; i<paths.size(); ++i) {
571 std::string p = paths[i].file();
572 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
579 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
581 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
583 if(argc != 1 || !naIsString(args[0]))
584 naRuntimeError(c, "bad arguments to resolveDataPath()");
586 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
587 const char* pdata = p.c_str();
588 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
591 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
593 if(argc != 1 || !naIsString(args[0]))
594 naRuntimeError(c, "bad arguments to findDataDir()");
596 SGPath p = globals->find_data_dir(naStr_data(args[0]));
597 const char* pdata = p.c_str();
598 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
601 class NasalCommand : public SGCommandMgr::Command
604 NasalCommand(FGNasalSys* sys, naRef f) :
608 _gcRoot = sys->gcSave(f);
611 virtual ~NasalCommand()
613 _sys->gcRelease(_gcRoot);
616 virtual bool operator()(const SGPropertyNode* aNode)
618 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
620 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
622 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
633 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
635 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
636 naRuntimeError(c, "bad arguments to addcommand()");
638 naRef func = args[1];
639 NasalCommand* cmd = new NasalCommand(nasalSys, func);
640 globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
644 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
646 SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
648 // SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
656 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
658 // <path> ... absolute path to an XML file
659 // <start-tag> ... callback function with two args: tag name, attribute hash
660 // <end-tag> ... callback function with one arg: tag name
661 // <data> ... callback function with one arg: data
662 // <pi> ... callback function with two args: target, data
663 // (pi = "processing instruction")
664 // All four callback functions are optional and default to nil.
665 // The function returns nil on error, or the validated file name otherwise.
666 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
668 if(argc < 1 || !naIsString(args[0]))
669 naRuntimeError(c, "parsexml(): path argument missing or not a string");
670 if(argc > 5) argc = 5;
671 for(int i=1; i<argc; i++)
672 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
673 naRuntimeError(c, "parsexml(): callback argument not a function");
675 const char* file = fgValidatePath(naStr_data(args[0]), false);
677 naRuntimeError(c, "parsexml(): reading '%s' denied "
678 "(unauthorized access)", naStr_data(args[0]));
681 std::ifstream input(file);
682 NasalXMLVisitor visitor(c, argc, args);
684 readXML(input, visitor);
685 } catch (const sg_exception& e) {
686 naRuntimeError(c, "parsexml(): file '%s' %s",
687 file, e.getFormattedMessage().c_str());
690 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
693 // Return UNIX epoch time in seconds.
694 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
698 GetSystemTimeAsFileTime(&ft);
699 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
700 // Converts from 100ns units in 1601 epoch to unix epoch in sec
701 return naNum((t * 1e-7) - 11644473600.0);
704 gettimeofday(&td, 0);
705 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
709 // Table of extension functions. Terminate with zeros.
710 static struct { const char* name; naCFunction func; } funcs[] = {
711 { "getprop", f_getprop },
712 { "setprop", f_setprop },
713 { "print", f_print },
714 { "logprint", f_logprint },
715 { "_fgcommand", f_fgcommand },
716 { "settimer", f_settimer },
717 { "maketimer", f_makeTimer },
718 { "_setlistener", f_setlistener },
719 { "removelistener", f_removelistener },
720 { "addcommand", f_addCommand },
721 { "removecommand", f_removeCommand },
722 { "_cmdarg", f_cmdarg },
723 { "_interpolate", f_interpolate },
725 { "srand", f_srand },
726 { "abort", f_abort },
727 { "directory", f_directory },
728 { "resolvepath", f_resolveDataPath },
729 { "finddata", f_findDataDir },
730 { "parsexml", f_parsexml },
731 { "systime", f_systime },
735 naRef FGNasalSys::cmdArgGhost()
737 return propNodeGhost(_cmdArg);
740 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
745 void FGNasalSys::init()
749 _context = naNewContext();
751 // Start with globals. Add it to itself as a recursive
752 // sub-reference under the name "globals". This gives client-code
753 // write access to the namespace if someone wants to do something
755 _globals = naInit_std(_context);
756 naSave(_context, _globals);
757 hashset(_globals, "globals", _globals);
759 hashset(_globals, "math", naInit_math(_context));
760 hashset(_globals, "bits", naInit_bits(_context));
761 hashset(_globals, "io", naInit_io(_context));
762 hashset(_globals, "thread", naInit_thread(_context));
763 hashset(_globals, "utf8", naInit_utf8(_context));
765 // Add our custom extension functions:
766 for(i=0; funcs[i].name; i++)
767 hashset(_globals, funcs[i].name,
768 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
770 // And our SGPropertyNode wrapper
771 hashset(_globals, "props", genPropsModule());
773 // Add string methods
774 _string = naInit_string(_context);
775 naSave(_context, _string);
776 initNasalString(_globals, _string, _context);
778 initNasalPositioned(_globals, _context);
779 initNasalPositioned_cppbind(_globals, _context);
780 NasalClipboard::init(this);
781 initNasalCanvas(_globals, _context);
782 initNasalCondition(_globals, _context);
783 initNasalHTTP(_globals, _context);
785 NasalTimerObj::init("Timer")
786 .method("start", &TimerObj::start)
787 .method("stop", &TimerObj::stop)
788 .method("restart", &TimerObj::restart)
789 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
790 .member("isRunning", &TimerObj::isRunning);
792 // Now load the various source files in the Nasal directory
793 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
794 loadScriptDirectory(nasalDir);
796 // Add modules in Nasal subdirectories to property tree
797 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
798 simgear::Dir::NO_DOT_OR_DOTDOT, "");
799 for (unsigned int i=0; i<directories.size(); ++i) {
800 simgear::Dir dir(directories[i]);
801 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
802 addModule(directories[i].file(), scripts);
805 // set signal and remove node to avoid restoring at reinit
806 const char *s = "nasal-dir-initialized";
807 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
808 signal->setBoolValue(s, true);
809 signal->removeChildren(s, false);
811 // Pull scripts out of the property tree, too
812 loadPropertyScripts();
814 // now Nasal modules are loaded, we can do some delayed work
815 postinitNasalPositioned(_globals, _context);
816 postinitNasalGUI(_globals, _context);
819 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
821 static naRef wrapNodeFunc = naNil();
822 if (naIsNil(wrapNodeFunc)) {
823 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
824 wrapNodeFunc = props.get("wrapNode");
828 args[0] = propNodeGhost(aProps);
829 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
832 void FGNasalSys::update(double)
834 if( NasalClipboard::getInstance() )
835 NasalClipboard::getInstance()->update();
837 if(!_dead_listener.empty()) {
838 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
839 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
840 _dead_listener.clear();
843 if (!_loadList.empty())
848 // process Nasal load hook (only one per update loop to avoid excessive lags)
849 _loadList.pop()->load();
852 if (!_unloadList.empty())
854 // process pending Nasal unload hooks after _all_ load hooks were processed
855 // (only unload one per update loop to avoid excessive lags)
856 _unloadList.pop()->unload();
859 // The global context is a legacy thing. We use dynamically
860 // created contexts for naCall() now, so that we can call them
861 // recursively. But there are still spots that want to use it for
862 // naNew*() calls, which end up leaking memory because the context
863 // only clears out its temporary vector when it's *used*. So just
864 // junk it and fetch a new/reinitialized one every frame. This is
865 // clumsy: the right solution would use the dynamic context in all
866 // cases and eliminate _context entirely. But that's more work,
867 // and this works fine (yes, they say "New" and "Free", but
868 // they're very fast, just trust me). -Andy
869 naFreeContext(_context);
870 _context = naNewContext();
873 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
875 return p1.file() < p2.file();
878 // Loads all scripts in given directory
879 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
881 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
882 // Note: simgear::Dir already reports file entries in a deterministic order,
883 // so a fixed loading sequence is guaranteed (same for every user)
884 for (unsigned int i=0; i<scripts.size(); ++i) {
885 SGPath fullpath(scripts[i]);
886 SGPath file = fullpath.file();
887 loadModule(fullpath, file.base().c_str());
891 // Create module with list of scripts
892 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
894 if (! scripts.empty())
896 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
897 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
898 for (unsigned int i=0; i<scripts.size(); ++i) {
899 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
900 pFileNode->setStringValue(scripts[i].c_str());
902 if (!module_node->hasChild("enabled",0))
904 SGPropertyNode* node = module_node->getChild("enabled",0,true);
905 node->setBoolValue(true);
906 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
911 // Loads the scripts found under /nasal in the global tree
912 void FGNasalSys::loadPropertyScripts()
914 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
917 for(int i=0; i<nasal->nChildren(); i++)
919 SGPropertyNode* n = nasal->getChild(i);
920 loadPropertyScripts(n);
924 // Loads the scripts found under /nasal in the global tree
925 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
927 bool is_loaded = false;
929 const char* module = n->getName();
930 if(n->hasChild("module"))
931 module = n->getStringValue("module");
932 if (n->getBoolValue("enabled",true))
934 // allow multiple files to be specified within a single
938 bool file_specified = false;
940 while((fn = n->getChild("file", j)) != NULL) {
941 file_specified = true;
942 const char* file = fn->getStringValue();
944 if (!p.isAbsolute() || !p.exists())
946 p = globals->resolve_maybe_aircraft_path(file);
949 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
950 file << "' for module '" << module << "'.");
953 ok &= p.isNull() ? false : loadModule(p, module);
957 const char* src = n->getStringValue("script");
958 if(!n->hasChild("script")) src = 0; // Hrm...
960 createModule(module, n->getPath().c_str(), src, strlen(src));
962 if(!file_specified && !src)
964 // module no longer exists - clear the archived "enable" flag
965 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
966 SGPropertyNode* node = n->getChild("enabled",0,false);
968 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
970 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
971 "no <file> or <script> defined in " <<
972 "/nasal/" << module);
979 SGPropertyNode* enable = n->getChild("enabled");
982 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
983 enable->addChangeListener(listener, false);
986 SGPropertyNode* loaded = n->getChild("loaded",0,true);
987 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
988 loaded->setBoolValue(is_loaded);
991 // Logs a runtime error, with stack trace, to the FlightGear log stream
992 void FGNasalSys::logError(naContext context)
994 SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
995 int stack_depth = naStackDepth(context);
996 if( stack_depth < 1 )
998 SG_LOG(SG_NASAL, SG_ALERT,
999 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1000 ", line " << naGetLine(context, 0));
1001 for(int i=1; i<stack_depth; i++)
1002 SG_LOG(SG_NASAL, SG_ALERT,
1003 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1004 ", line " << naGetLine(context, i));
1007 // Reads a script file, executes it, and places the resulting
1008 // namespace into the global namespace under the specified module
1010 bool FGNasalSys::loadModule(SGPath file, const char* module)
1013 char* buf = readfile(file.c_str(), &len);
1015 SG_LOG(SG_NASAL, SG_ALERT,
1016 "Nasal error: could not read script file " << file.c_str()
1017 << " into module " << module);
1021 bool ok = createModule(module, file.c_str(), buf, len);
1026 // Parse and run. Save the local variables namespace, as it will
1027 // become a sub-object of globals. The optional "arg" argument can be
1028 // used to pass an associated property node to the module, which can then
1029 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1030 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1031 const char* src, int len,
1032 const SGPropertyNode* cmdarg,
1033 int argc, naRef* args)
1035 naRef code = parse(fileName, src, len);
1039 // See if we already have a module hash to use. This allows the
1040 // user to, for example, add functions to the built-in math
1041 // module. Make a new one if necessary.
1043 naRef modname = naNewString(_context);
1044 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1045 if(!naHash_get(_globals, modname, &locals))
1046 locals = naNewHash(_context);
1048 _cmdArg = (SGPropertyNode*)cmdarg;
1050 call(code, argc, args, locals);
1051 hashset(_globals, moduleName, locals);
1055 void FGNasalSys::deleteModule(const char* moduleName)
1057 naRef modname = naNewString(_context);
1058 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1059 naHash_delete(_globals, modname);
1062 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1065 naRef srcfile = naNewString(_context);
1066 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1067 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1069 SG_LOG(SG_NASAL, SG_ALERT,
1070 "Nasal parse error: " << naGetError(_context) <<
1071 " in "<< filename <<", line " << errLine);
1075 // Bind to the global namespace before returning
1076 return naBindFunction(_context, code, _globals);
1079 bool FGNasalSys::handleCommand( const char* moduleName,
1080 const char* fileName,
1082 const SGPropertyNode* arg )
1084 naRef code = parse(fileName, src, strlen(src));
1085 if(naIsNil(code)) return false;
1087 // Commands can be run "in" a module. Make sure that module
1088 // exists, and set it up as the local variables hash for the
1090 naRef locals = naNil();
1092 naRef modname = naNewString(_context);
1093 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1094 if(!naHash_get(_globals, modname, &locals)) {
1095 locals = naNewHash(_context);
1096 naHash_set(_globals, modname, locals);
1100 // Cache this command's argument for inspection via cmdarg(). For
1101 // performance reasons, we won't bother with it if the invoked
1102 // code doesn't need it.
1103 _cmdArg = (SGPropertyNode*)arg;
1105 call(code, 0, 0, locals);
1109 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1111 const char* src = arg->getStringValue("script");
1112 const char* moduleName = arg->getStringValue("module");
1114 return handleCommand( moduleName,
1115 arg ? arg->getPath(true).c_str() : moduleName,
1120 // settimer(func, dt, simtime) extension function. The first argument
1121 // is a Nasal function to call, the second is a delta time (from now),
1122 // in seconds. The third, if present, is a boolean value indicating
1123 // that "real world" time (rather than simulator time) is to be used.
1125 // Implementation note: the FGTimer objects don't live inside the
1126 // garbage collector, so the Nasal handler functions have to be
1127 // "saved" somehow lest they be inadvertently cleaned. In this case,
1128 // they are inserted into a globals.__gcsave hash and removed on
1130 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1132 // Extract the handler, delta, and simtime arguments:
1133 naRef handler = argc > 0 ? args[0] : naNil();
1134 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1135 naRuntimeError(c, "settimer() with invalid function argument");
1139 naRef delta = argc > 1 ? args[1] : naNil();
1140 if(naIsNil(delta)) {
1141 naRuntimeError(c, "settimer() with invalid time argument");
1145 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1147 // Generate and register a C++ timer handler
1148 NasalTimer* t = new NasalTimer;
1149 t->handler = handler;
1150 t->gcKey = gcSave(handler);
1153 globals->get_event_mgr()->addEvent("NasalTimer",
1154 t, &NasalTimer::timerExpired,
1155 delta.num, simtime);
1158 void FGNasalSys::handleTimer(NasalTimer* t)
1160 call(t->handler, 0, 0, naNil());
1161 gcRelease(t->gcKey);
1164 int FGNasalSys::gcSave(naRef r)
1169 void FGNasalSys::gcRelease(int key)
1174 void FGNasalSys::NasalTimer::timerExpired()
1176 nasal->handleTimer(this);
1180 int FGNasalSys::_listenerId = 0;
1182 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1183 // Attaches a callback function to a property (specified as a global
1184 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1185 // optional argument (default=0) is set to 1, then the function is also
1186 // called initially. If the fourth, optional argument is set to 0, then the
1187 // function is only called when the property node value actually changes.
1188 // Otherwise it's called independent of the value whenever the node is
1189 // written to (default). The setlistener() function returns a unique
1190 // id number, which is to be used as argument to the removelistener()
1192 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1194 SGPropertyNode_ptr node;
1195 naRef prop = argc > 0 ? args[0] : naNil();
1196 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1197 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1199 naRuntimeError(c, "setlistener() with invalid property argument");
1204 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1207 naRef code = argc > 1 ? args[1] : naNil();
1208 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1209 naRuntimeError(c, "setlistener() with invalid function argument");
1213 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1214 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1215 FGNasalListener *nl = new FGNasalListener(node, code, this,
1216 gcSave(code), _listenerId, init, type);
1218 node->addChangeListener(nl, init != 0);
1220 _listener[_listenerId] = nl;
1221 return naNum(_listenerId++);
1224 // removelistener(int) extension function. The argument is the id of
1225 // a listener as returned by the setlistener() function.
1226 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1228 naRef id = argc > 0 ? args[0] : naNil();
1229 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1231 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1232 naRuntimeError(c, "removelistener() with invalid listener id");
1236 it->second->_dead = true;
1237 _dead_listener.push_back(it->second);
1238 _listener.erase(it);
1239 return naNum(_listener.size());
1242 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1244 if( _loadList.empty() )
1246 _loadList.push(data);
1249 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1251 _unloadList.push(data);
1254 //////////////////////////////////////////////////////////////////////////
1255 // FGNasalListener class.
1257 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1258 FGNasalSys* nasal, int key, int id,
1259 int init, int type) :
1272 if(_type == 0 && !_init)
1276 FGNasalListener::~FGNasalListener()
1278 _node->removeChangeListener(this);
1279 _nas->gcRelease(_gcKey);
1282 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1284 if(_active || _dead) return;
1287 arg[0] = _nas->propNodeGhost(which);
1288 arg[1] = _nas->propNodeGhost(_node);
1289 arg[2] = mode; // value changed, child added/removed
1290 arg[3] = naNum(_node != which); // child event?
1291 _nas->call(_code, 4, arg, naNil());
1295 void FGNasalListener::valueChanged(SGPropertyNode* node)
1297 if(_type < 2 && node != _node) return; // skip child events
1298 if(_type > 0 || changed(_node) || _init)
1299 call(node, naNum(0));
1304 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1306 if(_type == 2) call(child, naNum(1));
1309 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1311 if(_type == 2) call(child, naNum(-1));
1314 bool FGNasalListener::changed(SGPropertyNode* node)
1316 using namespace simgear;
1317 props::Type type = node->getType();
1318 if(type == props::NONE) return false;
1319 if(type == props::UNSPECIFIED) return true;
1327 long l = node->getLongValue();
1328 result = l != _last_int;
1335 double d = node->getDoubleValue();
1336 result = d != _last_float;
1342 string s = node->getStringValue();
1343 result = s != _last_string;
1350 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1352 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1353 _c(naSubContext(c)),
1354 _start_element(argc > 1 ? args[1] : naNil()),
1355 _end_element(argc > 2 ? args[2] : naNil()),
1356 _data(argc > 3 ? args[3] : naNil()),
1357 _pi(argc > 4 ? args[4] : naNil())
1361 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1363 if(naIsNil(_start_element)) return;
1364 naRef attr = naNewHash(_c);
1365 for(int i=0; i<a.size(); i++) {
1366 naRef name = make_string(a.getName(i));
1367 naRef value = make_string(a.getValue(i));
1368 naHash_set(attr, name, value);
1370 call(_start_element, 2, make_string(tag), attr);
1373 void NasalXMLVisitor::endElement(const char* tag)
1375 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1378 void NasalXMLVisitor::data(const char* str, int len)
1380 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1383 void NasalXMLVisitor::pi(const char* target, const char* data)
1385 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1388 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1393 naCall(_c, func, num, args, naNil(), naNil());
1398 naRef NasalXMLVisitor::make_string(const char* s, int n)
1400 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1401 n < 0 ? strlen(s) : n);