]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
Round millibars to nearest whole number, and make inches default even in UK until...
[flightgear.git] / src / Scripting / NasalSys.cxx
1 #include <string.h>
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5
6 #include <plib/ul.h>
7
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>
14
15 #include <Main/globals.hxx>
16 #include <Main/fg_props.hxx>
17
18 #include "NasalSys.hxx"
19
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
24 // I/O.
25 static char* readfile(const char* file, int* lenOut)
26 {
27     struct stat data;
28     if(stat(file, &data) != 0) return 0;
29     FILE* f = fopen(file, "rb");
30     if(!f) return 0;
31     char* buf = new char[data.st_size];
32     *lenOut = fread(buf, 1, data.st_size, f);
33     fclose(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,
37         // etc...)
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!");
42         delete[] buf;
43         return 0;
44     }
45     return buf;
46 }
47
48 FGNasalSys::FGNasalSys()
49 {
50     _context = 0;
51     _globals = naNil();
52     _gcHash = naNil();
53     _nextGCKey = 0; // Any value will do
54 }
55
56 FGNasalSys::~FGNasalSys()
57 {
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
62     // won't be freed).
63     _context = 0;
64     _globals = naNil();
65 }
66
67 bool FGNasalSys::parseAndRun(const char* sourceCode)
68 {
69     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
70                        strlen(sourceCode));
71     if(naIsNil(code))
72         return false;
73
74     naCall(_context, code, naNil(), naNil(), naNil());
75
76     if(!naGetError(_context)) return true;
77     logError();
78     return false;
79 }
80
81 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
82 {
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!
86
87     char buf[256];
88     if(!name) {
89         sprintf(buf, "FGNasalScript@%8.8x", (int)script);
90         name = buf;
91     }
92
93     script->_code = parse(name, src);
94     if(naIsNil(script->_code)) {
95         delete script;
96         return 0;
97     }
98
99     script->_gcKey = gcSave(script->_code);
100     return script;
101 }
102
103 // Utility.  Sets a named key in a hash by C string, rather than nasal
104 // string object.
105 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
106 {
107     naRef s = naNewString(_context);
108     naStr_fromdata(s, (char*)key, strlen(key));
109     naHash_set(hash, s, val);
110 }
111
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
118 // elements.
119 static SGPropertyNode* findnode(naContext c, naRef vec, int len)
120 {
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));
126         if(p == 0) return 0;
127     }
128     return p;
129 }
130
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)
135 {
136     const SGPropertyNode* p = findnode(c, args, naVec_size(args));
137     if(!p) return naNil();
138
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());
144
145     case SGPropertyNode::STRING:
146         {
147             naRef nastr = naNewString(c);
148             const char* val = p->getStringValue();
149             naStr_fromdata(nastr, (char*)val, strlen(val));
150             return nastr;
151         }
152     default:
153         return naNil();
154     }
155 }
156
157 // setprop() extension function.  Concatenates its string arguments as
158 // property names and sets the value of the specified property to the
159 // final argument.
160 static naRef f_setprop(naContext c, naRef args)
161 {
162 #define BUFLEN 1024
163     int argc = naVec_size(args);
164     char buf[BUFLEN + 1];
165     buf[BUFLEN] = 0;
166     char* p = buf;
167     int buflen = BUFLEN;
168     for(int i=0; i<argc-1; i++) {
169         naRef s = naStringValue(c, naVec_get(args, i));
170         if(naIsNil(s)) return naNil();
171         strncpy(p, naStr_data(s), buflen);
172         p += naStr_len(s);
173         buflen = BUFLEN - (p - buf);
174         if(i < (argc-2) && buflen > 0) {
175             *p++ = '/';
176             buflen--;
177         }
178     }
179
180     SGPropertyNode* props = globals->get_props();
181     naRef val = naVec_get(args, argc-1);
182     if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
183     else                props->setDoubleValue(buf, naNumValue(val).num);
184     return naNil();
185 #undef BUFLEN
186 }
187
188 // print() extension function.  Concatenates and prints its arguments
189 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
190 // make sure it appears.  Is there better way to do this?
191 static naRef f_print(naContext c, naRef args)
192 {
193 #define BUFLEN 1024
194     char buf[BUFLEN + 1];
195     buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
196     char* p = buf;
197     int buflen = BUFLEN;
198     int n = naVec_size(args);
199     for(int i=0; i<n; i++) {
200         naRef s = naStringValue(c, naVec_get(args, i));
201         if(naIsNil(s)) continue;
202         strncpy(p, naStr_data(s), buflen);
203         p += naStr_len(s);
204         buflen = BUFLEN - (p - buf);
205         if(buflen <= 0) break;
206     }
207     SG_LOG(SG_GENERAL, SG_ALERT, buf);
208     return naNil();
209 #undef BUFLEN
210 }
211
212 // fgcommand() extension function.  Executes a named command via the
213 // FlightGear command manager.  Takes a single property node name as
214 // an argument.
215 static naRef f_fgcommand(naContext c, naRef args)
216 {
217     naRef cmd = naVec_get(args, 0);
218     naRef props = naVec_get(args, 1);
219     if(!naIsString(cmd) || !naIsGhost(props)) return naNil();
220     SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
221     globals->get_commands()->execute(naStr_data(cmd), *node);
222     return naNil();
223
224 }
225
226 // settimer(func, dt, simtime) extension function.  Falls through to
227 // FGNasalSys::setTimer().  See there for docs.
228 static naRef f_settimer(naContext c, naRef args)
229 {
230     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
231     nasal->setTimer(args);
232     return naNil();
233 }
234
235 // Returns a ghost handle to the argument to the currently executing
236 // command
237 static naRef f_cmdarg(naContext c, naRef args)
238 {
239     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
240     return nasal->cmdArgGhost();
241 }
242
243 // Sets up a property interpolation.  The first argument is either a
244 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
245 // interpolate.  The second argument is a vector of pairs of
246 // value/delta numbers.
247 static naRef f_interpolate(naContext c, naRef args)
248 {
249     SGPropertyNode* node;
250     naRef prop = naVec_get(args, 0);
251     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
252     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
253     else return naNil();
254
255     naRef curve = naVec_get(args, 1);
256     if(!naIsVector(curve)) return naNil();
257     int nPoints = naVec_size(curve) / 2;
258     double* values = new double[nPoints];
259     double* deltas = new double[nPoints];
260     for(int i=0; i<nPoints; i++) {
261         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
262         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
263     }
264
265     ((SGInterpolator*)globals->get_subsystem("interpolator"))
266         ->interpolate(node, nPoints, values, deltas);
267 }
268
269 static naRef f_rand(naContext c, naRef args)
270 {
271     return naNum(sg_random());
272 }
273
274 // Table of extension functions.  Terminate with zeros.
275 static struct { char* name; naCFunction func; } funcs[] = {
276     { "getprop",   f_getprop },
277     { "setprop",   f_setprop },
278     { "print",     f_print },
279     { "_fgcommand", f_fgcommand },
280     { "settimer",  f_settimer },
281     { "_cmdarg",  f_cmdarg },
282     { "_interpolate",  f_interpolate },
283     { "rand",  f_rand },
284     { 0, 0 }
285 };
286
287 naRef FGNasalSys::cmdArgGhost()
288 {
289     return propNodeGhost(_cmdArg);
290 }
291
292 void FGNasalSys::init()
293 {
294     int i;
295
296     _context = naNewContext();
297
298     // Start with globals.  Add it to itself as a recursive
299     // sub-reference under the name "globals".  This gives client-code
300     // write access to the namespace if someone wants to do something
301     // fancy.
302     _globals = naStdLib(_context);
303     naSave(_context, _globals);
304     hashset(_globals, "globals", _globals);
305
306     // Add in the math library under "math"
307     hashset(_globals, "math", naMathLib(_context));
308
309     // Add our custom extension functions:
310     for(i=0; funcs[i].name; i++)
311         hashset(_globals, funcs[i].name,
312                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
313
314     // And our SGPropertyNode wrapper
315     hashset(_globals, "props", genPropsModule());
316
317     // Make a "__gcsave" hash to hold the naRef objects which get
318     // passed to handles outside the interpreter (to protect them from
319     // begin garbage-collected).
320     _gcHash = naNewHash(_context);
321     hashset(_globals, "__gcsave", _gcHash);
322
323     // Now load the various source files in the Nasal directory
324     SGPath p(globals->get_fg_root());
325     p.append("Nasal");
326     ulDirEnt* dent;
327     ulDir* dir = ulOpenDir(p.c_str());
328     while(dir && (dent = ulReadDir(dir)) != 0) {
329         SGPath fullpath(p);
330         fullpath.append(dent->d_name);
331         SGPath file(dent->d_name);
332         if(file.extension() != "nas") continue;
333         readScriptFile(fullpath, file.base().c_str());
334     }
335
336     // Pull scripts out of the property tree, too
337     loadPropertyScripts();
338 }
339
340 // Loads the scripts found under /nasal in the global tree
341 void FGNasalSys::loadPropertyScripts()
342 {
343     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
344     if(!nasal) return;
345
346     for(int i=0; i<nasal->nChildren(); i++) {
347         SGPropertyNode* n = nasal->getChild(i);
348
349         const char* module = n->getName();
350         if(n->hasChild("module"))
351             module = n->getStringValue("module");
352
353         const char* file = n->getStringValue("file");
354         if(!n->hasChild("file")) file = 0; // Hrm...
355         if(file) {
356             SGPath p(globals->get_fg_root());
357             p.append(file);
358             readScriptFile(p, module);
359         }
360         
361         const char* src = n->getStringValue("script");
362         if(!n->hasChild("script")) src = 0; // Hrm...
363         if(src)
364             initModule(module, n->getPath(), src, strlen(src));
365
366         if(!file && !src)
367             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
368                    "no <file> or <script> defined in " <<
369                    "/nasal/" << module);
370     }
371 }
372
373 // Logs a runtime error, with stack trace, to the FlightGear log stream
374 void FGNasalSys::logError()
375 {
376     SG_LOG(SG_NASAL, SG_ALERT,
377            "Nasal runtime error: " << naGetError(_context));
378     SG_LOG(SG_NASAL, SG_ALERT,
379            "  at " << naStr_data(naGetSourceFile(_context, 0)) <<
380            ", line " << naGetLine(_context, 0));
381     for(int i=1; i<naStackDepth(_context); i++)
382         SG_LOG(SG_NASAL, SG_ALERT,
383                "  called from: " << naStr_data(naGetSourceFile(_context, i)) <<
384                ", line " << naGetLine(_context, i));
385 }
386
387 // Reads a script file, executes it, and places the resulting
388 // namespace into the global namespace under the specified module
389 // name.
390 void FGNasalSys::readScriptFile(SGPath file, const char* module)
391 {
392     int len = 0;
393     char* buf = readfile(file.c_str(), &len);
394     if(!buf) {
395         SG_LOG(SG_NASAL, SG_ALERT,
396                "Nasal error: could not read script file " << file.c_str()
397                << " into module " << module);
398         return;
399     }
400
401     initModule(module, file.c_str(), buf, len);
402     delete[] buf;
403 }
404
405 // Parse and run.  Save the local variables namespace, as it will
406 // become a sub-object of globals.
407 void FGNasalSys::initModule(const char* moduleName, const char* fileName,
408                             const char* src, int len)
409 {
410     if(len == 0) len = strlen(src);
411
412     naRef code = parse(fileName, src, len);
413     if(naIsNil(code))
414         return;
415
416     // See if we already have a module hash to use.  This allows the
417     // user to, for example, add functions to the built-in math
418     // module.  Make a new one if necessary.
419     naRef locals;
420     naRef modname = naNewString(_context);
421     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
422     if(!naHash_get(_globals, modname, &locals))
423         locals = naNewHash(_context);
424
425     naCall(_context, code, naNil(), naNil(), locals);
426     if(naGetError(_context)) {
427         logError();
428         return;
429     }
430     hashset(_globals, moduleName, locals);
431 }
432
433 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
434 {
435     if(len == 0) len = strlen(buf);
436     int errLine = -1;
437     naRef srcfile = naNewString(_context);
438     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
439     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
440     if(naIsNil(code)) {
441         SG_LOG(SG_NASAL, SG_ALERT,
442                "Nasal parse error: " << naGetError(_context) <<
443                " in "<< filename <<", line " << errLine);
444         return naNil();
445     }
446
447     // Bind to the global namespace before returning
448     return naBindFunction(_context, code, _globals);
449 }
450
451 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
452 {
453     // Parse the Nasal source.  I'd love to use the property name of
454     // the argument, but it's actually a *clone* of the original
455     // location in the property tree.  arg->getPath() returns an empty
456     // string.
457     const char* nasal = arg->getStringValue("script");
458     naRef code = parse("<command>", nasal);
459     if(naIsNil(code)) return false;
460     
461     // Cache the command argument for inspection via cmdarg().  For
462     // performance reasons, we won't bother with it if the invoked
463     // code doesn't need it.
464     _cmdArg = (SGPropertyNode*)arg;
465
466     // Call it!
467     naRef result = naCall(_context, code, naNil(), naNil(), naNil());
468     if(!naGetError(_context)) return true;
469     logError();
470     return false;
471 }
472
473 // settimer(func, dt, simtime) extension function.  The first argument
474 // is a Nasal function to call, the second is a delta time (from now),
475 // in seconds.  The third, if present, is a boolean value indicating
476 // that "simulator" time (rather than real time) is to be used.
477 //
478 // Implementation note: the FGTimer objects don't live inside the
479 // garbage collector, so the Nasal handler functions have to be
480 // "saved" somehow lest they be inadvertently cleaned.  In this case,
481 // they are inserted into a globals.__gcsave hash and removed on
482 // expiration.
483 void FGNasalSys::setTimer(naRef args)
484 {
485     // Extract the handler, delta, and simtime arguments:
486     naRef handler = naVec_get(args, 0);
487     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
488         return;
489
490     naRef delta = naNumValue(naVec_get(args, 1));
491     if(naIsNil(delta)) return;
492     
493     bool simtime = naTrue(naVec_get(args, 2)) ? true : false;
494
495     // Generate and register a C++ timer handler
496     NasalTimer* t = new NasalTimer;
497     t->handler = handler;
498     t->gcKey = gcSave(handler);
499     t->nasal = this;
500
501     globals->get_event_mgr()->addEvent("NasalTimer",
502                                        t, &NasalTimer::timerExpired,
503                                        delta.num, simtime);
504 }
505
506 void FGNasalSys::handleTimer(NasalTimer* t)
507 {
508     naCall(_context, t->handler, naNil(), naNil(), naNil());
509     gcRelease(t->gcKey);
510 }
511
512 int FGNasalSys::gcSave(naRef r)
513 {
514     int key = _nextGCKey++;
515     naHash_set(_gcHash, naNum(key), r);
516     return key;
517 }
518
519 void FGNasalSys::gcRelease(int key)
520 {
521     naHash_delete(_gcHash, naNum(key));
522 }
523
524 void FGNasalSys::NasalTimer::timerExpired()
525 {
526     nasal->handleTimer(this);
527     delete this;
528 }