13 #include <simgear/nasal/nasal.h>
14 #include <simgear/props/props.hxx>
15 #include <simgear/math/sg_random.h>
16 #include <simgear/misc/sg_path.hxx>
17 #include <simgear/misc/interpolator.hxx>
18 #include <simgear/structure/commands.hxx>
20 #include <Main/globals.hxx>
21 #include <Main/fg_props.hxx>
23 #include "NasalSys.hxx"
25 // Read and return file contents in a single buffer. Note use of
26 // stat() to get the file size. This is a win32 function, believe it
27 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
28 // Text mode brain damage will kill us if we're trying to do bytewise
30 static char* readfile(const char* file, int* lenOut)
33 if(stat(file, &data) != 0) return 0;
34 FILE* f = fopen(file, "rb");
36 char* buf = new char[data.st_size];
37 *lenOut = fread(buf, 1, data.st_size, f);
39 if(*lenOut != data.st_size) {
40 // Shouldn't happen, but warn anyway since it represents a
41 // platform bug and not a typical runtime error (missing file,
43 SG_LOG(SG_NASAL, SG_ALERT,
44 "ERROR in Nasal initialization: " <<
45 "short count returned from fread() of " << file <<
46 ". Check your C library!");
53 FGNasalSys::FGNasalSys()
58 _nextGCKey = 0; // Any value will do
60 _purgeListeners = false;
63 // Does a naCall() in a new context. Wrapped here to make lock
64 // tracking easier. Extension functions are called with the lock, but
65 // we have to release it before making a new naCall(). So rather than
66 // drop the lock in every extension function that might call back into
67 // Nasal, we keep a stack depth counter here and only unlock/lock
68 // around the naCall if it isn't the first one.
69 naRef FGNasalSys::call(naRef code, naRef locals)
71 naContext ctx = naNewContext();
72 if(_callCount) naModUnlock();
74 naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
78 if(_callCount) naModLock();
83 FGNasalSys::~FGNasalSys()
85 map<int, FGNasalListener *>::iterator it, end = _listener.end();
86 for(it = _listener.begin(); it != end; ++it)
89 naFreeContext(_context);
93 bool FGNasalSys::parseAndRun(const char* sourceCode)
95 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
103 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
105 FGNasalScript* script = new FGNasalScript();
106 script->_gcKey = -1; // important, if we delete it on a parse
107 script->_nas = this; // error, don't clobber a real handle!
111 sprintf(buf, "FGNasalScript@%p", script);
115 script->_code = parse(name, src, strlen(src));
116 if(naIsNil(script->_code)) {
121 script->_gcKey = gcSave(script->_code);
125 // Utility. Sets a named key in a hash by C string, rather than nasal
127 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
129 naRef s = naNewString(_context);
130 naStr_fromdata(s, (char*)key, strlen(key));
131 naHash_set(hash, s, val);
134 // The get/setprop functions accept a *list* of strings and walk
135 // through the property tree with them to find the appropriate node.
136 // This allows a Nasal object to hold onto a property path and use it
137 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
138 // is the utility function that walks the property tree.
139 // Future enhancement: support integer arguments to specify array
141 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
143 SGPropertyNode* p = globals->get_props();
145 for(int i=0; i<len; i++) {
147 if(!naIsString(a)) return 0;
148 p = p->getNode(naStr_data(a));
151 } catch (const string& err) {
152 naRuntimeError(c, (char *)err.c_str());
158 // getprop() extension function. Concatenates its string arguments as
159 // property names and returns the value of the specified property. Or
160 // nil if it doesn't exist.
161 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
163 const SGPropertyNode* p = findnode(c, args, argc);
164 if(!p) return naNil();
166 switch(p->getType()) {
167 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
168 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
169 case SGPropertyNode::DOUBLE:
170 return naNum(p->getDoubleValue());
172 case SGPropertyNode::STRING:
173 case SGPropertyNode::UNSPECIFIED:
175 naRef nastr = naNewString(c);
176 const char* val = p->getStringValue();
177 naStr_fromdata(nastr, (char*)val, strlen(val));
180 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
186 // setprop() extension function. Concatenates its string arguments as
187 // property names and sets the value of the specified property to the
189 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
192 char buf[BUFLEN + 1];
196 for(int i=0; i<argc-1; i++) {
197 naRef s = naStringValue(c, args[i]);
198 if(naIsNil(s)) return naNil();
199 strncpy(p, naStr_data(s), buflen);
201 buflen = BUFLEN - (p - buf);
202 if(i < (argc-2) && buflen > 0) {
208 SGPropertyNode* props = globals->get_props();
209 naRef val = args[argc-1];
211 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
213 naRef n = naNumValue(val);
215 naRuntimeError(c, "setprop() value is not string or number");
216 props->setDoubleValue(buf, n.num);
218 } catch (const string& err) {
219 naRuntimeError(c, (char *)err.c_str());
225 // print() extension function. Concatenates and prints its arguments
226 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
227 // make sure it appears. Is there better way to do this?
228 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
232 for(int i=0; i<n; i++) {
233 naRef s = naStringValue(c, args[i]);
234 if(naIsNil(s)) continue;
235 buf += naStr_data(s);
237 SG_LOG(SG_GENERAL, SG_ALERT, buf);
238 return naNum(buf.length());
241 // fgcommand() extension function. Executes a named command via the
242 // FlightGear command manager. Takes a single property node name as
244 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
246 if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
247 naRuntimeError(c, "bad arguments to fgcommand()");
248 naRef cmd = args[0], props = args[1];
249 SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
250 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
253 // settimer(func, dt, simtime) extension function. Falls through to
254 // FGNasalSys::setTimer(). See there for docs.
255 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
257 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
258 nasal->setTimer(argc, args);
262 // setlistener(func, property, bool) extension function. Falls through to
263 // FGNasalSys::setListener(). See there for docs.
264 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
266 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
267 return nasal->setListener(c, argc, args);
270 // removelistener(int) extension function. Falls through to
271 // FGNasalSys::removeListener(). See there for docs.
272 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
274 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
275 return nasal->removeListener(c, argc, args);
278 // Returns a ghost handle to the argument to the currently executing
280 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
282 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
283 return nasal->cmdArgGhost();
286 // Sets up a property interpolation. The first argument is either a
287 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
288 // interpolate. The second argument is a vector of pairs of
289 // value/delta numbers.
290 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
292 SGPropertyNode* node;
293 naRef prop = argc > 0 ? args[0] : naNil();
294 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
295 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
298 naRef curve = argc > 1 ? args[1] : naNil();
299 if(!naIsVector(curve)) return naNil();
300 int nPoints = naVec_size(curve) / 2;
301 double* values = new double[nPoints];
302 double* deltas = new double[nPoints];
303 for(int i=0; i<nPoints; i++) {
304 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
305 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
308 ((SGInterpolator*)globals->get_subsystem("interpolator"))
309 ->interpolate(node, nPoints, values, deltas);
314 // This is a better RNG than the one in the default Nasal distribution
315 // (which is based on the C library rand() implementation). It will
317 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
319 return naNum(sg_random());
322 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
328 // Return an array listing of all files in a directory
329 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
331 if(argc != 1 || !naIsString(args[0]))
332 naRuntimeError(c, "bad arguments to directory()");
333 naRef ldir = args[0];
334 ulDir* dir = ulOpenDir(naStr_data(args[0]));
335 if(!dir) return naNil();
336 naRef result = naNewVector(c);
338 while((dent = ulReadDir(dir)))
339 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
340 strlen(dent->d_name)));
345 // Table of extension functions. Terminate with zeros.
346 static struct { char* name; naCFunction func; } funcs[] = {
347 { "getprop", f_getprop },
348 { "setprop", f_setprop },
349 { "print", f_print },
350 { "_fgcommand", f_fgcommand },
351 { "settimer", f_settimer },
352 { "_setlistener", f_setlistener },
353 { "removelistener", f_removelistener },
354 { "_cmdarg", f_cmdarg },
355 { "_interpolate", f_interpolate },
357 { "srand", f_srand },
358 { "directory", f_directory },
362 naRef FGNasalSys::cmdArgGhost()
364 return propNodeGhost(_cmdArg);
367 void FGNasalSys::init()
371 _context = naNewContext();
373 // Start with globals. Add it to itself as a recursive
374 // sub-reference under the name "globals". This gives client-code
375 // write access to the namespace if someone wants to do something
377 _globals = naInit_std(_context);
378 naSave(_context, _globals);
379 hashset(_globals, "globals", _globals);
381 hashset(_globals, "math", naInit_math(_context));
382 hashset(_globals, "bits", naInit_bits(_context));
383 hashset(_globals, "io", naInit_io(_context));
384 hashset(_globals, "thread", naInit_thread(_context));
385 hashset(_globals, "utf8", naInit_utf8(_context));
387 // Add our custom extension functions:
388 for(i=0; funcs[i].name; i++)
389 hashset(_globals, funcs[i].name,
390 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
392 // And our SGPropertyNode wrapper
393 hashset(_globals, "props", genPropsModule());
395 // Make a "__gcsave" hash to hold the naRef objects which get
396 // passed to handles outside the interpreter (to protect them from
397 // begin garbage-collected).
398 _gcHash = naNewHash(_context);
399 hashset(_globals, "__gcsave", _gcHash);
401 // Now load the various source files in the Nasal directory
402 SGPath p(globals->get_fg_root());
405 ulDir* dir = ulOpenDir(p.c_str());
406 while(dir && (dent = ulReadDir(dir)) != 0) {
408 fullpath.append(dent->d_name);
409 SGPath file(dent->d_name);
410 if(file.extension() != "nas") continue;
411 loadModule(fullpath, file.base().c_str());
415 // set signal and remove node to avoid restoring at reinit
416 const char *s = "nasal-dir-initialized";
417 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
418 signal->setBoolValue(s, true);
419 signal->removeChildren(s);
421 // Pull scripts out of the property tree, too
422 loadPropertyScripts();
425 void FGNasalSys::update(double)
427 if(_purgeListeners) {
428 _purgeListeners = false;
429 map<int, FGNasalListener *>::iterator it;
430 for(it = _listener.begin(); it != _listener.end();) {
431 FGNasalListener *nl = it->second;
433 _listener.erase(it++);
442 // Loads the scripts found under /nasal in the global tree
443 void FGNasalSys::loadPropertyScripts()
445 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
448 for(int i=0; i<nasal->nChildren(); i++) {
449 SGPropertyNode* n = nasal->getChild(i);
451 const char* module = n->getName();
452 if(n->hasChild("module"))
453 module = n->getStringValue("module");
455 // allow multiple files to be specified within in a single
459 bool file_specified = false;
460 while ( (fn = n->getChild("file", j)) != NULL ) {
461 file_specified = true;
462 const char* file = fn->getStringValue();
463 SGPath p(globals->get_fg_root());
465 loadModule(p, module);
469 // Old code which only allowed a single file to be specified per module
471 const char* file = n->getStringValue("file");
472 if(!n->hasChild("file")) file = 0; // Hrm...
474 SGPath p(globals->get_fg_root());
476 loadModule(p, module);
480 const char* src = n->getStringValue("script");
481 if(!n->hasChild("script")) src = 0; // Hrm...
483 createModule(module, n->getPath(), src, strlen(src));
485 if(!file_specified && !src)
486 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
487 "no <file> or <script> defined in " <<
488 "/nasal/" << module);
492 // Logs a runtime error, with stack trace, to the FlightGear log stream
493 void FGNasalSys::logError(naContext context)
495 SG_LOG(SG_NASAL, SG_ALERT,
496 "Nasal runtime error: " << naGetError(context));
497 SG_LOG(SG_NASAL, SG_ALERT,
498 " at " << naStr_data(naGetSourceFile(context, 0)) <<
499 ", line " << naGetLine(context, 0));
500 for(int i=1; i<naStackDepth(context); i++)
501 SG_LOG(SG_NASAL, SG_ALERT,
502 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
503 ", line " << naGetLine(context, i));
506 // Reads a script file, executes it, and places the resulting
507 // namespace into the global namespace under the specified module
509 void FGNasalSys::loadModule(SGPath file, const char* module)
512 char* buf = readfile(file.c_str(), &len);
514 SG_LOG(SG_NASAL, SG_ALERT,
515 "Nasal error: could not read script file " << file.c_str()
516 << " into module " << module);
520 createModule(module, file.c_str(), buf, len);
524 // Parse and run. Save the local variables namespace, as it will
525 // become a sub-object of globals. The optional "arg" argument can be
526 // used to pass an associated property node to the module, which can then
527 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
528 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
529 const char* src, int len, const SGPropertyNode* arg)
531 naRef code = parse(fileName, src, len);
535 // See if we already have a module hash to use. This allows the
536 // user to, for example, add functions to the built-in math
537 // module. Make a new one if necessary.
539 naRef modname = naNewString(_context);
540 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
541 if(!naHash_get(_globals, modname, &locals))
542 locals = naNewHash(_context);
544 _cmdArg = (SGPropertyNode*)arg;
547 hashset(_globals, moduleName, locals);
550 void FGNasalSys::deleteModule(const char* moduleName)
552 naRef modname = naNewString(_context);
553 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
554 naHash_delete(_globals, modname);
557 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
560 naRef srcfile = naNewString(_context);
561 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
562 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
564 SG_LOG(SG_NASAL, SG_ALERT,
565 "Nasal parse error: " << naGetError(_context) <<
566 " in "<< filename <<", line " << errLine);
570 // Bind to the global namespace before returning
571 return naBindFunction(_context, code, _globals);
574 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
576 const char* nasal = arg->getStringValue("script");
577 const char* moduleName = arg->getStringValue("module");
578 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
579 if(naIsNil(code)) return false;
581 // Commands can be run "in" a module. Make sure that module
582 // exists, and set it up as the local variables hash for the
584 naRef locals = naNil();
586 naRef modname = naNewString(_context);
587 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
588 if(!naHash_get(_globals, modname, &locals)) {
589 locals = naNewHash(_context);
590 naHash_set(_globals, modname, locals);
594 // Cache this command's argument for inspection via cmdarg(). For
595 // performance reasons, we won't bother with it if the invoked
596 // code doesn't need it.
597 _cmdArg = (SGPropertyNode*)arg;
603 // settimer(func, dt, simtime) extension function. The first argument
604 // is a Nasal function to call, the second is a delta time (from now),
605 // in seconds. The third, if present, is a boolean value indicating
606 // that "real world" time (rather than simulator time) is to be used.
608 // Implementation note: the FGTimer objects don't live inside the
609 // garbage collector, so the Nasal handler functions have to be
610 // "saved" somehow lest they be inadvertently cleaned. In this case,
611 // they are inserted into a globals.__gcsave hash and removed on
613 void FGNasalSys::setTimer(int argc, naRef* args)
615 // Extract the handler, delta, and simtime arguments:
616 naRef handler = argc > 0 ? args[0] : naNil();
617 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
620 naRef delta = argc > 1 ? args[1] : naNil();
621 if(naIsNil(delta)) return;
623 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
625 // Generate and register a C++ timer handler
626 NasalTimer* t = new NasalTimer;
627 t->handler = handler;
628 t->gcKey = gcSave(handler);
631 globals->get_event_mgr()->addEvent("NasalTimer",
632 t, &NasalTimer::timerExpired,
636 void FGNasalSys::handleTimer(NasalTimer* t)
638 call(t->handler, naNil());
642 int FGNasalSys::gcSave(naRef r)
644 int key = _nextGCKey++;
645 naHash_set(_gcHash, naNum(key), r);
649 void FGNasalSys::gcRelease(int key)
651 naHash_delete(_gcHash, naNum(key));
654 void FGNasalSys::NasalTimer::timerExpired()
656 nasal->handleTimer(this);
660 int FGNasalSys::_listenerId = 0;
662 // setlistener(property, func, bool) extension function. The first argument
663 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
664 // path), the second is a Nasal function, the optional third one a bool.
665 // If the bool is true, then the listener is executed initially. The
666 // setlistener() function returns a unique id number, that can be used
667 // as argument to the removelistener() function.
668 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
670 SGPropertyNode_ptr node;
671 naRef prop = argc > 0 ? args[0] : naNil();
672 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
673 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
675 naRuntimeError(c, "setlistener() with invalid property argument");
680 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
683 naRef handler = argc > 1 ? args[1] : naNil();
684 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
685 naRuntimeError(c, "setlistener() with invalid function argument");
689 bool initial = argc > 2 && naTrue(args[2]);
691 FGNasalListener *nl = new FGNasalListener(node, handler, this,
693 node->addChangeListener(nl, initial);
695 _listener[_listenerId] = nl;
696 return naNum(_listenerId++);
699 // removelistener(int) extension function. The argument is the id of
700 // a listener as returned by the setlistener() function.
701 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
703 naRef id = argc > 0 ? args[0] : naNil();
704 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
706 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
707 naRuntimeError(c, "removelistener() with invalid listener id");
711 FGNasalListener *nl = it->second;
714 _purgeListeners = true;
720 return naNum(_listener.size());
725 // FGNasalListener class.
727 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
728 FGNasalSys* nasal, int key) :
738 FGNasalListener::~FGNasalListener()
740 _node->removeChangeListener(this);
741 _nas->gcRelease(_gcKey);
744 void FGNasalListener::valueChanged(SGPropertyNode* node)
746 // drop recursive listener calls
751 _nas->_cmdArg = node;
752 _nas->call(_handler, naNil());
759 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
760 // such a class, then it lets modelLoaded() run the <load> script, and the
761 // destructor the <unload> script. The latter happens when the model branch
762 // is removed from the scene graph.
764 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
767 SGPropertyNode *n = prop->getNode("nasal"), *load;
771 load = n->getNode("load");
772 _unload = n->getNode("unload");
773 if(!load && !_unload)
777 const char *s = load ? load->getStringValue() : "";
778 FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
779 nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
782 FGNasalModelData::~FGNasalModelData()
787 FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
789 SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
790 "without Nasal subsystem present.");
795 const char *s = _unload->getStringValue();
796 nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
798 nas->deleteModule(_module.c_str());