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
76 // Does a naCall() in a new context. Wrapped here to make lock
77 // tracking easier. Extension functions are called with the lock, but
78 // we have to release it before making a new naCall(). So rather than
79 // drop the lock in every extension function that might call back into
80 // Nasal, we keep a stack depth counter here and only unlock/lock
81 // around the naCall if it isn't the first one.
82 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
84 naContext ctx = naNewContext();
85 if(_callCount) naModUnlock();
87 naRef result = naCall(ctx, code, argc, args, naNil(), locals);
91 if(_callCount) naModLock();
96 FGNasalSys::~FGNasalSys()
99 map<int, FGNasalListener *>::iterator it, end = _listener.end();
100 for(it = _listener.begin(); it != end; ++it)
103 naFreeContext(_context);
107 bool FGNasalSys::parseAndRun(const char* sourceCode)
109 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
113 call(code, 0, 0, naNil());
117 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
119 FGNasalScript* script = new FGNasalScript();
120 script->_gcKey = -1; // important, if we delete it on a parse
121 script->_nas = this; // error, don't clobber a real handle!
125 sprintf(buf, "FGNasalScript@%p", (void *)script);
129 script->_code = parse(name, src, strlen(src));
130 if(naIsNil(script->_code)) {
135 script->_gcKey = gcSave(script->_code);
139 // Utility. Sets a named key in a hash by C string, rather than nasal
141 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
143 naRef s = naNewString(_context);
144 naStr_fromdata(s, (char*)key, strlen(key));
145 naHash_set(hash, s, val);
148 // The get/setprop functions accept a *list* of strings and walk
149 // through the property tree with them to find the appropriate node.
150 // This allows a Nasal object to hold onto a property path and use it
151 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
152 // is the utility function that walks the property tree.
153 // Future enhancement: support integer arguments to specify array
155 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
157 SGPropertyNode* p = globals->get_props();
159 for(int i=0; i<len; i++) {
161 if(!naIsString(a)) return 0;
162 p = p->getNode(naStr_data(a));
165 } catch (const string& err) {
166 naRuntimeError(c, (char *)err.c_str());
172 // getprop() extension function. Concatenates its string arguments as
173 // property names and returns the value of the specified property. Or
174 // nil if it doesn't exist.
175 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
177 const SGPropertyNode* p = findnode(c, args, argc);
178 if(!p) return naNil();
180 switch(p->getType()) {
181 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
182 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
183 case SGPropertyNode::DOUBLE:
184 return naNum(p->getDoubleValue());
186 case SGPropertyNode::STRING:
187 case SGPropertyNode::UNSPECIFIED:
189 naRef nastr = naNewString(c);
190 const char* val = p->getStringValue();
191 naStr_fromdata(nastr, (char*)val, strlen(val));
194 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
200 // setprop() extension function. Concatenates its string arguments as
201 // property names and sets the value of the specified property to the
203 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
206 char buf[BUFLEN + 1];
210 for(int i=0; i<argc-1; i++) {
211 naRef s = naStringValue(c, args[i]);
212 if(naIsNil(s)) return naNil();
213 strncpy(p, naStr_data(s), buflen);
215 buflen = BUFLEN - (p - buf);
216 if(i < (argc-2) && buflen > 0) {
222 SGPropertyNode* props = globals->get_props();
223 naRef val = args[argc-1];
226 if(naIsString(val)) r = props->setStringValue(buf, naStr_data(val));
228 naRef n = naNumValue(val);
230 naRuntimeError(c, "setprop() value is not string or number");
231 r = props->setDoubleValue(buf, n.num);
233 if(!r) naRuntimeError(c, "setprop(): property is not writable");
234 } catch (const string& err) {
235 naRuntimeError(c, (char *)err.c_str());
241 // print() extension function. Concatenates and prints its arguments
242 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
243 // make sure it appears. Is there better way to do this?
244 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
248 for(int i=0; i<n; i++) {
249 naRef s = naStringValue(c, args[i]);
250 if(naIsNil(s)) continue;
251 buf += naStr_data(s);
253 SG_LOG(SG_GENERAL, SG_ALERT, buf);
254 return naNum(buf.length());
257 // fgcommand() extension function. Executes a named command via the
258 // FlightGear command manager. Takes a single property node name as
260 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
262 naRef cmd = argc > 0 ? args[0] : naNil();
263 naRef props = argc > 1 ? args[1] : naNil();
264 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
265 naRuntimeError(c, "bad arguments to fgcommand()");
266 SGPropertyNode_ptr tmp, *node;
268 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
270 tmp = new SGPropertyNode();
273 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
276 // settimer(func, dt, simtime) extension function. Falls through to
277 // FGNasalSys::setTimer(). See there for docs.
278 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
280 nasalSys->setTimer(c, argc, args);
284 // setlistener(func, property, bool) extension function. Falls through to
285 // FGNasalSys::setListener(). See there for docs.
286 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
288 return nasalSys->setListener(c, argc, args);
291 // removelistener(int) extension function. Falls through to
292 // FGNasalSys::removeListener(). See there for docs.
293 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
295 return nasalSys->removeListener(c, argc, args);
298 // Returns a ghost handle to the argument to the currently executing
300 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
302 return nasalSys->cmdArgGhost();
305 // Sets up a property interpolation. The first argument is either a
306 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
307 // interpolate. The second argument is a vector of pairs of
308 // value/delta numbers.
309 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
311 SGPropertyNode* node;
312 naRef prop = argc > 0 ? args[0] : naNil();
313 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
314 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
317 naRef curve = argc > 1 ? args[1] : naNil();
318 if(!naIsVector(curve)) return naNil();
319 int nPoints = naVec_size(curve) / 2;
320 double* values = new double[nPoints];
321 double* deltas = new double[nPoints];
322 for(int i=0; i<nPoints; i++) {
323 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
324 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
327 ((SGInterpolator*)globals->get_subsystem_mgr()
328 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
329 ->interpolate(node, nPoints, values, deltas);
336 // This is a better RNG than the one in the default Nasal distribution
337 // (which is based on the C library rand() implementation). It will
339 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
341 return naNum(sg_random());
344 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
350 // Return an array listing of all files in a directory
351 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
353 if(argc != 1 || !naIsString(args[0]))
354 naRuntimeError(c, "bad arguments to directory()");
355 naRef ldir = args[0];
356 ulDir* dir = ulOpenDir(naStr_data(args[0]));
357 if(!dir) return naNil();
358 naRef result = naNewVector(c);
360 while((dent = ulReadDir(dir)))
361 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
362 strlen(dent->d_name)));
368 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
370 // <path> ... absolute path to an XML file
371 // <start-tag> ... callback function with two args: tag name, attribute hash
372 // <end-tag> ... callback function with one arg: tag name
373 // <data> ... callback function with one arg: data
374 // <pi> ... callback function with two args: target, data
375 // (pi = "processing instruction")
376 // All four callback functions are optional and default to nil.
377 // The function returns nil on error, and the file name otherwise.
378 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
380 if(argc < 1 || !naIsString(args[0]))
381 naRuntimeError(c, "parsexml(): path argument missing or not a string");
382 if(argc > 5) argc = 5;
383 for(int i=1; i<argc; i++)
384 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
385 naRuntimeError(c, "parsexml(): callback argument not a function");
387 const char* file = naStr_data(args[0]);
388 std::ifstream input(file);
389 NasalXMLVisitor visitor(c, argc, args);
391 readXML(input, visitor);
392 } catch (const sg_exception& e) {
393 naRuntimeError(c, "parsexml(): file '%s' %s",
394 file, e.getFormattedMessage().c_str());
400 // Return UNIX epoch time in seconds.
401 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
405 GetSystemTimeAsFileTime(&ft);
406 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
407 // Converts from 100ns units in 1601 epoch to unix epoch in sec
408 return naNum((t * 1e-7) - 11644473600.0);
412 do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
413 return naNum(t + 1e-6 * td.tv_usec);
418 // Convert a cartesian point to a geodetic lat/lon/altitude.
419 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
421 double lat, lon, alt, xyz[3];
422 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
423 for(int i=0; i<3; i++)
424 xyz[i] = naNumValue(args[i]).num;
425 sgCartToGeod(xyz, &lat, &lon, &alt);
426 lat *= SG_RADIANS_TO_DEGREES;
427 lon *= SG_RADIANS_TO_DEGREES;
428 naRef vec = naNewVector(c);
429 naVec_append(vec, naNum(lat));
430 naVec_append(vec, naNum(lon));
431 naVec_append(vec, naNum(alt));
435 // Convert a geodetic lat/lon/altitude to a cartesian point.
436 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
438 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
439 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
440 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
441 double alt = naNumValue(args[2]).num;
443 sgGeodToCart(lat, lon, alt, xyz);
444 naRef vec = naNewVector(c);
445 naVec_append(vec, naNum(xyz[0]));
446 naVec_append(vec, naNum(xyz[1]));
447 naVec_append(vec, naNum(xyz[2]));
451 // For given geodetic point return array with elevation, and a material data
452 // hash, or nil if there's no information available (tile not loaded). If
453 // information about the material isn't available, then nil is returned instead
455 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
457 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
458 if(argc != 2) naRuntimeError(c, "geodinfo() expects 2 arguments: lat, lon");
459 double lat = naNumValue(args[0]).num;
460 double lon = naNumValue(args[1]).num;
462 const SGMaterial *mat;
463 if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
465 naRef vec = naNewVector(c);
466 naVec_append(vec, naNum(elev));
467 naRef matdata = naNil();
469 matdata = naNewHash(c);
470 naRef names = naNewVector(c);
471 const vector<string> n = mat->get_names();
472 for(unsigned int i=0; i<n.size(); i++)
473 naVec_append(names, naStr_fromdata(naNewString(c),
474 const_cast<char*>(n[i].c_str()), n[i].size()));
475 HASHSET("names", 5, names);
476 HASHSET("solid", 5, naNum(mat->get_solid()));
477 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
478 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
479 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
480 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
481 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
483 naVec_append(vec, matdata);
489 class airport_filter : public FGAirportSearchFilter {
490 virtual bool pass(FGAirport *a) { return a->isAirport(); }
492 class seaport_filter : public FGAirportSearchFilter {
493 virtual bool pass(FGAirport *a) { return a->isSeaport(); }
495 class heliport_filter : public FGAirportSearchFilter {
496 virtual bool pass(FGAirport *a) { return a->isHeliport(); }
499 // Returns data hash for particular or nearest airport of a <type>, or nil
500 // on error. Only one side of each runway is contained.
502 // airportinfo(<id>); e.g. "KSFO"
503 // airportinfo(<type>); type := ("airport"|"seaport"|"heliport")
504 // airportinfo() same as airportinfo("airport")
505 // airportinfo(<lat>, <lon> [, <type>]);
506 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
508 static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
509 static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
512 FGAirportList *aptlst = globals->get_airports();
514 if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
520 lat = latn->getDoubleValue();
521 lon = lonn->getDoubleValue();
524 apt = aptlst->search(lon, lat, airport);
525 } else if(argc == 1 && naIsString(args[0])) {
526 const char *s = naStr_data(args[0]);
527 if(!strcmp(s, "airport")) apt = aptlst->search(lon, lat, airport);
528 else if(!strcmp(s, "seaport")) apt = aptlst->search(lon, lat, seaport);
529 else if(!strcmp(s, "heliport")) apt = aptlst->search(lon, lat, heliport);
530 else apt = aptlst->search(s);
532 naRuntimeError(c, "airportinfo() with invalid function arguments");
535 if(!apt) return naNil();
537 string id = apt->getId();
538 string name = apt->getName();
541 FGRunwayList *rwylst = globals->get_runways();
543 naRef rwys = naNewHash(c);
544 if(rwylst->search(id, &rwy)) {
546 if(rwy._id != id) break;
547 if(rwy._type[0] != 'r') continue;
549 naRef rwyid = naStr_fromdata(naNewString(c),
550 const_cast<char *>(rwy._rwy_no.c_str()),
551 rwy._rwy_no.length());
553 naRef rwydata = naNewHash(c);
554 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
555 HASHSET("id", 2, rwyid);
556 HASHSET("lat", 3, naNum(rwy._lat));
557 HASHSET("lon", 3, naNum(rwy._lon));
558 HASHSET("heading", 7, naNum(rwy._heading));
559 HASHSET("length", 6, naNum(rwy._length * SG_FEET_TO_METER));
560 HASHSET("width", 5, naNum(rwy._width * SG_FEET_TO_METER));
561 HASHSET("threshold1", 10, naNum(rwy._displ_thresh1 * SG_FEET_TO_METER));
562 HASHSET("threshold2", 10, naNum(rwy._displ_thresh2 * SG_FEET_TO_METER));
563 HASHSET("stopway1", 8, naNum(rwy._stopway1 * SG_FEET_TO_METER));
564 HASHSET("stopway2", 8, naNum(rwy._stopway2 * SG_FEET_TO_METER));
566 naHash_set(rwys, rwyid, rwydata);
567 } while(rwylst->next(&rwy));
571 naRef aptdata = naNewHash(c);
572 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
573 HASHSET("id", 2, naStr_fromdata(naNewString(c),
574 const_cast<char *>(id.c_str()), id.length()));
575 HASHSET("name", 4, naStr_fromdata(naNewString(c),
576 const_cast<char *>(name.c_str()), name.length()));
577 HASHSET("lat", 3, naNum(apt->getLatitude()));
578 HASHSET("lon", 3, naNum(apt->getLongitude()));
579 HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
580 HASHSET("has_metar", 9, naNum(apt->getMetar()));
581 HASHSET("runways", 7, rwys);
587 // Table of extension functions. Terminate with zeros.
588 static struct { const char* name; naCFunction func; } funcs[] = {
589 { "getprop", f_getprop },
590 { "setprop", f_setprop },
591 { "print", f_print },
592 { "_fgcommand", f_fgcommand },
593 { "settimer", f_settimer },
594 { "_setlistener", f_setlistener },
595 { "removelistener", f_removelistener },
596 { "_cmdarg", f_cmdarg },
597 { "_interpolate", f_interpolate },
599 { "srand", f_srand },
600 { "directory", f_directory },
601 { "parsexml", f_parsexml },
602 { "systime", f_systime },
603 { "carttogeod", f_carttogeod },
604 { "geodtocart", f_geodtocart },
605 { "geodinfo", f_geodinfo },
606 { "airportinfo", f_airportinfo },
610 naRef FGNasalSys::cmdArgGhost()
612 return propNodeGhost(_cmdArg);
615 void FGNasalSys::init()
619 _context = naNewContext();
621 // Start with globals. Add it to itself as a recursive
622 // sub-reference under the name "globals". This gives client-code
623 // write access to the namespace if someone wants to do something
625 _globals = naInit_std(_context);
626 naSave(_context, _globals);
627 hashset(_globals, "globals", _globals);
629 hashset(_globals, "math", naInit_math(_context));
630 hashset(_globals, "bits", naInit_bits(_context));
631 hashset(_globals, "io", naInit_io(_context));
632 hashset(_globals, "thread", naInit_thread(_context));
633 hashset(_globals, "utf8", naInit_utf8(_context));
635 // Add our custom extension functions:
636 for(i=0; funcs[i].name; i++)
637 hashset(_globals, funcs[i].name,
638 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
640 // And our SGPropertyNode wrapper
641 hashset(_globals, "props", genPropsModule());
643 // Make a "__gcsave" hash to hold the naRef objects which get
644 // passed to handles outside the interpreter (to protect them from
645 // begin garbage-collected).
646 _gcHash = naNewHash(_context);
647 hashset(_globals, "__gcsave", _gcHash);
649 // Now load the various source files in the Nasal directory
650 SGPath p(globals->get_fg_root());
653 ulDir* dir = ulOpenDir(p.c_str());
654 while(dir && (dent = ulReadDir(dir)) != 0) {
656 fullpath.append(dent->d_name);
657 SGPath file(dent->d_name);
658 if(file.extension() != "nas") continue;
659 loadModule(fullpath, file.base().c_str());
663 // set signal and remove node to avoid restoring at reinit
664 const char *s = "nasal-dir-initialized";
665 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
666 signal->setBoolValue(s, true);
667 signal->removeChildren(s);
669 // Pull scripts out of the property tree, too
670 loadPropertyScripts();
673 void FGNasalSys::update(double)
675 if(!_dead_listener.empty()) {
676 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
677 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
678 _dead_listener.clear();
681 // The global context is a legacy thing. We use dynamically
682 // created contexts for naCall() now, so that we can call them
683 // recursively. But there are still spots that want to use it for
684 // naNew*() calls, which end up leaking memory because the context
685 // only clears out its temporary vector when it's *used*. So just
686 // junk it and fetch a new/reinitialized one every frame. This is
687 // clumsy: the right solution would use the dynamic context in all
688 // cases and eliminate _context entirely. But that's more work,
689 // and this works fine (yes, they say "New" and "Free", but
690 // they're very fast, just trust me). -Andy
691 naFreeContext(_context);
692 _context = naNewContext();
695 // Loads the scripts found under /nasal in the global tree
696 void FGNasalSys::loadPropertyScripts()
698 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
701 for(int i=0; i<nasal->nChildren(); i++) {
702 SGPropertyNode* n = nasal->getChild(i);
704 const char* module = n->getName();
705 if(n->hasChild("module"))
706 module = n->getStringValue("module");
708 // allow multiple files to be specified within in a single
712 bool file_specified = false;
713 while ( (fn = n->getChild("file", j)) != NULL ) {
714 file_specified = true;
715 const char* file = fn->getStringValue();
716 SGPath p(globals->get_fg_root());
718 loadModule(p, module);
722 // Old code which only allowed a single file to be specified per module
724 const char* file = n->getStringValue("file");
725 if(!n->hasChild("file")) file = 0; // Hrm...
727 SGPath p(globals->get_fg_root());
729 loadModule(p, module);
733 const char* src = n->getStringValue("script");
734 if(!n->hasChild("script")) src = 0; // Hrm...
736 createModule(module, n->getPath(), src, strlen(src));
738 if(!file_specified && !src)
739 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
740 "no <file> or <script> defined in " <<
741 "/nasal/" << module);
745 // Logs a runtime error, with stack trace, to the FlightGear log stream
746 void FGNasalSys::logError(naContext context)
748 SG_LOG(SG_NASAL, SG_ALERT,
749 "Nasal runtime error: " << naGetError(context));
750 SG_LOG(SG_NASAL, SG_ALERT,
751 " at " << naStr_data(naGetSourceFile(context, 0)) <<
752 ", line " << naGetLine(context, 0));
753 for(int i=1; i<naStackDepth(context); i++)
754 SG_LOG(SG_NASAL, SG_ALERT,
755 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
756 ", line " << naGetLine(context, i));
759 // Reads a script file, executes it, and places the resulting
760 // namespace into the global namespace under the specified module
762 void FGNasalSys::loadModule(SGPath file, const char* module)
765 char* buf = readfile(file.c_str(), &len);
767 SG_LOG(SG_NASAL, SG_ALERT,
768 "Nasal error: could not read script file " << file.c_str()
769 << " into module " << module);
773 createModule(module, file.c_str(), buf, len);
777 // Parse and run. Save the local variables namespace, as it will
778 // become a sub-object of globals. The optional "arg" argument can be
779 // used to pass an associated property node to the module, which can then
780 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
781 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
782 const char* src, int len, const SGPropertyNode* arg)
784 naRef code = parse(fileName, src, len);
788 // See if we already have a module hash to use. This allows the
789 // user to, for example, add functions to the built-in math
790 // module. Make a new one if necessary.
792 naRef modname = naNewString(_context);
793 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
794 if(!naHash_get(_globals, modname, &locals))
795 locals = naNewHash(_context);
797 _cmdArg = (SGPropertyNode*)arg;
799 call(code, 0, 0, locals);
800 hashset(_globals, moduleName, locals);
803 void FGNasalSys::deleteModule(const char* moduleName)
805 naRef modname = naNewString(_context);
806 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
807 naHash_delete(_globals, modname);
810 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
813 naRef srcfile = naNewString(_context);
814 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
815 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
817 SG_LOG(SG_NASAL, SG_ALERT,
818 "Nasal parse error: " << naGetError(_context) <<
819 " in "<< filename <<", line " << errLine);
823 // Bind to the global namespace before returning
824 return naBindFunction(_context, code, _globals);
827 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
829 const char* nasal = arg->getStringValue("script");
830 const char* moduleName = arg->getStringValue("module");
831 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
832 if(naIsNil(code)) return false;
834 // Commands can be run "in" a module. Make sure that module
835 // exists, and set it up as the local variables hash for the
837 naRef locals = naNil();
839 naRef modname = naNewString(_context);
840 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
841 if(!naHash_get(_globals, modname, &locals)) {
842 locals = naNewHash(_context);
843 naHash_set(_globals, modname, locals);
847 // Cache this command's argument for inspection via cmdarg(). For
848 // performance reasons, we won't bother with it if the invoked
849 // code doesn't need it.
850 _cmdArg = (SGPropertyNode*)arg;
852 call(code, 0, 0, locals);
856 // settimer(func, dt, simtime) extension function. The first argument
857 // is a Nasal function to call, the second is a delta time (from now),
858 // in seconds. The third, if present, is a boolean value indicating
859 // that "real world" time (rather than simulator time) is to be used.
861 // Implementation note: the FGTimer objects don't live inside the
862 // garbage collector, so the Nasal handler functions have to be
863 // "saved" somehow lest they be inadvertently cleaned. In this case,
864 // they are inserted into a globals.__gcsave hash and removed on
866 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
868 // Extract the handler, delta, and simtime arguments:
869 naRef handler = argc > 0 ? args[0] : naNil();
870 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
871 naRuntimeError(c, "settimer() with invalid function argument");
875 naRef delta = argc > 1 ? args[1] : naNil();
877 naRuntimeError(c, "settimer() with invalid time argument");
881 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
883 // Generate and register a C++ timer handler
884 NasalTimer* t = new NasalTimer;
885 t->handler = handler;
886 t->gcKey = gcSave(handler);
889 globals->get_event_mgr()->addEvent("NasalTimer",
890 t, &NasalTimer::timerExpired,
894 void FGNasalSys::handleTimer(NasalTimer* t)
896 call(t->handler, 0, 0, naNil());
900 int FGNasalSys::gcSave(naRef r)
902 int key = _nextGCKey++;
903 naHash_set(_gcHash, naNum(key), r);
907 void FGNasalSys::gcRelease(int key)
909 naHash_delete(_gcHash, naNum(key));
912 void FGNasalSys::NasalTimer::timerExpired()
914 nasal->handleTimer(this);
918 int FGNasalSys::_listenerId = 0;
920 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
921 // Attaches a callback function to a property (specified as a global
922 // property path string or a SGPropertyNode_ptr* ghost). If the third,
923 // optional argument (default=0) is set to 1, then the function is also
924 // called initially. If the fourth, optional argument is set to 0, then the
925 // function is only called when the property node value actually changes.
926 // Otherwise it's called independent of the value whenever the node is
927 // written to (default). The setlistener() function returns a unique
928 // id number, which is to be used as argument to the removelistener()
930 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
932 SGPropertyNode_ptr node;
933 naRef prop = argc > 0 ? args[0] : naNil();
934 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
935 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
937 naRuntimeError(c, "setlistener() with invalid property argument");
942 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
945 naRef code = argc > 1 ? args[1] : naNil();
946 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
947 naRuntimeError(c, "setlistener() with invalid function argument");
951 int type = argc > 3 && naIsNum(args[3]) ? (int)args[3].num : 1;
952 FGNasalListener *nl = new FGNasalListener(node, code, this,
953 gcSave(code), _listenerId, type);
955 bool initial = argc > 2 && naTrue(args[2]);
956 node->addChangeListener(nl, initial);
958 _listener[_listenerId] = nl;
959 return naNum(_listenerId++);
962 // removelistener(int) extension function. The argument is the id of
963 // a listener as returned by the setlistener() function.
964 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
966 naRef id = argc > 0 ? args[0] : naNil();
967 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
969 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
970 naRuntimeError(c, "removelistener() with invalid listener id");
974 it->second->_dead = true;
975 _dead_listener.push_back(it->second);
977 return naNum(_listener.size());
982 // FGNasalListener class.
984 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
985 FGNasalSys* nasal, int key, int id, int type) :
1000 FGNasalListener::~FGNasalListener()
1002 _node->removeChangeListener(this);
1003 _nas->gcRelease(_gcKey);
1006 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1008 if(_active || _dead) return;
1009 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1012 arg[0] = _nas->propNodeGhost(which);
1013 arg[1] = _nas->propNodeGhost(_node);
1014 arg[2] = mode; // value changed, child added/removed
1015 arg[3] = naNum(_node != which); // child event?
1016 _nas->_cmdArg = _node;
1017 _nas->call(_code, 4, arg, naNil());
1021 void FGNasalListener::valueChanged(SGPropertyNode* node)
1023 if(_type < 2 && node != _node) return; // skip child events
1024 if(_type > 0 || changed(_node) || _first_call)
1025 call(node, naNum(0));
1026 if(_type == -1) abort();
1028 _first_call = false;
1031 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1033 if(_type == 2) call(child, naNum(1));
1036 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1038 if(_type == 2) call(child, naNum(-1));
1041 bool FGNasalListener::changed(SGPropertyNode* node)
1043 SGPropertyNode::Type type = node->getType();
1044 if(type == SGPropertyNode::NONE) return false;
1045 if(type == SGPropertyNode::UNSPECIFIED) return true;
1049 case SGPropertyNode::BOOL:
1050 case SGPropertyNode::INT:
1051 case SGPropertyNode::LONG:
1053 long l = node->getLongValue();
1054 result = l != _last_int;
1058 case SGPropertyNode::FLOAT:
1059 case SGPropertyNode::DOUBLE:
1061 double d = node->getDoubleValue();
1062 result = d != _last_float;
1068 string s = node->getStringValue();
1069 result = s != _last_string;
1078 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1079 // such a class, then it lets modelLoaded() run the <load> script, and the
1080 // destructor the <unload> script. The latter happens when the model branch
1081 // is removed from the scene graph.
1083 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1089 SGPropertyNode *load = prop->getNode("load");
1090 _unload = prop->getNode("unload");
1091 if(!load && !_unload)
1096 _module += ':' + _props->getPath();
1097 const char *s = load ? load->getStringValue() : "";
1098 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1101 FGNasalModelData::~FGNasalModelData()
1107 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1108 "without Nasal subsystem present.");
1113 const char *s = _unload->getStringValue();
1114 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1116 nasalSys->deleteModule(_module.c_str());
1121 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1123 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1124 _c(naSubContext(c)),
1125 _start_element(argc > 1 ? args[1] : naNil()),
1126 _end_element(argc > 2 ? args[2] : naNil()),
1127 _data(argc > 3 ? args[3] : naNil()),
1128 _pi(argc > 4 ? args[4] : naNil())
1132 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1134 if(naIsNil(_start_element)) return;
1135 naRef attr = naNewHash(_c);
1136 for(int i=0; i<a.size(); i++) {
1137 naRef name = make_string(a.getName(i));
1138 naRef value = make_string(a.getValue(i));
1139 naHash_set(attr, name, value);
1141 call(_start_element, 2, make_string(tag), attr);
1144 void NasalXMLVisitor::endElement(const char* tag)
1146 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1149 void NasalXMLVisitor::data(const char* str, int len)
1151 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1154 void NasalXMLVisitor::pi(const char* target, const char* data)
1156 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1159 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1164 naCall(_c, func, num, args, naNil(), naNil());
1169 naRef NasalXMLVisitor::make_string(const char* s, int n)
1171 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1172 n < 0 ? strlen(s) : n);