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