7 # include <sys/time.h> // gettimeofday
12 #include <sys/types.h>
18 #include <simgear/nasal/nasal.h>
19 #include <simgear/props/props.hxx>
20 #include <simgear/math/sg_random.h>
21 #include <simgear/misc/sg_path.hxx>
22 #include <simgear/misc/interpolator.hxx>
23 #include <simgear/scene/material/mat.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
27 #include <Airports/runways.hxx>
28 #include <Airports/simple.hxx>
29 #include <Main/globals.hxx>
30 #include <Main/fg_props.hxx>
31 #include <Scenery/scenery.hxx>
33 #include "NasalSys.hxx"
35 static FGNasalSys* nasalSys = 0;
38 // Read and return file contents in a single buffer. Note use of
39 // stat() to get the file size. This is a win32 function, believe it
40 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
41 // Text mode brain damage will kill us if we're trying to do bytewise
43 static char* readfile(const char* file, int* lenOut)
46 if(stat(file, &data) != 0) return 0;
47 FILE* f = fopen(file, "rb");
49 char* buf = new char[data.st_size];
50 *lenOut = fread(buf, 1, data.st_size, f);
52 if(*lenOut != data.st_size) {
53 // Shouldn't happen, but warn anyway since it represents a
54 // platform bug and not a typical runtime error (missing file,
56 SG_LOG(SG_NASAL, SG_ALERT,
57 "ERROR in Nasal initialization: " <<
58 "short count returned from fread() of " << file <<
59 ". Check your C library!");
66 FGNasalSys::FGNasalSys()
72 _nextGCKey = 0; // Any value will do
74 _purgeListeners = false;
77 // Does a naCall() in a new context. Wrapped here to make lock
78 // tracking easier. Extension functions are called with the lock, but
79 // we have to release it before making a new naCall(). So rather than
80 // drop the lock in every extension function that might call back into
81 // Nasal, we keep a stack depth counter here and only unlock/lock
82 // around the naCall if it isn't the first one.
83 naRef FGNasalSys::call(naRef code, naRef locals)
85 naContext ctx = naNewContext();
86 if(_callCount) naModUnlock();
88 naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
92 if(_callCount) naModLock();
97 FGNasalSys::~FGNasalSys()
100 map<int, FGNasalListener *>::iterator it, end = _listener.end();
101 for(it = _listener.begin(); it != end; ++it)
104 naFreeContext(_context);
108 bool FGNasalSys::parseAndRun(const char* sourceCode)
110 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
118 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
120 FGNasalScript* script = new FGNasalScript();
121 script->_gcKey = -1; // important, if we delete it on a parse
122 script->_nas = this; // error, don't clobber a real handle!
126 sprintf(buf, "FGNasalScript@%p", (void *)script);
130 script->_code = parse(name, src, strlen(src));
131 if(naIsNil(script->_code)) {
136 script->_gcKey = gcSave(script->_code);
140 // Utility. Sets a named key in a hash by C string, rather than nasal
142 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
144 naRef s = naNewString(_context);
145 naStr_fromdata(s, (char*)key, strlen(key));
146 naHash_set(hash, s, val);
149 // The get/setprop functions accept a *list* of strings and walk
150 // through the property tree with them to find the appropriate node.
151 // This allows a Nasal object to hold onto a property path and use it
152 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
153 // is the utility function that walks the property tree.
154 // Future enhancement: support integer arguments to specify array
156 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
158 SGPropertyNode* p = globals->get_props();
160 for(int i=0; i<len; i++) {
162 if(!naIsString(a)) return 0;
163 p = p->getNode(naStr_data(a));
166 } catch (const string& err) {
167 naRuntimeError(c, (char *)err.c_str());
173 // getprop() extension function. Concatenates its string arguments as
174 // property names and returns the value of the specified property. Or
175 // nil if it doesn't exist.
176 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
178 const SGPropertyNode* p = findnode(c, args, argc);
179 if(!p) return naNil();
181 switch(p->getType()) {
182 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
183 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
184 case SGPropertyNode::DOUBLE:
185 return naNum(p->getDoubleValue());
187 case SGPropertyNode::STRING:
188 case SGPropertyNode::UNSPECIFIED:
190 naRef nastr = naNewString(c);
191 const char* val = p->getStringValue();
192 naStr_fromdata(nastr, (char*)val, strlen(val));
195 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
201 // setprop() extension function. Concatenates its string arguments as
202 // property names and sets the value of the specified property to the
204 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
207 char buf[BUFLEN + 1];
211 for(int i=0; i<argc-1; i++) {
212 naRef s = naStringValue(c, args[i]);
213 if(naIsNil(s)) return naNil();
214 strncpy(p, naStr_data(s), buflen);
216 buflen = BUFLEN - (p - buf);
217 if(i < (argc-2) && buflen > 0) {
223 SGPropertyNode* props = globals->get_props();
224 naRef val = args[argc-1];
226 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
228 naRef n = naNumValue(val);
230 naRuntimeError(c, "setprop() value is not string or number");
231 props->setDoubleValue(buf, n.num);
233 } catch (const string& err) {
234 naRuntimeError(c, (char *)err.c_str());
240 // print() extension function. Concatenates and prints its arguments
241 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
242 // make sure it appears. Is there better way to do this?
243 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
247 for(int i=0; i<n; i++) {
248 naRef s = naStringValue(c, args[i]);
249 if(naIsNil(s)) continue;
250 buf += naStr_data(s);
252 SG_LOG(SG_GENERAL, SG_ALERT, buf);
253 return naNum(buf.length());
256 // fgcommand() extension function. Executes a named command via the
257 // FlightGear command manager. Takes a single property node name as
259 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
261 naRef cmd = argc > 0 ? args[0] : naNil();
262 naRef props = argc > 1 ? args[1] : naNil();
263 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
264 naRuntimeError(c, "bad arguments to fgcommand()");
265 SGPropertyNode_ptr tmp, *node;
267 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
269 tmp = new SGPropertyNode();
272 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
275 // settimer(func, dt, simtime) extension function. Falls through to
276 // FGNasalSys::setTimer(). See there for docs.
277 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
279 nasalSys->setTimer(c, argc, args);
283 // setlistener(func, property, bool) extension function. Falls through to
284 // FGNasalSys::setListener(). See there for docs.
285 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
287 return nasalSys->setListener(c, argc, args);
290 // removelistener(int) extension function. Falls through to
291 // FGNasalSys::removeListener(). See there for docs.
292 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
294 return nasalSys->removeListener(c, argc, args);
297 // Returns a ghost handle to the argument to the currently executing
299 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
301 return nasalSys->cmdArgGhost();
304 // Sets up a property interpolation. The first argument is either a
305 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
306 // interpolate. The second argument is a vector of pairs of
307 // value/delta numbers.
308 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
310 SGPropertyNode* node;
311 naRef prop = argc > 0 ? args[0] : naNil();
312 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
313 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
316 naRef curve = argc > 1 ? args[1] : naNil();
317 if(!naIsVector(curve)) return naNil();
318 int nPoints = naVec_size(curve) / 2;
319 double* values = new double[nPoints];
320 double* deltas = new double[nPoints];
321 for(int i=0; i<nPoints; i++) {
322 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
323 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
326 ((SGInterpolator*)globals->get_subsystem_mgr()
327 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
328 ->interpolate(node, nPoints, values, deltas);
333 // This is a better RNG than the one in the default Nasal distribution
334 // (which is based on the C library rand() implementation). It will
336 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
338 return naNum(sg_random());
341 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
347 // Return an array listing of all files in a directory
348 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
350 if(argc != 1 || !naIsString(args[0]))
351 naRuntimeError(c, "bad arguments to directory()");
352 naRef ldir = args[0];
353 ulDir* dir = ulOpenDir(naStr_data(args[0]));
354 if(!dir) return naNil();
355 naRef result = naNewVector(c);
357 while((dent = ulReadDir(dir)))
358 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
359 strlen(dent->d_name)));
365 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
367 // <path> ... absolute path to an XML file
368 // <start-tag> ... callback function with two args: tag name, attribute hash
369 // <end-tag> ... callback function with one arg: tag name
370 // <data> ... callback function with one arg: data
371 // <pi> ... callback function with two args: target, data
372 // (pi = "processing instruction")
373 // All four callback functions are optional and default to nil.
374 // The function returns nil on error, and the file name otherwise.
375 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
377 if(argc < 1 || !naIsString(args[0]))
378 naRuntimeError(c, "parsexml(): path argument missing or not a string");
379 if(argc > 5) argc = 5;
380 for(int i=1; i<argc; i++)
381 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
382 naRuntimeError(c, "parsexml(): callback argument not a function");
384 const char* file = naStr_data(args[0]);
385 std::ifstream input(file);
386 NasalXMLVisitor visitor(c, argc, args);
388 readXML(input, visitor);
389 } catch (const sg_exception& e) {
390 string msg = string("parsexml(): file '") + file + "' "
391 + e.getFormattedMessage();
392 naRuntimeError(c, msg.c_str());
398 // Return UNIX epoch time in seconds.
399 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
403 GetSystemTimeAsFileTime(&ft);
404 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
405 // Converts from 100ns units in 1601 epoch to unix epoch in sec
406 return naNum((t * 1e-7) - 11644473600.0);
410 do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
411 return naNum(t + 1e-6 * td.tv_usec);
416 // Convert a cartesian point to a geodetic lat/lon/altitude.
417 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
419 double lat, lon, alt, xyz[3];
420 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
421 for(int i=0; i<3; i++)
422 xyz[i] = naNumValue(args[i]).num;
423 sgCartToGeod(xyz, &lat, &lon, &alt);
424 lat *= SG_RADIANS_TO_DEGREES;
425 lon *= SG_RADIANS_TO_DEGREES;
426 naRef vec = naNewVector(c);
427 naVec_append(vec, naNum(lat));
428 naVec_append(vec, naNum(lon));
429 naVec_append(vec, naNum(alt));
433 // Convert a geodetic lat/lon/altitude to a cartesian point.
434 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
436 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
437 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
438 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
439 double alt = naNumValue(args[2]).num;
441 sgGeodToCart(lat, lon, alt, xyz);
442 naRef vec = naNewVector(c);
443 naVec_append(vec, naNum(xyz[0]));
444 naVec_append(vec, naNum(xyz[1]));
445 naVec_append(vec, naNum(xyz[2]));
449 // For given geodetic point return array with elevation, and a material data
450 // hash, or nil if there's no information available (tile not loaded). If
451 // information about the material isn't available, then nil is returned instead
453 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
455 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
456 if(argc != 2) naRuntimeError(c, "geodinfo() expects 2 arguments: lat, lon");
457 double lat = naNumValue(args[0]).num;
458 double lon = naNumValue(args[1]).num;
460 const SGMaterial *mat;
461 if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
463 naRef vec = naNewVector(c);
464 naVec_append(vec, naNum(elev));
465 naRef matdata = naNil();
467 matdata = naNewHash(c);
468 naRef names = naNewVector(c);
469 const vector<string> n = mat->get_names();
470 for(unsigned int i=0; i<n.size(); i++)
471 naVec_append(names, naStr_fromdata(naNewString(c),
472 const_cast<char*>(n[i].c_str()), n[i].size()));
473 HASHSET("names", 5, names);
474 HASHSET("solid", 5, naNum(mat->get_solid()));
475 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
476 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
477 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
478 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
479 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
481 naVec_append(vec, matdata);
487 class airport_filter : public FGAirportSearchFilter {
488 virtual bool acceptable(FGAirport *a) { return a->isAirport(); }
491 // Returns airport data for given airport id ("KSFO"), or for the airport
492 // nearest to a given lat/lon pair, or without arguments, to the current
493 // aircraft position. Returns nil on error. Only one side of each runway is
495 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
497 static SGConstPropertyNode_ptr lat = fgGetNode("/position/latitude-deg", true);
498 static SGConstPropertyNode_ptr lon = fgGetNode("/position/longitude-deg", true);
501 FGAirportList *aptlst = globals->get_airports();
504 apt = aptlst->search(lon->getDoubleValue(), lat->getDoubleValue(), airport);
505 else if(argc == 1 && naIsString(args[0]))
506 apt = aptlst->search(naStr_data(args[0]));
507 else if(argc == 2 && naIsNum(args[0]) && naIsNum(args[1]))
508 apt = aptlst->search(args[1].num, args[0].num, airport);
510 naRuntimeError(c, "airportinfo() with invalid function arguments");
514 naRuntimeError(c, "airportinfo(): no airport found");
518 string id = apt->getId();
519 string name = apt->getName();
522 FGRunwayList *rwylst = globals->get_runways();
524 naRef rwys = naNewHash(c);
525 if(rwylst->search(id, &rwy)) {
527 if(rwy._id != id) break;
528 if(rwy._type[0] != 'r') continue;
530 naRef rwydata = naNewHash(c);
531 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
532 HASHSET("lat", 3, naNum(rwy._lat));
533 HASHSET("lon", 3, naNum(rwy._lon));
534 HASHSET("heading", 7, naNum(rwy._heading));
535 HASHSET("length", 6, naNum(rwy._length * SG_FEET_TO_METER));
536 HASHSET("width", 5, naNum(rwy._width * SG_FEET_TO_METER));
537 HASHSET("threshold1", 10, naNum(rwy._displ_thresh1 * SG_FEET_TO_METER));
538 HASHSET("threshold2", 10, naNum(rwy._displ_thresh2 * SG_FEET_TO_METER));
539 HASHSET("stopway1", 8, naNum(rwy._stopway1 * SG_FEET_TO_METER));
540 HASHSET("stopway2", 8, naNum(rwy._stopway2 * SG_FEET_TO_METER));
543 naRef no = naStr_fromdata(naNewString(c),
544 const_cast<char *>(rwy._rwy_no.c_str()),
545 rwy._rwy_no.length());
546 naHash_set(rwys, no, rwydata);
547 } while(rwylst->next(&rwy));
551 naRef aptdata = naNewHash(c);
552 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
553 HASHSET("id", 2, naStr_fromdata(naNewString(c),
554 const_cast<char *>(id.c_str()), id.length()));
555 HASHSET("name", 4, naStr_fromdata(naNewString(c),
556 const_cast<char *>(name.c_str()), name.length()));
557 HASHSET("lat", 3, naNum(apt->getLatitude()));
558 HASHSET("lon", 3, naNum(apt->getLongitude()));
559 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
560 HASHSET("has_metar", 9, naNum(apt->getMetar()));
561 HASHSET("runways", 7, rwys);
567 // Table of extension functions. Terminate with zeros.
568 static struct { char* name; naCFunction func; } funcs[] = {
569 { "getprop", f_getprop },
570 { "setprop", f_setprop },
571 { "print", f_print },
572 { "_fgcommand", f_fgcommand },
573 { "settimer", f_settimer },
574 { "_setlistener", f_setlistener },
575 { "removelistener", f_removelistener },
576 { "_cmdarg", f_cmdarg },
577 { "_interpolate", f_interpolate },
579 { "srand", f_srand },
580 { "directory", f_directory },
581 { "parsexml", f_parsexml },
582 { "systime", f_systime },
583 { "carttogeod", f_carttogeod },
584 { "geodtocart", f_geodtocart },
585 { "geodinfo", f_geodinfo },
586 { "airportinfo", f_airportinfo },
590 naRef FGNasalSys::cmdArgGhost()
592 return propNodeGhost(_cmdArg);
595 void FGNasalSys::init()
599 _context = naNewContext();
601 // Start with globals. Add it to itself as a recursive
602 // sub-reference under the name "globals". This gives client-code
603 // write access to the namespace if someone wants to do something
605 _globals = naInit_std(_context);
606 naSave(_context, _globals);
607 hashset(_globals, "globals", _globals);
609 hashset(_globals, "math", naInit_math(_context));
610 hashset(_globals, "bits", naInit_bits(_context));
611 hashset(_globals, "io", naInit_io(_context));
612 hashset(_globals, "thread", naInit_thread(_context));
613 hashset(_globals, "utf8", naInit_utf8(_context));
615 // Add our custom extension functions:
616 for(i=0; funcs[i].name; i++)
617 hashset(_globals, funcs[i].name,
618 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
620 // And our SGPropertyNode wrapper
621 hashset(_globals, "props", genPropsModule());
623 // Make a "__gcsave" hash to hold the naRef objects which get
624 // passed to handles outside the interpreter (to protect them from
625 // begin garbage-collected).
626 _gcHash = naNewHash(_context);
627 hashset(_globals, "__gcsave", _gcHash);
629 // Now load the various source files in the Nasal directory
630 SGPath p(globals->get_fg_root());
633 ulDir* dir = ulOpenDir(p.c_str());
634 while(dir && (dent = ulReadDir(dir)) != 0) {
636 fullpath.append(dent->d_name);
637 SGPath file(dent->d_name);
638 if(file.extension() != "nas") continue;
639 loadModule(fullpath, file.base().c_str());
643 // set signal and remove node to avoid restoring at reinit
644 const char *s = "nasal-dir-initialized";
645 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
646 signal->setBoolValue(s, true);
647 signal->removeChildren(s);
649 // Pull scripts out of the property tree, too
650 loadPropertyScripts();
653 void FGNasalSys::update(double)
655 if(_purgeListeners) {
656 _purgeListeners = false;
657 map<int, FGNasalListener *>::iterator it;
658 for(it = _listener.begin(); it != _listener.end();) {
659 FGNasalListener *nl = it->second;
661 _listener.erase(it++);
670 // Loads the scripts found under /nasal in the global tree
671 void FGNasalSys::loadPropertyScripts()
673 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
676 for(int i=0; i<nasal->nChildren(); i++) {
677 SGPropertyNode* n = nasal->getChild(i);
679 const char* module = n->getName();
680 if(n->hasChild("module"))
681 module = n->getStringValue("module");
683 // allow multiple files to be specified within in a single
687 bool file_specified = false;
688 while ( (fn = n->getChild("file", j)) != NULL ) {
689 file_specified = true;
690 const char* file = fn->getStringValue();
691 SGPath p(globals->get_fg_root());
693 loadModule(p, module);
697 // Old code which only allowed a single file to be specified per module
699 const char* file = n->getStringValue("file");
700 if(!n->hasChild("file")) file = 0; // Hrm...
702 SGPath p(globals->get_fg_root());
704 loadModule(p, module);
708 const char* src = n->getStringValue("script");
709 if(!n->hasChild("script")) src = 0; // Hrm...
711 createModule(module, n->getPath(), src, strlen(src));
713 if(!file_specified && !src)
714 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
715 "no <file> or <script> defined in " <<
716 "/nasal/" << module);
720 // Logs a runtime error, with stack trace, to the FlightGear log stream
721 void FGNasalSys::logError(naContext context)
723 SG_LOG(SG_NASAL, SG_ALERT,
724 "Nasal runtime error: " << naGetError(context));
725 SG_LOG(SG_NASAL, SG_ALERT,
726 " at " << naStr_data(naGetSourceFile(context, 0)) <<
727 ", line " << naGetLine(context, 0));
728 for(int i=1; i<naStackDepth(context); i++)
729 SG_LOG(SG_NASAL, SG_ALERT,
730 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
731 ", line " << naGetLine(context, i));
734 // Reads a script file, executes it, and places the resulting
735 // namespace into the global namespace under the specified module
737 void FGNasalSys::loadModule(SGPath file, const char* module)
740 char* buf = readfile(file.c_str(), &len);
742 SG_LOG(SG_NASAL, SG_ALERT,
743 "Nasal error: could not read script file " << file.c_str()
744 << " into module " << module);
748 createModule(module, file.c_str(), buf, len);
752 // Parse and run. Save the local variables namespace, as it will
753 // become a sub-object of globals. The optional "arg" argument can be
754 // used to pass an associated property node to the module, which can then
755 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
756 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
757 const char* src, int len, const SGPropertyNode* arg)
759 naRef code = parse(fileName, src, len);
763 // See if we already have a module hash to use. This allows the
764 // user to, for example, add functions to the built-in math
765 // module. Make a new one if necessary.
767 naRef modname = naNewString(_context);
768 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
769 if(!naHash_get(_globals, modname, &locals))
770 locals = naNewHash(_context);
772 _cmdArg = (SGPropertyNode*)arg;
775 hashset(_globals, moduleName, locals);
778 void FGNasalSys::deleteModule(const char* moduleName)
780 naRef modname = naNewString(_context);
781 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
782 naHash_delete(_globals, modname);
785 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
788 naRef srcfile = naNewString(_context);
789 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
790 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
792 SG_LOG(SG_NASAL, SG_ALERT,
793 "Nasal parse error: " << naGetError(_context) <<
794 " in "<< filename <<", line " << errLine);
798 // Bind to the global namespace before returning
799 return naBindFunction(_context, code, _globals);
802 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
804 const char* nasal = arg->getStringValue("script");
805 const char* moduleName = arg->getStringValue("module");
806 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
807 if(naIsNil(code)) return false;
809 // Commands can be run "in" a module. Make sure that module
810 // exists, and set it up as the local variables hash for the
812 naRef locals = naNil();
814 naRef modname = naNewString(_context);
815 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
816 if(!naHash_get(_globals, modname, &locals)) {
817 locals = naNewHash(_context);
818 naHash_set(_globals, modname, locals);
822 // Cache this command's argument for inspection via cmdarg(). For
823 // performance reasons, we won't bother with it if the invoked
824 // code doesn't need it.
825 _cmdArg = (SGPropertyNode*)arg;
831 // settimer(func, dt, simtime) extension function. The first argument
832 // is a Nasal function to call, the second is a delta time (from now),
833 // in seconds. The third, if present, is a boolean value indicating
834 // that "real world" time (rather than simulator time) is to be used.
836 // Implementation note: the FGTimer objects don't live inside the
837 // garbage collector, so the Nasal handler functions have to be
838 // "saved" somehow lest they be inadvertently cleaned. In this case,
839 // they are inserted into a globals.__gcsave hash and removed on
841 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
843 // Extract the handler, delta, and simtime arguments:
844 naRef handler = argc > 0 ? args[0] : naNil();
845 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
846 naRuntimeError(c, "settimer() with invalid function argument");
850 naRef delta = argc > 1 ? args[1] : naNil();
852 naRuntimeError(c, "settimer() with invalid time argument");
856 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
858 // Generate and register a C++ timer handler
859 NasalTimer* t = new NasalTimer;
860 t->handler = handler;
861 t->gcKey = gcSave(handler);
864 globals->get_event_mgr()->addEvent("NasalTimer",
865 t, &NasalTimer::timerExpired,
869 void FGNasalSys::handleTimer(NasalTimer* t)
871 call(t->handler, naNil());
875 int FGNasalSys::gcSave(naRef r)
877 int key = _nextGCKey++;
878 naHash_set(_gcHash, naNum(key), r);
882 void FGNasalSys::gcRelease(int key)
884 naHash_delete(_gcHash, naNum(key));
887 void FGNasalSys::NasalTimer::timerExpired()
889 nasal->handleTimer(this);
893 int FGNasalSys::_listenerId = 0;
895 // setlistener(property, func, bool) extension function. The first argument
896 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
897 // path), the second is a Nasal function, the optional third one a bool.
898 // If the bool is true, then the listener is executed initially. The
899 // setlistener() function returns a unique id number, that can be used
900 // as argument to the removelistener() function.
901 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
903 SGPropertyNode_ptr node;
904 naRef prop = argc > 0 ? args[0] : naNil();
905 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
906 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
908 naRuntimeError(c, "setlistener() with invalid property argument");
913 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
916 naRef handler = argc > 1 ? args[1] : naNil();
917 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
918 naRuntimeError(c, "setlistener() with invalid function argument");
922 bool initial = argc > 2 && naTrue(args[2]);
924 FGNasalListener *nl = new FGNasalListener(node, handler, this,
925 gcSave(handler), _listenerId);
926 node->addChangeListener(nl, initial);
928 _listener[_listenerId] = nl;
929 return naNum(_listenerId++);
932 // removelistener(int) extension function. The argument is the id of
933 // a listener as returned by the setlistener() function.
934 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
936 naRef id = argc > 0 ? args[0] : naNil();
937 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
939 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
940 naRuntimeError(c, "removelistener() with invalid listener id");
944 FGNasalListener *nl = it->second;
947 _purgeListeners = true;
953 return naNum(_listener.size());
958 // FGNasalListener class.
960 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
961 FGNasalSys* nasal, int key, int id) :
972 FGNasalListener::~FGNasalListener()
974 _node->removeChangeListener(this);
975 _nas->gcRelease(_gcKey);
978 void FGNasalListener::valueChanged(SGPropertyNode* node)
980 // drop recursive listener calls
984 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
986 _nas->_cmdArg = node;
987 _nas->call(_handler, naNil());
994 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
995 // such a class, then it lets modelLoaded() run the <load> script, and the
996 // destructor the <unload> script. The latter happens when the model branch
997 // is removed from the scene graph.
999 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1002 SGPropertyNode *n = prop->getNode("nasal"), *load;
1006 load = n->getNode("load");
1007 _unload = n->getNode("unload");
1008 if(!load && !_unload)
1013 _module += ':' + _props->getPath();
1014 const char *s = load ? load->getStringValue() : "";
1015 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1018 FGNasalModelData::~FGNasalModelData()
1024 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1025 "without Nasal subsystem present.");
1030 const char *s = _unload->getStringValue();
1031 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1033 nasalSys->deleteModule(_module.c_str());
1038 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1040 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1041 _c(naSubContext(c)),
1042 _start_element(argc > 1 ? args[1] : naNil()),
1043 _end_element(argc > 2 ? args[2] : naNil()),
1044 _data(argc > 3 ? args[3] : naNil()),
1045 _pi(argc > 4 ? args[4] : naNil())
1049 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1051 if(naIsNil(_start_element)) return;
1052 naRef attr = naNewHash(_c);
1053 for(int i=0; i<a.size(); i++) {
1054 naRef name = make_string(a.getName(i));
1055 naRef value = make_string(a.getValue(i));
1056 naHash_set(attr, name, value);
1058 call(_start_element, 2, make_string(tag), attr);
1061 void NasalXMLVisitor::endElement(const char* tag)
1063 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1066 void NasalXMLVisitor::data(const char* str, int len)
1068 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1071 void NasalXMLVisitor::pi(const char* target, const char* data)
1073 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1076 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1081 naCall(_c, func, num, args, naNil(), naNil());
1086 naRef NasalXMLVisitor::make_string(const char* s, int n)
1088 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1089 n < 0 ? strlen(s) : n);