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];
227 if(naIsString(val)) r = props->setStringValue(buf, naStr_data(val));
229 naRef n = naNumValue(val);
231 naRuntimeError(c, "setprop() value is not string or number");
232 r = props->setDoubleValue(buf, n.num);
234 if(!r) naRuntimeError(c, "setprop(): property is not writable");
235 } catch (const string& err) {
236 naRuntimeError(c, (char *)err.c_str());
242 // print() extension function. Concatenates and prints its arguments
243 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
244 // make sure it appears. Is there better way to do this?
245 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
249 for(int i=0; i<n; i++) {
250 naRef s = naStringValue(c, args[i]);
251 if(naIsNil(s)) continue;
252 buf += naStr_data(s);
254 SG_LOG(SG_GENERAL, SG_ALERT, buf);
255 return naNum(buf.length());
258 // fgcommand() extension function. Executes a named command via the
259 // FlightGear command manager. Takes a single property node name as
261 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
263 naRef cmd = argc > 0 ? args[0] : naNil();
264 naRef props = argc > 1 ? args[1] : naNil();
265 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
266 naRuntimeError(c, "bad arguments to fgcommand()");
267 SGPropertyNode_ptr tmp, *node;
269 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
271 tmp = new SGPropertyNode();
274 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
277 // settimer(func, dt, simtime) extension function. Falls through to
278 // FGNasalSys::setTimer(). See there for docs.
279 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
281 nasalSys->setTimer(c, argc, args);
285 // setlistener(func, property, bool) extension function. Falls through to
286 // FGNasalSys::setListener(). See there for docs.
287 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
289 return nasalSys->setListener(c, argc, args);
292 // removelistener(int) extension function. Falls through to
293 // FGNasalSys::removeListener(). See there for docs.
294 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
296 return nasalSys->removeListener(c, argc, args);
299 // Returns a ghost handle to the argument to the currently executing
301 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
303 return nasalSys->cmdArgGhost();
306 // Sets up a property interpolation. The first argument is either a
307 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
308 // interpolate. The second argument is a vector of pairs of
309 // value/delta numbers.
310 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
312 SGPropertyNode* node;
313 naRef prop = argc > 0 ? args[0] : naNil();
314 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
315 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
318 naRef curve = argc > 1 ? args[1] : naNil();
319 if(!naIsVector(curve)) return naNil();
320 int nPoints = naVec_size(curve) / 2;
321 double* values = new double[nPoints];
322 double* deltas = new double[nPoints];
323 for(int i=0; i<nPoints; i++) {
324 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
325 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
328 ((SGInterpolator*)globals->get_subsystem_mgr()
329 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
330 ->interpolate(node, nPoints, values, deltas);
335 // This is a better RNG than the one in the default Nasal distribution
336 // (which is based on the C library rand() implementation). It will
338 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
340 return naNum(sg_random());
343 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
349 // Return an array listing of all files in a directory
350 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
352 if(argc != 1 || !naIsString(args[0]))
353 naRuntimeError(c, "bad arguments to directory()");
354 naRef ldir = args[0];
355 ulDir* dir = ulOpenDir(naStr_data(args[0]));
356 if(!dir) return naNil();
357 naRef result = naNewVector(c);
359 while((dent = ulReadDir(dir)))
360 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
361 strlen(dent->d_name)));
367 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
369 // <path> ... absolute path to an XML file
370 // <start-tag> ... callback function with two args: tag name, attribute hash
371 // <end-tag> ... callback function with one arg: tag name
372 // <data> ... callback function with one arg: data
373 // <pi> ... callback function with two args: target, data
374 // (pi = "processing instruction")
375 // All four callback functions are optional and default to nil.
376 // The function returns nil on error, and the file name otherwise.
377 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
379 if(argc < 1 || !naIsString(args[0]))
380 naRuntimeError(c, "parsexml(): path argument missing or not a string");
381 if(argc > 5) argc = 5;
382 for(int i=1; i<argc; i++)
383 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
384 naRuntimeError(c, "parsexml(): callback argument not a function");
386 const char* file = naStr_data(args[0]);
387 std::ifstream input(file);
388 NasalXMLVisitor visitor(c, argc, args);
390 readXML(input, visitor);
391 } catch (const sg_exception& e) {
392 naRuntimeError(c, "parsexml(): file '%s' %s",
393 file, e.getFormattedMessage().c_str());
399 // Return UNIX epoch time in seconds.
400 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
404 GetSystemTimeAsFileTime(&ft);
405 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
406 // Converts from 100ns units in 1601 epoch to unix epoch in sec
407 return naNum((t * 1e-7) - 11644473600.0);
411 do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
412 return naNum(t + 1e-6 * td.tv_usec);
417 // Convert a cartesian point to a geodetic lat/lon/altitude.
418 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
420 double lat, lon, alt, xyz[3];
421 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
422 for(int i=0; i<3; i++)
423 xyz[i] = naNumValue(args[i]).num;
424 sgCartToGeod(xyz, &lat, &lon, &alt);
425 lat *= SG_RADIANS_TO_DEGREES;
426 lon *= SG_RADIANS_TO_DEGREES;
427 naRef vec = naNewVector(c);
428 naVec_append(vec, naNum(lat));
429 naVec_append(vec, naNum(lon));
430 naVec_append(vec, naNum(alt));
434 // Convert a geodetic lat/lon/altitude to a cartesian point.
435 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
437 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
438 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
439 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
440 double alt = naNumValue(args[2]).num;
442 sgGeodToCart(lat, lon, alt, xyz);
443 naRef vec = naNewVector(c);
444 naVec_append(vec, naNum(xyz[0]));
445 naVec_append(vec, naNum(xyz[1]));
446 naVec_append(vec, naNum(xyz[2]));
450 // For given geodetic point return array with elevation, and a material data
451 // hash, or nil if there's no information available (tile not loaded). If
452 // information about the material isn't available, then nil is returned instead
454 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
456 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
457 if(argc != 2) naRuntimeError(c, "geodinfo() expects 2 arguments: lat, lon");
458 double lat = naNumValue(args[0]).num;
459 double lon = naNumValue(args[1]).num;
461 const SGMaterial *mat;
462 if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
464 naRef vec = naNewVector(c);
465 naVec_append(vec, naNum(elev));
466 naRef matdata = naNil();
468 matdata = naNewHash(c);
469 naRef names = naNewVector(c);
470 const vector<string> n = mat->get_names();
471 for(unsigned int i=0; i<n.size(); i++)
472 naVec_append(names, naStr_fromdata(naNewString(c),
473 const_cast<char*>(n[i].c_str()), n[i].size()));
474 HASHSET("names", 5, names);
475 HASHSET("solid", 5, naNum(mat->get_solid()));
476 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
477 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
478 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
479 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
480 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
482 naVec_append(vec, matdata);
488 class airport_filter : public FGAirportSearchFilter {
489 virtual bool pass(FGAirport *a) { return a->isAirport(); }
491 class seaport_filter : public FGAirportSearchFilter {
492 virtual bool pass(FGAirport *a) { return a->isSeaport(); }
494 class heliport_filter : public FGAirportSearchFilter {
495 virtual bool pass(FGAirport *a) { return a->isHeliport(); }
498 // Returns data hash for particular or nearest airport of a <type>, or nil
499 // on error. Only one side of each runway is contained.
501 // airportinfo(<id>); e.g. "KSFO"
502 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
503 // airportinfo() same as airportinfo("airport")
504 // airportinfo(<lat>, <lon> [, <type>]);
505 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
507 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
508 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
511 FGAirportList *aptlst = globals->get_airports();
513 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
519 lat = latn->getDoubleValue();
520 lon = lonn->getDoubleValue();
523 apt = aptlst->search(lon, lat, airport);
524 } else if(argc == 1 && naIsString(args[0])) {
525 const char *s = naStr_data(args[0]);
526 if(!strcmp(s, "airport")) apt = aptlst->search(lon, lat, airport);
527 else if(!strcmp(s, "seaport")) apt = aptlst->search(lon, lat, seaport);
528 else if(!strcmp(s, "heliport")) apt = aptlst->search(lon, lat, heliport);
529 else apt = aptlst->search(s);
531 naRuntimeError(c, "airportinfo() with invalid function arguments");
535 naRuntimeError(c, "airportinfo(): no airport found");
539 string id = apt->getId();
540 string name = apt->getName();
543 FGRunwayList *rwylst = globals->get_runways();
545 naRef rwys = naNewHash(c);
546 if(rwylst->search(id, &rwy)) {
548 if(rwy._id != id) break;
549 if(rwy._type[0] != 'r') continue;
551 naRef rwydata = naNewHash(c);
552 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
553 HASHSET("lat", 3, naNum(rwy._lat));
554 HASHSET("lon", 3, naNum(rwy._lon));
555 HASHSET("heading", 7, naNum(rwy._heading));
556 HASHSET("length", 6, naNum(rwy._length * SG_FEET_TO_METER));
557 HASHSET("width", 5, naNum(rwy._width * SG_FEET_TO_METER));
558 HASHSET("threshold1", 10, naNum(rwy._displ_thresh1 * SG_FEET_TO_METER));
559 HASHSET("threshold2", 10, naNum(rwy._displ_thresh2 * SG_FEET_TO_METER));
560 HASHSET("stopway1", 8, naNum(rwy._stopway1 * SG_FEET_TO_METER));
561 HASHSET("stopway2", 8, naNum(rwy._stopway2 * SG_FEET_TO_METER));
564 naRef no = naStr_fromdata(naNewString(c),
565 const_cast<char *>(rwy._rwy_no.c_str()),
566 rwy._rwy_no.length());
567 naHash_set(rwys, no, rwydata);
568 } while(rwylst->next(&rwy));
572 naRef aptdata = naNewHash(c);
573 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
574 HASHSET("id", 2, naStr_fromdata(naNewString(c),
575 const_cast<char *>(id.c_str()), id.length()));
576 HASHSET("name", 4, naStr_fromdata(naNewString(c),
577 const_cast<char *>(name.c_str()), name.length()));
578 HASHSET("lat", 3, naNum(apt->getLatitude()));
579 HASHSET("lon", 3, naNum(apt->getLongitude()));
580 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
581 HASHSET("has_metar", 9, naNum(apt->getMetar()));
582 HASHSET("runways", 7, rwys);
588 // Table of extension functions. Terminate with zeros.
589 static struct { char* name; naCFunction func; } funcs[] = {
590 { "getprop", f_getprop },
591 { "setprop", f_setprop },
592 { "print", f_print },
593 { "_fgcommand", f_fgcommand },
594 { "settimer", f_settimer },
595 { "_setlistener", f_setlistener },
596 { "removelistener", f_removelistener },
597 { "_cmdarg", f_cmdarg },
598 { "_interpolate", f_interpolate },
600 { "srand", f_srand },
601 { "directory", f_directory },
602 { "parsexml", f_parsexml },
603 { "systime", f_systime },
604 { "carttogeod", f_carttogeod },
605 { "geodtocart", f_geodtocart },
606 { "geodinfo", f_geodinfo },
607 { "airportinfo", f_airportinfo },
611 naRef FGNasalSys::cmdArgGhost()
613 return propNodeGhost(_cmdArg);
616 void FGNasalSys::init()
620 _context = naNewContext();
622 // Start with globals. Add it to itself as a recursive
623 // sub-reference under the name "globals". This gives client-code
624 // write access to the namespace if someone wants to do something
626 _globals = naInit_std(_context);
627 naSave(_context, _globals);
628 hashset(_globals, "globals", _globals);
630 hashset(_globals, "math", naInit_math(_context));
631 hashset(_globals, "bits", naInit_bits(_context));
632 hashset(_globals, "io", naInit_io(_context));
633 hashset(_globals, "thread", naInit_thread(_context));
634 hashset(_globals, "utf8", naInit_utf8(_context));
636 // Add our custom extension functions:
637 for(i=0; funcs[i].name; i++)
638 hashset(_globals, funcs[i].name,
639 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
641 // And our SGPropertyNode wrapper
642 hashset(_globals, "props", genPropsModule());
644 // Make a "__gcsave" hash to hold the naRef objects which get
645 // passed to handles outside the interpreter (to protect them from
646 // begin garbage-collected).
647 _gcHash = naNewHash(_context);
648 hashset(_globals, "__gcsave", _gcHash);
650 // Now load the various source files in the Nasal directory
651 SGPath p(globals->get_fg_root());
654 ulDir* dir = ulOpenDir(p.c_str());
655 while(dir && (dent = ulReadDir(dir)) != 0) {
657 fullpath.append(dent->d_name);
658 SGPath file(dent->d_name);
659 if(file.extension() != "nas") continue;
660 loadModule(fullpath, file.base().c_str());
664 // set signal and remove node to avoid restoring at reinit
665 const char *s = "nasal-dir-initialized";
666 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
667 signal->setBoolValue(s, true);
668 signal->removeChildren(s);
670 // Pull scripts out of the property tree, too
671 loadPropertyScripts();
674 void FGNasalSys::update(double)
676 if(_purgeListeners) {
677 _purgeListeners = false;
678 map<int, FGNasalListener *>::iterator it;
679 for(it = _listener.begin(); it != _listener.end();) {
680 FGNasalListener *nl = it->second;
682 _listener.erase(it++);
691 // Loads the scripts found under /nasal in the global tree
692 void FGNasalSys::loadPropertyScripts()
694 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
697 for(int i=0; i<nasal->nChildren(); i++) {
698 SGPropertyNode* n = nasal->getChild(i);
700 const char* module = n->getName();
701 if(n->hasChild("module"))
702 module = n->getStringValue("module");
704 // allow multiple files to be specified within in a single
708 bool file_specified = false;
709 while ( (fn = n->getChild("file", j)) != NULL ) {
710 file_specified = true;
711 const char* file = fn->getStringValue();
712 SGPath p(globals->get_fg_root());
714 loadModule(p, module);
718 // Old code which only allowed a single file to be specified per module
720 const char* file = n->getStringValue("file");
721 if(!n->hasChild("file")) file = 0; // Hrm...
723 SGPath p(globals->get_fg_root());
725 loadModule(p, module);
729 const char* src = n->getStringValue("script");
730 if(!n->hasChild("script")) src = 0; // Hrm...
732 createModule(module, n->getPath(), src, strlen(src));
734 if(!file_specified && !src)
735 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
736 "no <file> or <script> defined in " <<
737 "/nasal/" << module);
741 // Logs a runtime error, with stack trace, to the FlightGear log stream
742 void FGNasalSys::logError(naContext context)
744 SG_LOG(SG_NASAL, SG_ALERT,
745 "Nasal runtime error: " << naGetError(context));
746 SG_LOG(SG_NASAL, SG_ALERT,
747 " at " << naStr_data(naGetSourceFile(context, 0)) <<
748 ", line " << naGetLine(context, 0));
749 for(int i=1; i<naStackDepth(context); i++)
750 SG_LOG(SG_NASAL, SG_ALERT,
751 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
752 ", line " << naGetLine(context, i));
755 // Reads a script file, executes it, and places the resulting
756 // namespace into the global namespace under the specified module
758 void FGNasalSys::loadModule(SGPath file, const char* module)
761 char* buf = readfile(file.c_str(), &len);
763 SG_LOG(SG_NASAL, SG_ALERT,
764 "Nasal error: could not read script file " << file.c_str()
765 << " into module " << module);
769 createModule(module, file.c_str(), buf, len);
773 // Parse and run. Save the local variables namespace, as it will
774 // become a sub-object of globals. The optional "arg" argument can be
775 // used to pass an associated property node to the module, which can then
776 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
777 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
778 const char* src, int len, const SGPropertyNode* arg)
780 naRef code = parse(fileName, src, len);
784 // See if we already have a module hash to use. This allows the
785 // user to, for example, add functions to the built-in math
786 // module. Make a new one if necessary.
788 naRef modname = naNewString(_context);
789 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
790 if(!naHash_get(_globals, modname, &locals))
791 locals = naNewHash(_context);
793 _cmdArg = (SGPropertyNode*)arg;
796 hashset(_globals, moduleName, locals);
799 void FGNasalSys::deleteModule(const char* moduleName)
801 naRef modname = naNewString(_context);
802 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
803 naHash_delete(_globals, modname);
806 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
809 naRef srcfile = naNewString(_context);
810 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
811 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
813 SG_LOG(SG_NASAL, SG_ALERT,
814 "Nasal parse error: " << naGetError(_context) <<
815 " in "<< filename <<", line " << errLine);
819 // Bind to the global namespace before returning
820 return naBindFunction(_context, code, _globals);
823 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
825 const char* nasal = arg->getStringValue("script");
826 const char* moduleName = arg->getStringValue("module");
827 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
828 if(naIsNil(code)) return false;
830 // Commands can be run "in" a module. Make sure that module
831 // exists, and set it up as the local variables hash for the
833 naRef locals = naNil();
835 naRef modname = naNewString(_context);
836 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
837 if(!naHash_get(_globals, modname, &locals)) {
838 locals = naNewHash(_context);
839 naHash_set(_globals, modname, locals);
843 // Cache this command's argument for inspection via cmdarg(). For
844 // performance reasons, we won't bother with it if the invoked
845 // code doesn't need it.
846 _cmdArg = (SGPropertyNode*)arg;
852 // settimer(func, dt, simtime) extension function. The first argument
853 // is a Nasal function to call, the second is a delta time (from now),
854 // in seconds. The third, if present, is a boolean value indicating
855 // that "real world" time (rather than simulator time) is to be used.
857 // Implementation note: the FGTimer objects don't live inside the
858 // garbage collector, so the Nasal handler functions have to be
859 // "saved" somehow lest they be inadvertently cleaned. In this case,
860 // they are inserted into a globals.__gcsave hash and removed on
862 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
864 // Extract the handler, delta, and simtime arguments:
865 naRef handler = argc > 0 ? args[0] : naNil();
866 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
867 naRuntimeError(c, "settimer() with invalid function argument");
871 naRef delta = argc > 1 ? args[1] : naNil();
873 naRuntimeError(c, "settimer() with invalid time argument");
877 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
879 // Generate and register a C++ timer handler
880 NasalTimer* t = new NasalTimer;
881 t->handler = handler;
882 t->gcKey = gcSave(handler);
885 globals->get_event_mgr()->addEvent("NasalTimer",
886 t, &NasalTimer::timerExpired,
890 void FGNasalSys::handleTimer(NasalTimer* t)
892 call(t->handler, naNil());
896 int FGNasalSys::gcSave(naRef r)
898 int key = _nextGCKey++;
899 naHash_set(_gcHash, naNum(key), r);
903 void FGNasalSys::gcRelease(int key)
905 naHash_delete(_gcHash, naNum(key));
908 void FGNasalSys::NasalTimer::timerExpired()
910 nasal->handleTimer(this);
914 int FGNasalSys::_listenerId = 0;
916 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
917 // Attaches a callback function to a property (specified as a global
918 // property path string or a SGPropertyNode_ptr* ghost). If the third,
919 // optional argument (default=0) is set to 1, then the function is also
920 // called initially. If the fourth, optional argument is set to 0, then the
921 // function is only called when the property node value actually changes.
922 // Otherwise it's called independent of the value whenever the node is
923 // written to (default). The setlistener() function returns a unique
924 // id number, which is to be used as argument to the removelistener()
926 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
928 SGPropertyNode_ptr node;
929 naRef prop = argc > 0 ? args[0] : naNil();
930 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
931 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
933 naRuntimeError(c, "setlistener() with invalid property argument");
938 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
941 naRef handler = argc > 1 ? args[1] : naNil();
942 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
943 naRuntimeError(c, "setlistener() with invalid function argument");
947 bool persistent = argc > 3 ? naTrue(args[3]) : true;
948 FGNasalListener *nl = new FGNasalListener(node, handler, this,
949 gcSave(handler), _listenerId, persistent);
951 bool initial = argc > 2 && naTrue(args[2]);
952 node->addChangeListener(nl, initial);
954 _listener[_listenerId] = nl;
955 return naNum(_listenerId++);
958 // removelistener(int) extension function. The argument is the id of
959 // a listener as returned by the setlistener() function.
960 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
962 naRef id = argc > 0 ? args[0] : naNil();
963 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
965 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
966 naRuntimeError(c, "removelistener() with invalid listener id");
970 FGNasalListener *nl = it->second;
973 _purgeListeners = true;
979 return naNum(_listener.size());
984 // FGNasalListener class.
986 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
987 FGNasalSys* nasal, int key, int id,
997 _persistent(persistent),
1003 FGNasalListener::~FGNasalListener()
1005 _node->removeChangeListener(this);
1006 _nas->gcRelease(_gcKey);
1009 void FGNasalListener::valueChanged(SGPropertyNode* node)
1011 // drop recursive listener calls
1012 if(_active || _dead)
1014 if(_persistent || changed(node) || _first_call) {
1015 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1017 _nas->_cmdArg = node;
1018 _nas->call(_handler, naNil());
1021 _first_call = false;
1024 bool FGNasalListener::changed(SGPropertyNode* node)
1026 SGPropertyNode::Type type = node->getType();
1027 if(type == SGPropertyNode::NONE) return false;
1028 if(type == SGPropertyNode::UNSPECIFIED) return true;
1032 case SGPropertyNode::BOOL:
1033 case SGPropertyNode::INT:
1034 case SGPropertyNode::LONG:
1036 long l = node->getLongValue();
1037 result = l != _last_int;
1041 case SGPropertyNode::FLOAT:
1042 case SGPropertyNode::DOUBLE:
1044 double d = node->getDoubleValue();
1045 result = d != _last_float;
1051 string s = node->getStringValue();
1052 result = s != _last_string;
1061 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1062 // such a class, then it lets modelLoaded() run the <load> script, and the
1063 // destructor the <unload> script. The latter happens when the model branch
1064 // is removed from the scene graph.
1066 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1069 SGPropertyNode *n = prop->getNode("nasal"), *load;
1073 load = n->getNode("load");
1074 _unload = n->getNode("unload");
1075 if(!load && !_unload)
1080 _module += ':' + _props->getPath();
1081 const char *s = load ? load->getStringValue() : "";
1082 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1085 FGNasalModelData::~FGNasalModelData()
1091 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1092 "without Nasal subsystem present.");
1097 const char *s = _unload->getStringValue();
1098 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1100 nasalSys->deleteModule(_module.c_str());
1105 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1107 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1108 _c(naSubContext(c)),
1109 _start_element(argc > 1 ? args[1] : naNil()),
1110 _end_element(argc > 2 ? args[2] : naNil()),
1111 _data(argc > 3 ? args[3] : naNil()),
1112 _pi(argc > 4 ? args[4] : naNil())
1116 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1118 if(naIsNil(_start_element)) return;
1119 naRef attr = naNewHash(_c);
1120 for(int i=0; i<a.size(); i++) {
1121 naRef name = make_string(a.getName(i));
1122 naRef value = make_string(a.getValue(i));
1123 naHash_set(attr, name, value);
1125 call(_start_element, 2, make_string(tag), attr);
1128 void NasalXMLVisitor::endElement(const char* tag)
1130 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1133 void NasalXMLVisitor::data(const char* str, int len)
1135 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1138 void NasalXMLVisitor::pi(const char* target, const char* data)
1140 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1143 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1148 naCall(_c, func, num, args, naNil(), naNil());
1153 naRef NasalXMLVisitor::make_string(const char* s, int n)
1155 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1156 n < 0 ? strlen(s) : n);