8 #include <simgear/nasal/nasal.h>
9 #include <simgear/props/props.hxx>
10 #include <simgear/math/sg_random.h>
11 #include <simgear/misc/sg_path.hxx>
12 #include <simgear/misc/interpolator.hxx>
13 #include <simgear/structure/commands.hxx>
15 #include <Main/globals.hxx>
16 #include <Main/fg_props.hxx>
18 #include "NasalSys.hxx"
20 // Read and return file contents in a single buffer. Note use of
21 // stat() to get the file size. This is a win32 function, believe it
22 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
23 // Text mode brain damage will kill us if we're trying to do bytewise
25 static char* readfile(const char* file, int* lenOut)
28 if(stat(file, &data) != 0) return 0;
29 FILE* f = fopen(file, "rb");
31 char* buf = new char[data.st_size];
32 *lenOut = fread(buf, 1, data.st_size, f);
34 if(*lenOut != data.st_size) {
35 // Shouldn't happen, but warn anyway since it represents a
36 // platform bug and not a typical runtime error (missing file,
38 SG_LOG(SG_NASAL, SG_ALERT,
39 "ERROR in Nasal initialization: " <<
40 "short count returned from fread() of " << file <<
41 ". Check your C library!");
48 FGNasalSys::FGNasalSys()
53 _nextGCKey = 0; // Any value will do
56 FGNasalSys::~FGNasalSys()
58 // Nasal doesn't have a "destroy context" API yet. :(
59 // Not a problem for a global subsystem that will never be
60 // destroyed. And the context is actually a global, so no memory
61 // is technically leaked (although the GC pool memory obviously
67 bool FGNasalSys::parseAndRun(const char* sourceCode)
69 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
74 naCall(_context, code, naNil(), naNil(), naNil());
76 if(!naGetError(_context)) return true;
81 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
83 FGNasalScript* script = new FGNasalScript();
84 script->_gcKey = -1; // important, if we delete it on a parse
85 script->_nas = this; // error, don't clobber a real handle!
89 sprintf(buf, "FGNasalScript@%8.8x", (int)script);
93 script->_code = parse(name, src);
94 if(naIsNil(script->_code)) {
99 script->_gcKey = gcSave(script->_code);
103 // Utility. Sets a named key in a hash by C string, rather than nasal
105 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
107 naRef s = naNewString(_context);
108 naStr_fromdata(s, (char*)key, strlen(key));
109 naHash_set(hash, s, val);
112 // The get/setprop functions accept a *list* of strings and walk
113 // through the property tree with them to find the appropriate node.
114 // This allows a Nasal object to hold onto a property path and use it
115 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
116 // is the utility function that walks the property tree.
117 // Future enhancement: support integer arguments to specify array
119 static SGPropertyNode* findnode(naContext c, naRef vec, int len)
121 SGPropertyNode* p = globals->get_props();
122 for(int i=0; i<len; i++) {
123 naRef a = naVec_get(vec, i);
124 if(!naIsString(a)) return 0;
125 p = p->getNode(naStr_data(a));
131 // getprop() extension function. Concatenates its string arguments as
132 // property names and returns the value of the specified property. Or
133 // nil if it doesn't exist.
134 static naRef f_getprop(naContext c, naRef args)
136 const SGPropertyNode* p = findnode(c, args, naVec_size(args));
137 if(!p) return naNil();
139 switch(p->getType()) {
140 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
141 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
142 case SGPropertyNode::DOUBLE:
143 return naNum(p->getDoubleValue());
145 case SGPropertyNode::STRING:
146 case SGPropertyNode::UNSPECIFIED:
148 naRef nastr = naNewString(c);
149 const char* val = p->getStringValue();
150 naStr_fromdata(nastr, (char*)val, strlen(val));
153 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
159 // setprop() extension function. Concatenates its string arguments as
160 // property names and sets the value of the specified property to the
162 static naRef f_setprop(naContext c, naRef args)
165 int argc = naVec_size(args);
166 char buf[BUFLEN + 1];
170 for(int i=0; i<argc-1; i++) {
171 naRef s = naStringValue(c, naVec_get(args, i));
172 if(naIsNil(s)) return naNil();
173 strncpy(p, naStr_data(s), buflen);
175 buflen = BUFLEN - (p - buf);
176 if(i < (argc-2) && buflen > 0) {
182 SGPropertyNode* props = globals->get_props();
183 naRef val = naVec_get(args, argc-1);
184 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
185 else props->setDoubleValue(buf, naNumValue(val).num);
190 // print() extension function. Concatenates and prints its arguments
191 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
192 // make sure it appears. Is there better way to do this?
193 static naRef f_print(naContext c, naRef args)
196 char buf[BUFLEN + 1];
197 buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
198 buf[0] = 0; // Zero-length in case there are no arguments
201 int n = naVec_size(args);
202 for(int i=0; i<n; i++) {
203 naRef s = naStringValue(c, naVec_get(args, i));
204 if(naIsNil(s)) continue;
205 strncpy(p, naStr_data(s), buflen);
207 buflen = BUFLEN - (p - buf);
208 if(buflen <= 0) break;
210 SG_LOG(SG_GENERAL, SG_ALERT, buf);
215 // fgcommand() extension function. Executes a named command via the
216 // FlightGear command manager. Takes a single property node name as
218 static naRef f_fgcommand(naContext c, naRef args)
220 naRef cmd = naVec_get(args, 0);
221 naRef props = naVec_get(args, 1);
222 if(!naIsString(cmd) || !naIsGhost(props)) return naNil();
223 SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
224 globals->get_commands()->execute(naStr_data(cmd), *node);
229 // settimer(func, dt, simtime) extension function. Falls through to
230 // FGNasalSys::setTimer(). See there for docs.
231 static naRef f_settimer(naContext c, naRef args)
233 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
234 nasal->setTimer(args);
238 // Returns a ghost handle to the argument to the currently executing
240 static naRef f_cmdarg(naContext c, naRef args)
242 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
243 return nasal->cmdArgGhost();
246 // Sets up a property interpolation. The first argument is either a
247 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
248 // interpolate. The second argument is a vector of pairs of
249 // value/delta numbers.
250 static naRef f_interpolate(naContext c, naRef args)
252 SGPropertyNode* node;
253 naRef prop = naVec_get(args, 0);
254 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
255 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
258 naRef curve = naVec_get(args, 1);
259 if(!naIsVector(curve)) return naNil();
260 int nPoints = naVec_size(curve) / 2;
261 double* values = new double[nPoints];
262 double* deltas = new double[nPoints];
263 for(int i=0; i<nPoints; i++) {
264 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
265 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
268 ((SGInterpolator*)globals->get_subsystem("interpolator"))
269 ->interpolate(node, nPoints, values, deltas);
272 static naRef f_rand(naContext c, naRef args)
274 return naNum(sg_random());
277 // Table of extension functions. Terminate with zeros.
278 static struct { char* name; naCFunction func; } funcs[] = {
279 { "getprop", f_getprop },
280 { "setprop", f_setprop },
281 { "print", f_print },
282 { "_fgcommand", f_fgcommand },
283 { "settimer", f_settimer },
284 { "_cmdarg", f_cmdarg },
285 { "_interpolate", f_interpolate },
290 naRef FGNasalSys::cmdArgGhost()
292 return propNodeGhost(_cmdArg);
295 void FGNasalSys::init()
299 _context = naNewContext();
301 // Start with globals. Add it to itself as a recursive
302 // sub-reference under the name "globals". This gives client-code
303 // write access to the namespace if someone wants to do something
305 _globals = naStdLib(_context);
306 naSave(_context, _globals);
307 hashset(_globals, "globals", _globals);
309 // Add in the math library under "math"
310 hashset(_globals, "math", naMathLib(_context));
312 // Add our custom extension functions:
313 for(i=0; funcs[i].name; i++)
314 hashset(_globals, funcs[i].name,
315 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
317 // And our SGPropertyNode wrapper
318 hashset(_globals, "props", genPropsModule());
320 // Make a "__gcsave" hash to hold the naRef objects which get
321 // passed to handles outside the interpreter (to protect them from
322 // begin garbage-collected).
323 _gcHash = naNewHash(_context);
324 hashset(_globals, "__gcsave", _gcHash);
326 // Now load the various source files in the Nasal directory
327 SGPath p(globals->get_fg_root());
330 ulDir* dir = ulOpenDir(p.c_str());
331 while(dir && (dent = ulReadDir(dir)) != 0) {
333 fullpath.append(dent->d_name);
334 SGPath file(dent->d_name);
335 if(file.extension() != "nas") continue;
336 readScriptFile(fullpath, file.base().c_str());
339 // Pull scripts out of the property tree, too
340 loadPropertyScripts();
343 // Loads the scripts found under /nasal in the global tree
344 void FGNasalSys::loadPropertyScripts()
346 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
349 for(int i=0; i<nasal->nChildren(); i++) {
350 SGPropertyNode* n = nasal->getChild(i);
352 const char* module = n->getName();
353 if(n->hasChild("module"))
354 module = n->getStringValue("module");
356 const char* file = n->getStringValue("file");
357 if(!n->hasChild("file")) file = 0; // Hrm...
359 SGPath p(globals->get_fg_root());
361 readScriptFile(p, module);
364 const char* src = n->getStringValue("script");
365 if(!n->hasChild("script")) src = 0; // Hrm...
367 initModule(module, n->getPath(), src, strlen(src));
370 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
371 "no <file> or <script> defined in " <<
372 "/nasal/" << module);
376 // Logs a runtime error, with stack trace, to the FlightGear log stream
377 void FGNasalSys::logError()
379 SG_LOG(SG_NASAL, SG_ALERT,
380 "Nasal runtime error: " << naGetError(_context));
381 SG_LOG(SG_NASAL, SG_ALERT,
382 " at " << naStr_data(naGetSourceFile(_context, 0)) <<
383 ", line " << naGetLine(_context, 0));
384 for(int i=1; i<naStackDepth(_context); i++)
385 SG_LOG(SG_NASAL, SG_ALERT,
386 " called from: " << naStr_data(naGetSourceFile(_context, i)) <<
387 ", line " << naGetLine(_context, i));
390 // Reads a script file, executes it, and places the resulting
391 // namespace into the global namespace under the specified module
393 void FGNasalSys::readScriptFile(SGPath file, const char* module)
396 char* buf = readfile(file.c_str(), &len);
398 SG_LOG(SG_NASAL, SG_ALERT,
399 "Nasal error: could not read script file " << file.c_str()
400 << " into module " << module);
404 initModule(module, file.c_str(), buf, len);
408 // Parse and run. Save the local variables namespace, as it will
409 // become a sub-object of globals.
410 void FGNasalSys::initModule(const char* moduleName, const char* fileName,
411 const char* src, int len)
413 if(len == 0) len = strlen(src);
415 naRef code = parse(fileName, src, len);
419 // See if we already have a module hash to use. This allows the
420 // user to, for example, add functions to the built-in math
421 // module. Make a new one if necessary.
423 naRef modname = naNewString(_context);
424 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
425 if(!naHash_get(_globals, modname, &locals))
426 locals = naNewHash(_context);
428 naCall(_context, code, naNil(), naNil(), locals);
429 if(naGetError(_context)) {
433 hashset(_globals, moduleName, locals);
436 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
438 if(len == 0) len = strlen(buf);
440 naRef srcfile = naNewString(_context);
441 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
442 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
444 SG_LOG(SG_NASAL, SG_ALERT,
445 "Nasal parse error: " << naGetError(_context) <<
446 " in "<< filename <<", line " << errLine);
450 // Bind to the global namespace before returning
451 return naBindFunction(_context, code, _globals);
454 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
456 // Parse the Nasal source. I'd love to use the property name of
457 // the argument, but it's actually a *clone* of the original
458 // location in the property tree. arg->getPath() returns an empty
460 const char* nasal = arg->getStringValue("script");
461 naRef code = parse("<command>", nasal);
462 if(naIsNil(code)) return false;
464 // Cache the command argument for inspection via cmdarg(). For
465 // performance reasons, we won't bother with it if the invoked
466 // code doesn't need it.
467 _cmdArg = (SGPropertyNode*)arg;
470 naRef result = naCall(_context, code, naNil(), naNil(), naNil());
471 if(!naGetError(_context)) return true;
476 // settimer(func, dt, simtime) extension function. The first argument
477 // is a Nasal function to call, the second is a delta time (from now),
478 // in seconds. The third, if present, is a boolean value indicating
479 // that "simulator" time (rather than real time) is to be used.
481 // Implementation note: the FGTimer objects don't live inside the
482 // garbage collector, so the Nasal handler functions have to be
483 // "saved" somehow lest they be inadvertently cleaned. In this case,
484 // they are inserted into a globals.__gcsave hash and removed on
486 void FGNasalSys::setTimer(naRef args)
488 // Extract the handler, delta, and simtime arguments:
489 naRef handler = naVec_get(args, 0);
490 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
493 naRef delta = naNumValue(naVec_get(args, 1));
494 if(naIsNil(delta)) return;
496 bool simtime = naTrue(naVec_get(args, 2)) ? true : false;
498 // Generate and register a C++ timer handler
499 NasalTimer* t = new NasalTimer;
500 t->handler = handler;
501 t->gcKey = gcSave(handler);
504 globals->get_event_mgr()->addEvent("NasalTimer",
505 t, &NasalTimer::timerExpired,
509 void FGNasalSys::handleTimer(NasalTimer* t)
511 naCall(_context, t->handler, naNil(), naNil(), naNil());
512 if(naGetError(_context))
517 int FGNasalSys::gcSave(naRef r)
519 int key = _nextGCKey++;
520 naHash_set(_gcHash, naNum(key), r);
524 void FGNasalSys::gcRelease(int key)
526 naHash_delete(_gcHash, naNum(key));
529 void FGNasalSys::NasalTimer::timerExpired()
531 nasal->handleTimer(this);