]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
rename FGAirportSearchFilter::acceptable() -> ::pass()
[flightgear.git] / src / Scripting / NasalSys.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #ifdef HAVE_SYS_TIME_H
7 #  include <sys/time.h>  // gettimeofday
8 #endif
9
10 #include <string.h>
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fstream>
15
16 #include <plib/ul.h>
17
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>
26
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>
32
33 #include "NasalSys.hxx"
34
35 static FGNasalSys* nasalSys = 0;
36
37
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
42 // I/O.
43 static char* readfile(const char* file, int* lenOut)
44 {
45     struct stat data;
46     if(stat(file, &data) != 0) return 0;
47     FILE* f = fopen(file, "rb");
48     if(!f) return 0;
49     char* buf = new char[data.st_size];
50     *lenOut = fread(buf, 1, data.st_size, f);
51     fclose(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,
55         // etc...)
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!");
60         delete[] buf;
61         return 0;
62     }
63     return buf;
64 }
65
66 FGNasalSys::FGNasalSys()
67 {
68     nasalSys = this;
69     _context = 0;
70     _globals = naNil();
71     _gcHash = naNil();
72     _nextGCKey = 0; // Any value will do
73     _callCount = 0;
74     _purgeListeners = false;
75 }
76
77 // Does a naCall() in a new context.  Wrapped here to make lock
78 // tracking easier.  Extension functions are called with the lock, but
79 // we have to release it before making a new naCall().  So rather than
80 // drop the lock in every extension function that might call back into
81 // Nasal, we keep a stack depth counter here and only unlock/lock
82 // around the naCall if it isn't the first one.
83 naRef FGNasalSys::call(naRef code, naRef locals)
84 {
85     naContext ctx = naNewContext();
86     if(_callCount) naModUnlock();
87     _callCount++;
88     naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
89     if(naGetError(ctx))
90         logError(ctx);
91     _callCount--;
92     if(_callCount) naModLock();
93     naFreeContext(ctx);
94     return result;
95 }
96
97 FGNasalSys::~FGNasalSys()
98 {
99     nasalSys = 0;
100     map<int, FGNasalListener *>::iterator it, end = _listener.end();
101     for(it = _listener.begin(); it != end; ++it)
102         delete it->second;
103
104     naFreeContext(_context);
105     _globals = naNil();
106 }
107
108 bool FGNasalSys::parseAndRun(const char* sourceCode)
109 {
110     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
111                        strlen(sourceCode));
112     if(naIsNil(code))
113         return false;
114     call(code, naNil());
115     return true;
116 }
117
118 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
119 {
120     FGNasalScript* script = new FGNasalScript();
121     script->_gcKey = -1; // important, if we delete it on a parse
122     script->_nas = this; // error, don't clobber a real handle!
123
124     char buf[256];
125     if(!name) {
126         sprintf(buf, "FGNasalScript@%p", (void *)script);
127         name = buf;
128     }
129
130     script->_code = parse(name, src, strlen(src));
131     if(naIsNil(script->_code)) {
132         delete script;
133         return 0;
134     }
135
136     script->_gcKey = gcSave(script->_code);
137     return script;
138 }
139
140 // Utility.  Sets a named key in a hash by C string, rather than nasal
141 // string object.
142 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
143 {
144     naRef s = naNewString(_context);
145     naStr_fromdata(s, (char*)key, strlen(key));
146     naHash_set(hash, s, val);
147 }
148
149 // The get/setprop functions accept a *list* of strings and walk
150 // through the property tree with them to find the appropriate node.
151 // This allows a Nasal object to hold onto a property path and use it
152 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
153 // is the utility function that walks the property tree.
154 // Future enhancement: support integer arguments to specify array
155 // elements.
156 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
157 {
158     SGPropertyNode* p = globals->get_props();
159     try {
160         for(int i=0; i<len; i++) {
161             naRef a = vec[i];
162             if(!naIsString(a)) return 0;
163             p = p->getNode(naStr_data(a));
164             if(p == 0) return 0;
165         }
166     } catch (const string& err) {
167         naRuntimeError(c, (char *)err.c_str());
168         return 0;
169     }
170     return p;
171 }
172
173 // getprop() extension function.  Concatenates its string arguments as
174 // property names and returns the value of the specified property.  Or
175 // nil if it doesn't exist.
176 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
177 {
178     const SGPropertyNode* p = findnode(c, args, argc);
179     if(!p) return naNil();
180
181     switch(p->getType()) {
182     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
183     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
184     case SGPropertyNode::DOUBLE:
185         return naNum(p->getDoubleValue());
186
187     case SGPropertyNode::STRING:
188     case SGPropertyNode::UNSPECIFIED:
189         {
190             naRef nastr = naNewString(c);
191             const char* val = p->getStringValue();
192             naStr_fromdata(nastr, (char*)val, strlen(val));
193             return nastr;
194         }
195     case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
196     default:
197         return naNil();
198     }
199 }
200
201 // setprop() extension function.  Concatenates its string arguments as
202 // property names and sets the value of the specified property to the
203 // final argument.
204 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
205 {
206 #define BUFLEN 1024
207     char buf[BUFLEN + 1];
208     buf[BUFLEN] = 0;
209     char* p = buf;
210     int buflen = BUFLEN;
211     for(int i=0; i<argc-1; i++) {
212         naRef s = naStringValue(c, args[i]);
213         if(naIsNil(s)) return naNil();
214         strncpy(p, naStr_data(s), buflen);
215         p += naStr_len(s);
216         buflen = BUFLEN - (p - buf);
217         if(i < (argc-2) && buflen > 0) {
218             *p++ = '/';
219             buflen--;
220         }
221     }
222
223     SGPropertyNode* props = globals->get_props();
224     naRef val = args[argc-1];
225     bool ret;
226     try {
227         if(naIsString(val)) ret = props->setStringValue(buf, naStr_data(val));
228         else {
229             naRef n = naNumValue(val);
230             if(naIsNil(n))
231                 naRuntimeError(c, "setprop() value is not string or number");
232             ret = props->setDoubleValue(buf, n.num);
233         }
234     } catch (const string& err) {
235         naRuntimeError(c, (char *)err.c_str());
236     }
237     if(!ret) naRuntimeError(c, "setprop(): property is not writable");
238     return naNil();
239 #undef BUFLEN
240 }
241
242 // print() extension function.  Concatenates and prints its arguments
243 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
244 // make sure it appears.  Is there better way to do this?
245 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
246 {
247     string buf;
248     int n = argc;
249     for(int i=0; i<n; i++) {
250         naRef s = naStringValue(c, args[i]);
251         if(naIsNil(s)) continue;
252         buf += naStr_data(s);
253     }
254     SG_LOG(SG_GENERAL, SG_ALERT, buf);
255     return naNum(buf.length());
256 }
257
258 // fgcommand() extension function.  Executes a named command via the
259 // FlightGear command manager.  Takes a single property node name as
260 // an argument.
261 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
262 {
263     naRef cmd = argc > 0 ? args[0] : naNil();
264     naRef props = argc > 1 ? args[1] : naNil();
265     if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
266         naRuntimeError(c, "bad arguments to fgcommand()");
267     SGPropertyNode_ptr tmp, *node;
268     if(!naIsNil(props))
269         node = (SGPropertyNode_ptr*)naGhost_ptr(props);
270     else {
271         tmp = new SGPropertyNode();
272         node = &tmp;
273     }
274     return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
275 }
276
277 // settimer(func, dt, simtime) extension function.  Falls through to
278 // FGNasalSys::setTimer().  See there for docs.
279 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
280 {
281     nasalSys->setTimer(c, argc, args);
282     return naNil();
283 }
284
285 // setlistener(func, property, bool) extension function.  Falls through to
286 // FGNasalSys::setListener().  See there for docs.
287 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
288 {
289     return nasalSys->setListener(c, argc, args);
290 }
291
292 // removelistener(int) extension function. Falls through to
293 // FGNasalSys::removeListener(). See there for docs.
294 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
295 {
296     return nasalSys->removeListener(c, argc, args);
297 }
298
299 // Returns a ghost handle to the argument to the currently executing
300 // command
301 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
302 {
303     return nasalSys->cmdArgGhost();
304 }
305
306 // Sets up a property interpolation.  The first argument is either a
307 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
308 // interpolate.  The second argument is a vector of pairs of
309 // value/delta numbers.
310 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
311 {
312     SGPropertyNode* node;
313     naRef prop = argc > 0 ? args[0] : naNil();
314     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
315     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
316     else return naNil();
317
318     naRef curve = argc > 1 ? args[1] : naNil();
319     if(!naIsVector(curve)) return naNil();
320     int nPoints = naVec_size(curve) / 2;
321     double* values = new double[nPoints];
322     double* deltas = new double[nPoints];
323     for(int i=0; i<nPoints; i++) {
324         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
325         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
326     }
327
328     ((SGInterpolator*)globals->get_subsystem_mgr()
329         ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
330         ->interpolate(node, nPoints, values, deltas);
331
332     return naNil();
333 }
334
335 // This is a better RNG than the one in the default Nasal distribution
336 // (which is based on the C library rand() implementation). It will
337 // override.
338 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
339 {
340     return naNum(sg_random());
341 }
342
343 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
344 {
345     sg_srandom_time();
346     return naNum(0);
347 }
348
349 // Return an array listing of all files in a directory
350 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
351 {
352     if(argc != 1 || !naIsString(args[0]))
353         naRuntimeError(c, "bad arguments to directory()");
354     naRef ldir = args[0];
355     ulDir* dir = ulOpenDir(naStr_data(args[0]));
356     if(!dir) return naNil();
357     naRef result = naNewVector(c);
358     ulDirEnt* dent;
359     while((dent = ulReadDir(dir)))
360         naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
361                                             strlen(dent->d_name)));
362     ulCloseDir(dir);
363     return result;
364 }
365
366 // Parse XML file.
367 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
368 //
369 // <path>      ... absolute path to an XML file
370 // <start-tag> ... callback function with two args: tag name, attribute hash
371 // <end-tag>   ... callback function with one arg:  tag name
372 // <data>      ... callback function with one arg:  data
373 // <pi>        ... callback function with two args: target, data
374 //                 (pi = "processing instruction")
375 // All four callback functions are optional and default to nil.
376 // The function returns nil on error, and the file name otherwise.
377 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
378 {
379     if(argc < 1 || !naIsString(args[0]))
380         naRuntimeError(c, "parsexml(): path argument missing or not a string");
381     if(argc > 5) argc = 5;
382     for(int i=1; i<argc; i++)
383         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
384             naRuntimeError(c, "parsexml(): callback argument not a function");
385
386     const char* file = naStr_data(args[0]);
387     std::ifstream input(file);
388     NasalXMLVisitor visitor(c, argc, args);
389     try {
390         readXML(input, visitor);
391     } catch (const sg_exception& e) {
392         string msg = string("parsexml(): file '") + file + "' "
393                      + e.getFormattedMessage();
394         naRuntimeError(c, msg.c_str());
395         return naNil();
396     }
397     return args[0];
398 }
399
400 // Return UNIX epoch time in seconds.
401 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
402 {
403 #ifdef WIN32
404     FILETIME ft;
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);
409 #else
410     time_t t;
411     struct timeval td;
412     do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
413     return naNum(t + 1e-6 * td.tv_usec);
414 #endif
415
416 }
417
418 // Convert a cartesian point to a geodetic lat/lon/altitude.
419 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
420 {
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));
432     return vec;
433 }
434
435 // Convert a geodetic lat/lon/altitude to a cartesian point.
436 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
437 {
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;
442     double xyz[3];
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]));
448     return vec;
449 }
450
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
454 // of the hash.
455 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
456 {
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;
461     double elev;
462     const SGMaterial *mat;
463     if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
464         return naNil();
465     naRef vec = naNewVector(c);
466     naVec_append(vec, naNum(elev));
467     naRef matdata = naNil();
468     if(mat) {
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()));
482     }
483     naVec_append(vec, matdata);
484     return vec;
485 #undef HASHSET
486 }
487
488
489 class airport_filter : public FGAirportSearchFilter {
490     virtual bool pass(FGAirport *a) { return a->isAirport(); }
491 } airport;
492
493 // Returns airport data for given airport id ("KSFO"), or for the airport
494 // nearest to a given lat/lon pair, or without arguments, to the current
495 // aircraft position. Returns nil on error. Only one side of each runway is
496 // returned.
497 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
498 {
499     static SGConstPropertyNode_ptr lat = fgGetNode("/position/latitude-deg", true);
500     static SGConstPropertyNode_ptr lon = fgGetNode("/position/longitude-deg", true);
501
502     // airport
503     FGAirportList *aptlst = globals->get_airports();
504     FGAirport *apt;
505     if(argc == 0)
506         apt = aptlst->search(lon->getDoubleValue(), lat->getDoubleValue(), airport);
507     else if(argc == 1 && naIsString(args[0]))
508         apt = aptlst->search(naStr_data(args[0]));
509     else if(argc == 2 && naIsNum(args[0]) && naIsNum(args[1]))
510         apt = aptlst->search(args[1].num, args[0].num, airport);
511     else {
512         naRuntimeError(c, "airportinfo() with invalid function arguments");
513         return naNil();
514     }
515     if(!apt) {
516         naRuntimeError(c, "airportinfo(): no airport found");
517         return naNil();
518     }
519
520     string id = apt->getId();
521     string name = apt->getName();
522
523     // set runway hash
524     FGRunwayList *rwylst = globals->get_runways();
525     FGRunway rwy;
526     naRef rwys = naNewHash(c);
527     if(rwylst->search(id, &rwy)) {
528         do {
529             if(rwy._id != id) break;
530             if(rwy._type[0] != 'r') continue;
531
532             naRef rwydata = naNewHash(c);
533 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
534             HASHSET("lat", 3, naNum(rwy._lat));
535             HASHSET("lon", 3, naNum(rwy._lon));
536             HASHSET("heading", 7, naNum(rwy._heading));
537             HASHSET("length", 6, naNum(rwy._length * SG_FEET_TO_METER));
538             HASHSET("width", 5, naNum(rwy._width * SG_FEET_TO_METER));
539             HASHSET("threshold1", 10, naNum(rwy._displ_thresh1 * SG_FEET_TO_METER));
540             HASHSET("threshold2", 10, naNum(rwy._displ_thresh2 * SG_FEET_TO_METER));
541             HASHSET("stopway1", 8, naNum(rwy._stopway1 * SG_FEET_TO_METER));
542             HASHSET("stopway2", 8, naNum(rwy._stopway2 * SG_FEET_TO_METER));
543 #undef HASHSET
544
545             naRef no = naStr_fromdata(naNewString(c),
546                     const_cast<char *>(rwy._rwy_no.c_str()),
547                     rwy._rwy_no.length());
548             naHash_set(rwys, no, rwydata);
549         } while(rwylst->next(&rwy));
550     }
551
552     // set airport hash
553     naRef aptdata = naNewHash(c);
554 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
555     HASHSET("id", 2, naStr_fromdata(naNewString(c),
556             const_cast<char *>(id.c_str()), id.length()));
557     HASHSET("name", 4, naStr_fromdata(naNewString(c),
558             const_cast<char *>(name.c_str()), name.length()));
559     HASHSET("lat", 3, naNum(apt->getLatitude()));
560     HASHSET("lon", 3, naNum(apt->getLongitude()));
561     HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
562     HASHSET("has_metar", 9, naNum(apt->getMetar()));
563     HASHSET("runways", 7, rwys);
564 #undef HASHSET
565     return aptdata;
566 }
567
568
569 // Table of extension functions.  Terminate with zeros.
570 static struct { char* name; naCFunction func; } funcs[] = {
571     { "getprop",   f_getprop },
572     { "setprop",   f_setprop },
573     { "print",     f_print },
574     { "_fgcommand", f_fgcommand },
575     { "settimer",  f_settimer },
576     { "_setlistener", f_setlistener },
577     { "removelistener", f_removelistener },
578     { "_cmdarg",  f_cmdarg },
579     { "_interpolate",  f_interpolate },
580     { "rand",  f_rand },
581     { "srand",  f_srand },
582     { "directory", f_directory },
583     { "parsexml", f_parsexml },
584     { "systime", f_systime },
585     { "carttogeod", f_carttogeod },
586     { "geodtocart", f_geodtocart },
587     { "geodinfo", f_geodinfo },
588     { "airportinfo", f_airportinfo },
589     { 0, 0 }
590 };
591
592 naRef FGNasalSys::cmdArgGhost()
593 {
594     return propNodeGhost(_cmdArg);
595 }
596
597 void FGNasalSys::init()
598 {
599     int i;
600
601     _context = naNewContext();
602
603     // Start with globals.  Add it to itself as a recursive
604     // sub-reference under the name "globals".  This gives client-code
605     // write access to the namespace if someone wants to do something
606     // fancy.
607     _globals = naInit_std(_context);
608     naSave(_context, _globals);
609     hashset(_globals, "globals", _globals);
610
611     hashset(_globals, "math", naInit_math(_context));
612     hashset(_globals, "bits", naInit_bits(_context));
613     hashset(_globals, "io", naInit_io(_context));
614     hashset(_globals, "thread", naInit_thread(_context));
615     hashset(_globals, "utf8", naInit_utf8(_context));
616
617     // Add our custom extension functions:
618     for(i=0; funcs[i].name; i++)
619         hashset(_globals, funcs[i].name,
620                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
621
622     // And our SGPropertyNode wrapper
623     hashset(_globals, "props", genPropsModule());
624
625     // Make a "__gcsave" hash to hold the naRef objects which get
626     // passed to handles outside the interpreter (to protect them from
627     // begin garbage-collected).
628     _gcHash = naNewHash(_context);
629     hashset(_globals, "__gcsave", _gcHash);
630
631     // Now load the various source files in the Nasal directory
632     SGPath p(globals->get_fg_root());
633     p.append("Nasal");
634     ulDirEnt* dent;
635     ulDir* dir = ulOpenDir(p.c_str());
636     while(dir && (dent = ulReadDir(dir)) != 0) {
637         SGPath fullpath(p);
638         fullpath.append(dent->d_name);
639         SGPath file(dent->d_name);
640         if(file.extension() != "nas") continue;
641         loadModule(fullpath, file.base().c_str());
642     }
643     ulCloseDir(dir);
644
645     // set signal and remove node to avoid restoring at reinit
646     const char *s = "nasal-dir-initialized";
647     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
648     signal->setBoolValue(s, true);
649     signal->removeChildren(s);
650
651     // Pull scripts out of the property tree, too
652     loadPropertyScripts();
653 }
654
655 void FGNasalSys::update(double)
656 {
657     if(_purgeListeners) {
658         _purgeListeners = false;
659         map<int, FGNasalListener *>::iterator it;
660         for(it = _listener.begin(); it != _listener.end();) {
661             FGNasalListener *nl = it->second;
662             if(nl->_dead) {
663                 _listener.erase(it++);
664                 delete nl;
665             } else {
666                 ++it;
667             }
668         }
669     }
670 }
671
672 // Loads the scripts found under /nasal in the global tree
673 void FGNasalSys::loadPropertyScripts()
674 {
675     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
676     if(!nasal) return;
677
678     for(int i=0; i<nasal->nChildren(); i++) {
679         SGPropertyNode* n = nasal->getChild(i);
680
681         const char* module = n->getName();
682         if(n->hasChild("module"))
683             module = n->getStringValue("module");
684
685         // allow multiple files to be specified within in a single
686         // Nasal module tag
687         int j = 0;
688         SGPropertyNode *fn;
689         bool file_specified = false;
690         while ( (fn = n->getChild("file", j)) != NULL ) {
691             file_specified = true;
692             const char* file = fn->getStringValue();
693             SGPath p(globals->get_fg_root());
694             p.append(file);
695             loadModule(p, module);
696             j++;
697         }
698
699         // Old code which only allowed a single file to be specified per module
700         /*
701         const char* file = n->getStringValue("file");
702         if(!n->hasChild("file")) file = 0; // Hrm...
703         if(file) {
704             SGPath p(globals->get_fg_root());
705             p.append(file);
706             loadModule(p, module);
707         }
708         */
709
710         const char* src = n->getStringValue("script");
711         if(!n->hasChild("script")) src = 0; // Hrm...
712         if(src)
713             createModule(module, n->getPath(), src, strlen(src));
714
715         if(!file_specified && !src)
716             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
717                    "no <file> or <script> defined in " <<
718                    "/nasal/" << module);
719     }
720 }
721
722 // Logs a runtime error, with stack trace, to the FlightGear log stream
723 void FGNasalSys::logError(naContext context)
724 {
725     SG_LOG(SG_NASAL, SG_ALERT,
726            "Nasal runtime error: " << naGetError(context));
727     SG_LOG(SG_NASAL, SG_ALERT,
728            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
729            ", line " << naGetLine(context, 0));
730     for(int i=1; i<naStackDepth(context); i++)
731         SG_LOG(SG_NASAL, SG_ALERT,
732                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
733                ", line " << naGetLine(context, i));
734 }
735
736 // Reads a script file, executes it, and places the resulting
737 // namespace into the global namespace under the specified module
738 // name.
739 void FGNasalSys::loadModule(SGPath file, const char* module)
740 {
741     int len = 0;
742     char* buf = readfile(file.c_str(), &len);
743     if(!buf) {
744         SG_LOG(SG_NASAL, SG_ALERT,
745                "Nasal error: could not read script file " << file.c_str()
746                << " into module " << module);
747         return;
748     }
749
750     createModule(module, file.c_str(), buf, len);
751     delete[] buf;
752 }
753
754 // Parse and run.  Save the local variables namespace, as it will
755 // become a sub-object of globals.  The optional "arg" argument can be
756 // used to pass an associated property node to the module, which can then
757 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
758 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
759                               const char* src, int len, const SGPropertyNode* arg)
760 {
761     naRef code = parse(fileName, src, len);
762     if(naIsNil(code))
763         return;
764
765     // See if we already have a module hash to use.  This allows the
766     // user to, for example, add functions to the built-in math
767     // module.  Make a new one if necessary.
768     naRef locals;
769     naRef modname = naNewString(_context);
770     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
771     if(!naHash_get(_globals, modname, &locals))
772         locals = naNewHash(_context);
773
774     _cmdArg = (SGPropertyNode*)arg;
775
776     call(code, locals);
777     hashset(_globals, moduleName, locals);
778 }
779
780 void FGNasalSys::deleteModule(const char* moduleName)
781 {
782     naRef modname = naNewString(_context);
783     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
784     naHash_delete(_globals, modname);
785 }
786
787 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
788 {
789     int errLine = -1;
790     naRef srcfile = naNewString(_context);
791     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
792     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
793     if(naIsNil(code)) {
794         SG_LOG(SG_NASAL, SG_ALERT,
795                "Nasal parse error: " << naGetError(_context) <<
796                " in "<< filename <<", line " << errLine);
797         return naNil();
798     }
799
800     // Bind to the global namespace before returning
801     return naBindFunction(_context, code, _globals);
802 }
803
804 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
805 {
806     const char* nasal = arg->getStringValue("script");
807     const char* moduleName = arg->getStringValue("module");
808     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
809     if(naIsNil(code)) return false;
810
811     // Commands can be run "in" a module.  Make sure that module
812     // exists, and set it up as the local variables hash for the
813     // command.
814     naRef locals = naNil();
815     if(moduleName[0]) {
816         naRef modname = naNewString(_context);
817         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
818         if(!naHash_get(_globals, modname, &locals)) {
819             locals = naNewHash(_context);
820             naHash_set(_globals, modname, locals);
821         }
822     }
823
824     // Cache this command's argument for inspection via cmdarg().  For
825     // performance reasons, we won't bother with it if the invoked
826     // code doesn't need it.
827     _cmdArg = (SGPropertyNode*)arg;
828
829     call(code, locals);
830     return true;
831 }
832
833 // settimer(func, dt, simtime) extension function.  The first argument
834 // is a Nasal function to call, the second is a delta time (from now),
835 // in seconds.  The third, if present, is a boolean value indicating
836 // that "real world" time (rather than simulator time) is to be used.
837 //
838 // Implementation note: the FGTimer objects don't live inside the
839 // garbage collector, so the Nasal handler functions have to be
840 // "saved" somehow lest they be inadvertently cleaned.  In this case,
841 // they are inserted into a globals.__gcsave hash and removed on
842 // expiration.
843 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
844 {
845     // Extract the handler, delta, and simtime arguments:
846     naRef handler = argc > 0 ? args[0] : naNil();
847     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
848         naRuntimeError(c, "settimer() with invalid function argument");
849         return;
850     }
851
852     naRef delta = argc > 1 ? args[1] : naNil();
853     if(naIsNil(delta)) {
854         naRuntimeError(c, "settimer() with invalid time argument");
855         return;
856     }
857
858     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
859
860     // Generate and register a C++ timer handler
861     NasalTimer* t = new NasalTimer;
862     t->handler = handler;
863     t->gcKey = gcSave(handler);
864     t->nasal = this;
865
866     globals->get_event_mgr()->addEvent("NasalTimer",
867                                        t, &NasalTimer::timerExpired,
868                                        delta.num, simtime);
869 }
870
871 void FGNasalSys::handleTimer(NasalTimer* t)
872 {
873     call(t->handler, naNil());
874     gcRelease(t->gcKey);
875 }
876
877 int FGNasalSys::gcSave(naRef r)
878 {
879     int key = _nextGCKey++;
880     naHash_set(_gcHash, naNum(key), r);
881     return key;
882 }
883
884 void FGNasalSys::gcRelease(int key)
885 {
886     naHash_delete(_gcHash, naNum(key));
887 }
888
889 void FGNasalSys::NasalTimer::timerExpired()
890 {
891     nasal->handleTimer(this);
892     delete this;
893 }
894
895 int FGNasalSys::_listenerId = 0;
896
897 // setlistener(property, func, bool) extension function.  The first argument
898 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
899 // path), the second is a Nasal function, the optional third one a bool.
900 // If the bool is true, then the listener is executed initially. The
901 // setlistener() function returns a unique id number, that can be used
902 // as argument to the removelistener() function.
903 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
904 {
905     SGPropertyNode_ptr node;
906     naRef prop = argc > 0 ? args[0] : naNil();
907     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
908     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
909     else {
910         naRuntimeError(c, "setlistener() with invalid property argument");
911         return naNil();
912     }
913
914     if(node->isTied())
915         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
916                 node->getPath());
917
918     naRef handler = argc > 1 ? args[1] : naNil();
919     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
920         naRuntimeError(c, "setlistener() with invalid function argument");
921         return naNil();
922     }
923
924     bool initial = argc > 2 && naTrue(args[2]);
925
926     FGNasalListener *nl = new FGNasalListener(node, handler, this,
927             gcSave(handler), _listenerId);
928     node->addChangeListener(nl, initial);
929
930     _listener[_listenerId] = nl;
931     return naNum(_listenerId++);
932 }
933
934 // removelistener(int) extension function. The argument is the id of
935 // a listener as returned by the setlistener() function.
936 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
937 {
938     naRef id = argc > 0 ? args[0] : naNil();
939     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
940
941     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
942         naRuntimeError(c, "removelistener() with invalid listener id");
943         return naNil();
944     }
945
946     FGNasalListener *nl = it->second;
947     if(nl->_active) {
948         nl->_dead = true;
949         _purgeListeners = true;
950         return naNum(-1);
951     }
952
953     _listener.erase(it);
954     delete nl;
955     return naNum(_listener.size());
956 }
957
958
959
960 // FGNasalListener class.
961
962 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
963                                  FGNasalSys* nasal, int key, int id) :
964     _node(node),
965     _handler(handler),
966     _gcKey(key),
967     _id(id),
968     _nas(nasal),
969     _active(0),
970     _dead(false)
971 {
972 }
973
974 FGNasalListener::~FGNasalListener()
975 {
976     _node->removeChangeListener(this);
977     _nas->gcRelease(_gcKey);
978 }
979
980 void FGNasalListener::valueChanged(SGPropertyNode* node)
981 {
982     // drop recursive listener calls
983     if(_active || _dead)
984         return;
985
986     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
987     _active++;
988     _nas->_cmdArg = node;
989     _nas->call(_handler, naNil());
990     _active--;
991 }
992
993
994
995
996 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
997 // such a class, then it lets modelLoaded() run the <load> script, and the
998 // destructor the <unload> script. The latter happens when the model branch
999 // is removed from the scene graph.
1000
1001 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1002                                    osg::Node *)
1003 {
1004     SGPropertyNode *n = prop->getNode("nasal"), *load;
1005     if(!n)
1006         return;
1007
1008     load = n->getNode("load");
1009     _unload = n->getNode("unload");
1010     if(!load && !_unload)
1011         return;
1012
1013     _module = path;
1014     if(_props)
1015         _module += ':' + _props->getPath();
1016     const char *s = load ? load->getStringValue() : "";
1017     nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1018 }
1019
1020 FGNasalModelData::~FGNasalModelData()
1021 {
1022     if(_module.empty())
1023         return;
1024
1025     if(!nasalSys) {
1026         SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1027                 "without Nasal subsystem present.");
1028         return;
1029     }
1030
1031     if(_unload) {
1032         const char *s = _unload->getStringValue();
1033         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1034     }
1035     nasalSys->deleteModule(_module.c_str());
1036 }
1037
1038
1039
1040 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1041 //
1042 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1043     _c(naSubContext(c)),
1044     _start_element(argc > 1 ? args[1] : naNil()),
1045     _end_element(argc > 2 ? args[2] : naNil()),
1046     _data(argc > 3 ? args[3] : naNil()),
1047     _pi(argc > 4 ? args[4] : naNil())
1048 {
1049 }
1050
1051 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1052 {
1053     if(naIsNil(_start_element)) return;
1054     naRef attr = naNewHash(_c);
1055     for(int i=0; i<a.size(); i++) {
1056         naRef name = make_string(a.getName(i));
1057         naRef value = make_string(a.getValue(i));
1058         naHash_set(attr, name, value);
1059     }
1060     call(_start_element, 2, make_string(tag), attr);
1061 }
1062
1063 void NasalXMLVisitor::endElement(const char* tag)
1064 {
1065     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1066 }
1067
1068 void NasalXMLVisitor::data(const char* str, int len)
1069 {
1070     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1071 }
1072
1073 void NasalXMLVisitor::pi(const char* target, const char* data)
1074 {
1075     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1076 }
1077
1078 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1079 {
1080     naRef args[2];
1081     args[0] = a;
1082     args[1] = b;
1083     naCall(_c, func, num, args, naNil(), naNil());
1084     if(naGetError(_c))
1085         naRethrowError(_c);
1086 }
1087
1088 naRef NasalXMLVisitor::make_string(const char* s, int n)
1089 {
1090     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1091                           n < 0 ? strlen(s) : n);
1092 }
1093
1094