13 #include <simgear/nasal/nasal.h>
14 #include <simgear/props/props.hxx>
15 #include <simgear/math/sg_random.h>
16 #include <simgear/misc/sg_path.hxx>
17 #include <simgear/misc/interpolator.hxx>
18 #include <simgear/structure/commands.hxx>
20 #include <Main/globals.hxx>
21 #include <Main/fg_props.hxx>
23 #include "NasalSys.hxx"
25 // Read and return file contents in a single buffer. Note use of
26 // stat() to get the file size. This is a win32 function, believe it
27 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
28 // Text mode brain damage will kill us if we're trying to do bytewise
30 static char* readfile(const char* file, int* lenOut)
33 if(stat(file, &data) != 0) return 0;
34 FILE* f = fopen(file, "rb");
36 char* buf = new char[data.st_size];
37 *lenOut = fread(buf, 1, data.st_size, f);
39 if(*lenOut != data.st_size) {
40 // Shouldn't happen, but warn anyway since it represents a
41 // platform bug and not a typical runtime error (missing file,
43 SG_LOG(SG_NASAL, SG_ALERT,
44 "ERROR in Nasal initialization: " <<
45 "short count returned from fread() of " << file <<
46 ". Check your C library!");
53 FGNasalSys::FGNasalSys()
58 _nextGCKey = 0; // Any value will do
61 FGNasalSys::~FGNasalSys()
63 // Nasal doesn't have a "destroy context" API yet. :(
64 // Not a problem for a global subsystem that will never be
65 // destroyed. And the context is actually a global, so no memory
66 // is technically leaked (although the GC pool memory obviously
72 bool FGNasalSys::parseAndRun(const char* sourceCode)
74 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
79 naCall(_context, code, 0, 0, naNil(), naNil());
81 if(!naGetError(_context)) return true;
86 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
88 FGNasalScript* script = new FGNasalScript();
89 script->_gcKey = -1; // important, if we delete it on a parse
90 script->_nas = this; // error, don't clobber a real handle!
94 sprintf(buf, "FGNasalScript@%p", script);
98 script->_code = parse(name, src, strlen(src));
99 if(naIsNil(script->_code)) {
104 script->_gcKey = gcSave(script->_code);
108 // Utility. Sets a named key in a hash by C string, rather than nasal
110 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
112 naRef s = naNewString(_context);
113 naStr_fromdata(s, (char*)key, strlen(key));
114 naHash_set(hash, s, val);
117 // The get/setprop functions accept a *list* of strings and walk
118 // through the property tree with them to find the appropriate node.
119 // This allows a Nasal object to hold onto a property path and use it
120 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
121 // is the utility function that walks the property tree.
122 // Future enhancement: support integer arguments to specify array
124 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
126 SGPropertyNode* p = globals->get_props();
127 for(int i=0; i<len; i++) {
129 if(!naIsString(a)) return 0;
130 p = p->getNode(naStr_data(a));
136 // getprop() extension function. Concatenates its string arguments as
137 // property names and returns the value of the specified property. Or
138 // nil if it doesn't exist.
139 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
141 const SGPropertyNode* p = findnode(c, args, argc);
142 if(!p) return naNil();
144 switch(p->getType()) {
145 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
146 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
147 case SGPropertyNode::DOUBLE:
148 return naNum(p->getDoubleValue());
150 case SGPropertyNode::STRING:
151 case SGPropertyNode::UNSPECIFIED:
153 naRef nastr = naNewString(c);
154 const char* val = p->getStringValue();
155 naStr_fromdata(nastr, (char*)val, strlen(val));
158 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
164 // setprop() extension function. Concatenates its string arguments as
165 // property names and sets the value of the specified property to the
167 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
170 char buf[BUFLEN + 1];
174 for(int i=0; i<argc-1; i++) {
175 naRef s = naStringValue(c, args[i]);
176 if(naIsNil(s)) return naNil();
177 strncpy(p, naStr_data(s), buflen);
179 buflen = BUFLEN - (p - buf);
180 if(i < (argc-2) && buflen > 0) {
186 SGPropertyNode* props = globals->get_props();
187 naRef val = args[argc-1];
188 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
189 else props->setDoubleValue(buf, naNumValue(val).num);
194 // print() extension function. Concatenates and prints its arguments
195 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
196 // make sure it appears. Is there better way to do this?
197 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
200 char buf[BUFLEN + 1];
201 buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
202 buf[0] = 0; // Zero-length in case there are no arguments
206 for(int i=0; i<n; i++) {
207 naRef s = naStringValue(c, args[i]);
208 if(naIsNil(s)) continue;
209 strncpy(p, naStr_data(s), buflen);
211 buflen = BUFLEN - (p - buf);
212 if(buflen <= 0) break;
214 SG_LOG(SG_GENERAL, SG_ALERT, buf);
219 // fgcommand() extension function. Executes a named command via the
220 // FlightGear command manager. Takes a single property node name as
222 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
224 if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
225 naRuntimeError(c, "bad arguments to fgcommand()");
226 naRef cmd = args[0], props = args[1];
227 SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
228 globals->get_commands()->execute(naStr_data(cmd), *node);
233 // settimer(func, dt, simtime) extension function. Falls through to
234 // FGNasalSys::setTimer(). See there for docs.
235 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
237 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
238 nasal->setTimer(argc, args);
242 // setlistener(func, property) extension function. Falls through to
243 // FGNasalSys::setListener(). See there for docs.
244 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
246 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
247 nasal->setListener(argc, args);
251 // Returns a ghost handle to the argument to the currently executing
253 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
255 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
256 return nasal->cmdArgGhost();
259 // Sets up a property interpolation. The first argument is either a
260 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
261 // interpolate. The second argument is a vector of pairs of
262 // value/delta numbers.
263 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
265 SGPropertyNode* node;
266 naRef prop = argc > 0 ? args[0] : naNil();
267 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
268 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
271 naRef curve = argc > 1 ? args[1] : naNil();
272 if(!naIsVector(curve)) return naNil();
273 int nPoints = naVec_size(curve) / 2;
274 double* values = new double[nPoints];
275 double* deltas = new double[nPoints];
276 for(int i=0; i<nPoints; i++) {
277 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
278 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
281 ((SGInterpolator*)globals->get_subsystem("interpolator"))
282 ->interpolate(node, nPoints, values, deltas);
287 // This is a better RNG than the one in the default Nasal distribution
288 // (which is based on the C library rand() implementation). It will
290 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
292 return naNum(sg_random());
295 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
301 // Return an array listing of all files in a directory
302 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
304 if(argc != 1 || !naIsString(args[0]))
305 naRuntimeError(c, "bad arguments to directory()");
306 naRef ldir = args[0];
307 ulDir* dir = ulOpenDir(naStr_data(args[0]));
308 if(!dir) return naNil();
309 naRef result = naNewVector(c);
311 while((dent = ulReadDir(dir)))
312 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
313 strlen(dent->d_name)));
318 // Table of extension functions. Terminate with zeros.
319 static struct { char* name; naCFunction func; } funcs[] = {
320 { "getprop", f_getprop },
321 { "setprop", f_setprop },
322 { "print", f_print },
323 { "_fgcommand", f_fgcommand },
324 { "settimer", f_settimer },
325 { "_setlistener", f_setlistener },
326 { "_cmdarg", f_cmdarg },
327 { "_interpolate", f_interpolate },
329 { "srand", f_srand },
330 { "directory", f_directory },
334 naRef FGNasalSys::cmdArgGhost()
336 return propNodeGhost(_cmdArg);
339 void FGNasalSys::init()
343 _context = naNewContext();
345 // Start with globals. Add it to itself as a recursive
346 // sub-reference under the name "globals". This gives client-code
347 // write access to the namespace if someone wants to do something
349 _globals = naStdLib(_context);
350 naSave(_context, _globals);
351 hashset(_globals, "globals", _globals);
353 // Add in the math library under "math"
354 hashset(_globals, "math", naMathLib(_context));
356 // Add our custom extension functions:
357 for(i=0; funcs[i].name; i++)
358 hashset(_globals, funcs[i].name,
359 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
361 // And our SGPropertyNode wrapper
362 hashset(_globals, "props", genPropsModule());
364 // Make a "__gcsave" hash to hold the naRef objects which get
365 // passed to handles outside the interpreter (to protect them from
366 // begin garbage-collected).
367 _gcHash = naNewHash(_context);
368 hashset(_globals, "__gcsave", _gcHash);
370 // Now load the various source files in the Nasal directory
371 SGPath p(globals->get_fg_root());
374 ulDir* dir = ulOpenDir(p.c_str());
375 while(dir && (dent = ulReadDir(dir)) != 0) {
377 fullpath.append(dent->d_name);
378 SGPath file(dent->d_name);
379 if(file.extension() != "nas") continue;
380 loadModule(fullpath, file.base().c_str());
383 // Pull scripts out of the property tree, too
384 loadPropertyScripts();
387 // Loads the scripts found under /nasal in the global tree
388 void FGNasalSys::loadPropertyScripts()
390 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
393 for(int i=0; i<nasal->nChildren(); i++) {
394 SGPropertyNode* n = nasal->getChild(i);
396 const char* module = n->getName();
397 if(n->hasChild("module"))
398 module = n->getStringValue("module");
400 // allow multiple files to be specified within in a single
404 bool file_specified = false;
405 while ( (fn = n->getChild("file", j)) != NULL ) {
406 file_specified = true;
407 const char* file = fn->getStringValue();
408 SGPath p(globals->get_fg_root());
410 loadModule(p, module);
414 // Old code which only allowed a single file to be specified per module
416 const char* file = n->getStringValue("file");
417 if(!n->hasChild("file")) file = 0; // Hrm...
419 SGPath p(globals->get_fg_root());
421 loadModule(p, module);
425 const char* src = n->getStringValue("script");
426 if(!n->hasChild("script")) src = 0; // Hrm...
428 createModule(module, n->getPath(), src, strlen(src));
430 if(!file_specified && !src)
431 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
432 "no <file> or <script> defined in " <<
433 "/nasal/" << module);
437 // Logs a runtime error, with stack trace, to the FlightGear log stream
438 void FGNasalSys::logError(naContext context)
440 SG_LOG(SG_NASAL, SG_ALERT,
441 "Nasal runtime error: " << naGetError(context));
442 SG_LOG(SG_NASAL, SG_ALERT,
443 " at " << naStr_data(naGetSourceFile(context, 0)) <<
444 ", line " << naGetLine(context, 0));
445 for(int i=1; i<naStackDepth(context); i++)
446 SG_LOG(SG_NASAL, SG_ALERT,
447 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
448 ", line " << naGetLine(context, i));
451 // Reads a script file, executes it, and places the resulting
452 // namespace into the global namespace under the specified module
454 void FGNasalSys::loadModule(SGPath file, const char* module)
457 char* buf = readfile(file.c_str(), &len);
459 SG_LOG(SG_NASAL, SG_ALERT,
460 "Nasal error: could not read script file " << file.c_str()
461 << " into module " << module);
465 createModule(module, file.c_str(), buf, len);
469 // Parse and run. Save the local variables namespace, as it will
470 // become a sub-object of globals.
471 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
472 const char* src, int len)
474 naRef code = parse(fileName, src, len);
478 // See if we already have a module hash to use. This allows the
479 // user to, for example, add functions to the built-in math
480 // module. Make a new one if necessary.
482 naRef modname = naNewString(_context);
483 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
484 if(!naHash_get(_globals, modname, &locals))
485 locals = naNewHash(_context);
487 naCall(_context, code, 0, 0, naNil(), locals);
488 if(naGetError(_context)) {
492 hashset(_globals, moduleName, locals);
495 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
498 naRef srcfile = naNewString(_context);
499 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
500 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
502 SG_LOG(SG_NASAL, SG_ALERT,
503 "Nasal parse error: " << naGetError(_context) <<
504 " in "<< filename <<", line " << errLine);
508 // Bind to the global namespace before returning
509 return naBindFunction(_context, code, _globals);
512 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
514 const char* nasal = arg->getStringValue("script");
515 const char* moduleName = arg->getStringValue("module");
516 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
517 if(naIsNil(code)) return false;
519 naRef locals = naNil();
521 naRef modname = naNewString(_context);
522 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
523 if(!naHash_get(_globals, modname, &locals))
524 locals = naNewHash(_context);
526 // Cache the command argument for inspection via cmdarg(). For
527 // performance reasons, we won't bother with it if the invoked
528 // code doesn't need it.
529 _cmdArg = (SGPropertyNode*)arg;
532 naRef result = naCall(_context, code, 0, 0, naNil(), locals);
533 if(!naGetError(_context)) return true;
538 // settimer(func, dt, simtime) extension function. The first argument
539 // is a Nasal function to call, the second is a delta time (from now),
540 // in seconds. The third, if present, is a boolean value indicating
541 // that "real world" time (rather than simulator time) is to be used.
543 // Implementation note: the FGTimer objects don't live inside the
544 // garbage collector, so the Nasal handler functions have to be
545 // "saved" somehow lest they be inadvertently cleaned. In this case,
546 // they are inserted into a globals.__gcsave hash and removed on
548 void FGNasalSys::setTimer(int argc, naRef* args)
550 // Extract the handler, delta, and simtime arguments:
551 naRef handler = argc > 0 ? args[0] : naNil();
552 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
555 naRef delta = argc > 1 ? args[1] : naNil();
556 if(naIsNil(delta)) return;
558 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
560 // Generate and register a C++ timer handler
561 NasalTimer* t = new NasalTimer;
562 t->handler = handler;
563 t->gcKey = gcSave(handler);
566 globals->get_event_mgr()->addEvent("NasalTimer",
567 t, &NasalTimer::timerExpired,
571 void FGNasalSys::handleTimer(NasalTimer* t)
573 naCall(_context, t->handler, 0, 0, naNil(), naNil());
574 if(naGetError(_context))
579 int FGNasalSys::gcSave(naRef r)
581 int key = _nextGCKey++;
582 naHash_set(_gcHash, naNum(key), r);
586 void FGNasalSys::gcRelease(int key)
588 naHash_delete(_gcHash, naNum(key));
591 void FGNasalSys::NasalTimer::timerExpired()
593 nasal->handleTimer(this);
597 // setlistener(property, func) extension function. The first argument
598 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
599 // path), the second is a Nasal function.
600 void FGNasalSys::setListener(int argc, naRef* args)
602 SGPropertyNode* node;
603 naRef prop = argc > 0 ? args[0] : naNil();
604 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
605 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
608 naRef handler = argc > 1 ? args[1] : naNil();
609 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
612 bool initial = argc > 2 && naTrue(args[2]);
613 node->addChangeListener(new FGNasalListener(handler, this, gcSave(handler)), initial);