]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
41de581a649d9772ce13b47bfdbe7c393b887401
[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 #include "NasalDisplay.hxx"
20
21 // Read and return file contents in a single buffer.  Note use of
22 // stat() to get the file size.  This is a win32 function, believe it
23 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
24 // Text mode brain damage will kill us if we're trying to do bytewise
25 // I/O.
26 static char* readfile(const char* file, int* lenOut)
27 {
28     struct stat data;
29     if(stat(file, &data) != 0) return 0;
30     FILE* f = fopen(file, "rb");
31     if(!f) return 0;
32     char* buf = new char[data.st_size];
33     *lenOut = fread(buf, 1, data.st_size, f);
34     fclose(f);
35     if(*lenOut != data.st_size) {
36         // Shouldn't happen, but warn anyway since it represents a
37         // platform bug and not a typical runtime error (missing file,
38         // etc...)
39         SG_LOG(SG_NASAL, SG_ALERT,
40                "ERROR in Nasal initialization: " <<
41                "short count returned from fread() of " << file <<
42                ".  Check your C library!");
43         delete[] buf;
44         return 0;
45     }
46     return buf;
47 }
48
49 FGNasalSys::FGNasalSys()
50 {
51     _context = 0;
52     _globals = naNil();
53     _gcHash = naNil();
54     _nextGCKey = 0; // Any value will do
55 }
56
57 FGNasalSys::~FGNasalSys()
58 {
59     // Nasal doesn't have a "destroy context" API yet. :(
60     // Not a problem for a global subsystem that will never be
61     // destroyed.  And the context is actually a global, so no memory
62     // is technically leaked (although the GC pool memory obviously
63     // won't be freed).
64     _context = 0;
65     _globals = naNil();
66 }
67
68 bool FGNasalSys::parseAndRun(const char* sourceCode)
69 {
70     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
71                        strlen(sourceCode));
72     if(naIsNil(code))
73         return false;
74
75     naCall(_context, code, 0, 0, naNil(), naNil());
76
77     if(!naGetError(_context)) return true;
78     logError();
79     return false;
80 }
81
82 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
83 {
84     FGNasalScript* script = new FGNasalScript();
85     script->_gcKey = -1; // important, if we delete it on a parse
86     script->_nas = this; // error, don't clobber a real handle!
87
88     char buf[256];
89     if(!name) {
90         sprintf(buf, "FGNasalScript@%p", script);
91         name = buf;
92     }
93
94     script->_code = parse(name, src, strlen(src));
95     if(naIsNil(script->_code)) {
96         delete script;
97         return 0;
98     }
99
100     script->_gcKey = gcSave(script->_code);
101     return script;
102 }
103
104 // Utility.  Sets a named key in a hash by C string, rather than nasal
105 // string object.
106 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
107 {
108     naRef s = naNewString(_context);
109     naStr_fromdata(s, (char*)key, strlen(key));
110     naHash_set(hash, s, val);
111 }
112
113 // The get/setprop functions accept a *list* of strings and walk
114 // through the property tree with them to find the appropriate node.
115 // This allows a Nasal object to hold onto a property path and use it
116 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
117 // is the utility function that walks the property tree.
118 // Future enhancement: support integer arguments to specify array
119 // elements.
120 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
121 {
122     SGPropertyNode* p = globals->get_props();
123     for(int i=0; i<len; i++) {
124         naRef a = vec[i];
125         if(!naIsString(a)) return 0;
126         p = p->getNode(naStr_data(a));
127         if(p == 0) return 0;
128     }
129     return p;
130 }
131
132 // getprop() extension function.  Concatenates its string arguments as
133 // property names and returns the value of the specified property.  Or
134 // nil if it doesn't exist.
135 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
136 {
137     const SGPropertyNode* p = findnode(c, args, argc);
138     if(!p) return naNil();
139
140     switch(p->getType()) {
141     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
142     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
143     case SGPropertyNode::DOUBLE:
144         return naNum(p->getDoubleValue());
145
146     case SGPropertyNode::STRING:
147     case SGPropertyNode::UNSPECIFIED:
148         {
149             naRef nastr = naNewString(c);
150             const char* val = p->getStringValue();
151             naStr_fromdata(nastr, (char*)val, strlen(val));
152             return nastr;
153         }
154     case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
155     default:
156         return naNil();
157     }
158 }
159
160 // setprop() extension function.  Concatenates its string arguments as
161 // property names and sets the value of the specified property to the
162 // final argument.
163 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
164 {
165 #define BUFLEN 1024
166     char buf[BUFLEN + 1];
167     buf[BUFLEN] = 0;
168     char* p = buf;
169     int buflen = BUFLEN;
170     for(int i=0; i<argc-1; i++) {
171         naRef s = naStringValue(c, args[i]);
172         if(naIsNil(s)) return naNil();
173         strncpy(p, naStr_data(s), buflen);
174         p += naStr_len(s);
175         buflen = BUFLEN - (p - buf);
176         if(i < (argc-2) && buflen > 0) {
177             *p++ = '/';
178             buflen--;
179         }
180     }
181
182     SGPropertyNode* props = globals->get_props();
183     naRef val = args[argc-1];
184     if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
185     else                props->setDoubleValue(buf, naNumValue(val).num);
186     return naNil();
187 #undef BUFLEN
188 }
189
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 me, int argc, naRef* args)
194 {
195 #define BUFLEN 1024
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
199     char* p = buf;
200     int buflen = BUFLEN;
201     int n = argc;
202     for(int i=0; i<n; i++) {
203         naRef s = naStringValue(c, args[i]);
204         if(naIsNil(s)) continue;
205         strncpy(p, naStr_data(s), buflen);
206         p += naStr_len(s);
207         buflen = BUFLEN - (p - buf);
208         if(buflen <= 0) break;
209     }
210     SG_LOG(SG_GENERAL, SG_ALERT, buf);
211     return naNil();
212 #undef BUFLEN
213 }
214
215 // fgcommand() extension function.  Executes a named command via the
216 // FlightGear command manager.  Takes a single property node name as
217 // an argument.
218 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
219 {
220     if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
221         naRuntimeError(c, "bad arguments to fgcommand()");
222     naRef cmd = args[0], props = args[1];
223     SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
224     globals->get_commands()->execute(naStr_data(cmd), *node);
225     return naNil();
226
227 }
228
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 me, int argc, naRef* args)
232 {
233     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
234     nasal->setTimer(argc, args);
235     return naNil();
236 }
237
238 // setlistener(func, property) extension function.  Falls through to
239 // FGNasalSys::setListener().  See there for docs.
240 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
241 {
242     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
243     nasal->setListener(argc, args);
244     return naNil();
245 }
246
247 // Returns a ghost handle to the argument to the currently executing
248 // command
249 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
250 {
251     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
252     return nasal->cmdArgGhost();
253 }
254
255 // Sets up a property interpolation.  The first argument is either a
256 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
257 // interpolate.  The second argument is a vector of pairs of
258 // value/delta numbers.
259 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
260 {
261     SGPropertyNode* node;
262     naRef prop = argc > 0 ? args[0] : naNil();
263     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
264     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
265     else return naNil();
266
267     naRef curve = argc > 1 ? args[1] : naNil();
268     if(!naIsVector(curve)) return naNil();
269     int nPoints = naVec_size(curve) / 2;
270     double* values = new double[nPoints];
271     double* deltas = new double[nPoints];
272     for(int i=0; i<nPoints; i++) {
273         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
274         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
275     }
276
277     ((SGInterpolator*)globals->get_subsystem("interpolator"))
278         ->interpolate(node, nPoints, values, deltas);
279
280     return naNil();
281 }
282
283 // This is a better RNG than the one in the default Nasal distribution
284 // (which is based on the C library rand() implementation). It will
285 // override.
286 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
287 {
288     return naNum(sg_random());
289 }
290
291 // Wrapper function for screenPrint
292 static naRef f_screenPrint(naContext c, naRef me, int argc, naRef* args)
293 {
294     if(argc != 1 || !naIsString(args[0]))
295         naRuntimeError(c, "bad arguments to screenPrint()");
296     naRef lmsg = args[0];
297     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
298     nasal->screenPrint(naStr_data(lmsg));
299     return naNil();
300 }
301
302 // Return an array listing of all files in a directory
303 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
304 {
305     if(argc != 1 || !naIsString(args[0]))
306         naRuntimeError(c, "bad arguments to directory()");
307     naRef ldir = args[0];
308     ulDir* dir = ulOpenDir(naStr_data(args[0]));
309     if(!dir) return naNil();
310     naRef result = naNewVector(c);
311     ulDirEnt* dent;
312     while((dent = ulReadDir(dir)))
313         naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
314                                             strlen(dent->d_name)));
315     ulCloseDir(dir);
316     return result;
317 }
318
319 // Table of extension functions.  Terminate with zeros.
320 static struct { char* name; naCFunction func; } funcs[] = {
321     { "getprop",   f_getprop },
322     { "setprop",   f_setprop },
323     { "print",     f_print },
324     { "_fgcommand", f_fgcommand },
325     { "settimer",  f_settimer },
326     { "_setlistener", f_setlistener },
327     { "_cmdarg",  f_cmdarg },
328     { "_interpolate",  f_interpolate },
329     { "rand",  f_rand },
330     { "screenPrint", f_screenPrint },
331     { "directory", f_directory },
332     { 0, 0 }
333 };
334
335 naRef FGNasalSys::cmdArgGhost()
336 {
337     return propNodeGhost(_cmdArg);
338 }
339
340 void FGNasalSys::init()
341 {
342     int i;
343
344     _context = naNewContext();
345
346     // Start with globals.  Add it to itself as a recursive
347     // sub-reference under the name "globals".  This gives client-code
348     // write access to the namespace if someone wants to do something
349     // fancy.
350     _globals = naStdLib(_context);
351     naSave(_context, _globals);
352     hashset(_globals, "globals", _globals);
353
354     // Add in the math library under "math"
355     hashset(_globals, "math", naMathLib(_context));
356
357     // Add our custom extension functions:
358     for(i=0; funcs[i].name; i++)
359         hashset(_globals, funcs[i].name,
360                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
361
362     // And our SGPropertyNode wrapper
363     hashset(_globals, "props", genPropsModule());
364
365     // Make a "__gcsave" hash to hold the naRef objects which get
366     // passed to handles outside the interpreter (to protect them from
367     // begin garbage-collected).
368     _gcHash = naNewHash(_context);
369     hashset(_globals, "__gcsave", _gcHash);
370
371     // Now load the various source files in the Nasal directory
372     SGPath p(globals->get_fg_root());
373     p.append("Nasal");
374     ulDirEnt* dent;
375     ulDir* dir = ulOpenDir(p.c_str());
376     while(dir && (dent = ulReadDir(dir)) != 0) {
377         SGPath fullpath(p);
378         fullpath.append(dent->d_name);
379         SGPath file(dent->d_name);
380         if(file.extension() != "nas") continue;
381         loadModule(fullpath, file.base().c_str());
382     }
383
384     // Pull scripts out of the property tree, too
385     loadPropertyScripts();
386 }
387
388 // Loads the scripts found under /nasal in the global tree
389 void FGNasalSys::loadPropertyScripts()
390 {
391     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
392     if(!nasal) return;
393
394     for(int i=0; i<nasal->nChildren(); i++) {
395         SGPropertyNode* n = nasal->getChild(i);
396
397         const char* module = n->getName();
398         if(n->hasChild("module"))
399             module = n->getStringValue("module");
400
401         // allow multiple files to be specified within in a single
402         // Nasal module tag
403         int j = 0;
404         SGPropertyNode *fn;
405         bool file_specified = false;
406         while ( (fn = n->getChild("file", j)) != NULL ) {
407             file_specified = true;
408             const char* file = fn->getStringValue();
409             SGPath p(globals->get_fg_root());
410             p.append(file);
411             loadModule(p, module);
412             j++;
413         }
414
415         // Old code which only allowed a single file to be specified per module
416         /*
417         const char* file = n->getStringValue("file");
418         if(!n->hasChild("file")) file = 0; // Hrm...
419         if(file) {
420             SGPath p(globals->get_fg_root());
421             p.append(file);
422             loadModule(p, module);
423         }
424         */
425         
426         const char* src = n->getStringValue("script");
427         if(!n->hasChild("script")) src = 0; // Hrm...
428         if(src)
429             createModule(module, n->getPath(), src, strlen(src));
430
431         if(!file_specified && !src)
432             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
433                    "no <file> or <script> defined in " <<
434                    "/nasal/" << module);
435     }
436 }
437
438 // Logs a runtime error, with stack trace, to the FlightGear log stream
439 void FGNasalSys::logError()
440 {
441     SG_LOG(SG_NASAL, SG_ALERT,
442            "Nasal runtime error: " << naGetError(_context));
443     SG_LOG(SG_NASAL, SG_ALERT,
444            "  at " << naStr_data(naGetSourceFile(_context, 0)) <<
445            ", line " << naGetLine(_context, 0));
446     for(int i=1; i<naStackDepth(_context); i++)
447         SG_LOG(SG_NASAL, SG_ALERT,
448                "  called from: " << naStr_data(naGetSourceFile(_context, i)) <<
449                ", line " << naGetLine(_context, i));
450 }
451
452 // Reads a script file, executes it, and places the resulting
453 // namespace into the global namespace under the specified module
454 // name.
455 void FGNasalSys::loadModule(SGPath file, const char* module)
456 {
457     int len = 0;
458     char* buf = readfile(file.c_str(), &len);
459     if(!buf) {
460         SG_LOG(SG_NASAL, SG_ALERT,
461                "Nasal error: could not read script file " << file.c_str()
462                << " into module " << module);
463         return;
464     }
465
466     createModule(module, file.c_str(), buf, len);
467     delete[] buf;
468 }
469
470 // Parse and run.  Save the local variables namespace, as it will
471 // become a sub-object of globals.
472 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
473                               const char* src, int len)
474 {
475     naRef code = parse(fileName, src, len);
476     if(naIsNil(code))
477         return;
478
479     // See if we already have a module hash to use.  This allows the
480     // user to, for example, add functions to the built-in math
481     // module.  Make a new one if necessary.
482     naRef locals;
483     naRef modname = naNewString(_context);
484     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
485     if(!naHash_get(_globals, modname, &locals))
486         locals = naNewHash(_context);
487
488     naCall(_context, code, 0, 0, naNil(), locals);
489     if(naGetError(_context)) {
490         logError();
491         return;
492     }
493     hashset(_globals, moduleName, locals);
494 }
495
496 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
497 {
498     int errLine = -1;
499     naRef srcfile = naNewString(_context);
500     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
501     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
502     if(naIsNil(code)) {
503         SG_LOG(SG_NASAL, SG_ALERT,
504                "Nasal parse error: " << naGetError(_context) <<
505                " in "<< filename <<", line " << errLine);
506         return naNil();
507     }
508
509     // Bind to the global namespace before returning
510     return naBindFunction(_context, code, _globals);
511 }
512
513 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
514 {
515     const char* nasal = arg->getStringValue("script");
516     const char* moduleName = arg->getStringValue("module");
517     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
518     if(naIsNil(code)) return false;
519
520     naRef locals = naNil();
521     if (moduleName[0]) {
522         naRef modname = naNewString(_context);
523         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
524         if(!naHash_get(_globals, modname, &locals))
525             locals = naNewHash(_context);
526     }
527     // Cache the command argument for inspection via cmdarg().  For
528     // performance reasons, we won't bother with it if the invoked
529     // code doesn't need it.
530     _cmdArg = (SGPropertyNode*)arg;
531
532     // Call it!
533     naRef result = naCall(_context, code, 0, 0, naNil(), locals);
534     if(!naGetError(_context)) return true;
535     logError();
536     return false;
537 }
538
539 // settimer(func, dt, simtime) extension function.  The first argument
540 // is a Nasal function to call, the second is a delta time (from now),
541 // in seconds.  The third, if present, is a boolean value indicating
542 // that "real world" time (rather than simulator time) is to be used.
543 //
544 // Implementation note: the FGTimer objects don't live inside the
545 // garbage collector, so the Nasal handler functions have to be
546 // "saved" somehow lest they be inadvertently cleaned.  In this case,
547 // they are inserted into a globals.__gcsave hash and removed on
548 // expiration.
549 void FGNasalSys::setTimer(int argc, naRef* args)
550 {
551     // Extract the handler, delta, and simtime arguments:
552     naRef handler = argc > 0 ? args[0] : naNil();
553     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
554         return;
555
556     naRef delta = argc > 1 ? args[1] : naNil();
557     if(naIsNil(delta)) return;
558     
559     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
560
561     // Generate and register a C++ timer handler
562     NasalTimer* t = new NasalTimer;
563     t->handler = handler;
564     t->gcKey = gcSave(handler);
565     t->nasal = this;
566
567     globals->get_event_mgr()->addEvent("NasalTimer",
568                                        t, &NasalTimer::timerExpired,
569                                        delta.num, simtime);
570 }
571
572 void FGNasalSys::handleTimer(NasalTimer* t)
573 {
574     naCall(_context, t->handler, 0, 0, naNil(), naNil());
575     if(naGetError(_context))
576         logError();
577     gcRelease(t->gcKey);
578 }
579
580 int FGNasalSys::gcSave(naRef r)
581 {
582     int key = _nextGCKey++;
583     naHash_set(_gcHash, naNum(key), r);
584     return key;
585 }
586
587 void FGNasalSys::gcRelease(int key)
588 {
589     naHash_delete(_gcHash, naNum(key));
590 }
591
592 void FGNasalSys::NasalTimer::timerExpired()
593 {
594     nasal->handleTimer(this);
595     delete this;
596 }
597
598 // setlistener(property, func) extension function.  The first argument
599 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
600 // path), the second is a Nasal function.
601 void FGNasalSys::setListener(int argc, naRef* args)
602 {
603     SGPropertyNode* node;
604     naRef prop = argc > 0 ? args[0] : naNil();
605     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
606     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
607     else return;
608
609     naRef handler = argc > 1 ? args[1] : naNil();
610     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
611         return;
612
613     node->addChangeListener(new FGNasalListener(handler, this, gcSave(handler)));
614 }
615
616 // functions providing access to the NasalDisplay - used to display text directly on the screen
617 void FGNasalSys::screenPrint(const char* src)
618 {
619   globals->get_Nasal_display()->RegisterSingleMessage(src, 0);
620 }