]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
use airport search filter to only search for "regular" airports (no
[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
487 class airport_filter : public FGAirportSearchFilter {
488     virtual bool acceptable(FGAirport *a) { return a->isAirport(); }
489 } airport;
490
491 // Returns airport data for given airport id ("KSFO"), or for the airport
492 // nearest to a given lat/lon pair, or without arguments, to the current
493 // aircraft position. Returns nil on error. Only one side of each runway is
494 // returned.
495 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
496 {
497     static SGConstPropertyNode_ptr lat = fgGetNode("/position/latitude-deg", true);
498     static SGConstPropertyNode_ptr lon = fgGetNode("/position/longitude-deg", true);
499
500     // airport
501     FGAirportList *aptlst = globals->get_airports();
502     FGAirport *apt;
503     if(argc == 0)
504         apt = aptlst->search(lon->getDoubleValue(), lat->getDoubleValue(), airport);
505     else if(argc == 1 && naIsString(args[0]))
506         apt = aptlst->search(naStr_data(args[0]));
507     else if(argc == 2 && naIsNum(args[0]) && naIsNum(args[1]))
508         apt = aptlst->search(args[1].num, args[0].num, airport);
509     else {
510         naRuntimeError(c, "airportinfo() with invalid function arguments");
511         return naNil();
512     }
513     if(!apt) {
514         naRuntimeError(c, "airportinfo(): no airport found");
515         return naNil();
516     }
517
518     string id = apt->getId();
519     string name = apt->getName();
520
521     // set runway hash
522     FGRunwayList *rwylst = globals->get_runways();
523     FGRunway rwy;
524     naRef rwys = naNewHash(c);
525     if(rwylst->search(id, &rwy)) {
526         do {
527             if(rwy._id != id) break;
528             if(rwy._type[0] != 'r') continue;
529
530             naRef rwydata = naNewHash(c);
531 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
532             HASHSET("lat", 3, naNum(rwy._lat));
533             HASHSET("lon", 3, naNum(rwy._lon));
534             HASHSET("heading", 7, naNum(rwy._heading));
535             HASHSET("length", 6, naNum(rwy._length * SG_FEET_TO_METER));
536             HASHSET("width", 5, naNum(rwy._width * SG_FEET_TO_METER));
537             HASHSET("threshold1", 10, naNum(rwy._displ_thresh1 * SG_FEET_TO_METER));
538             HASHSET("threshold2", 10, naNum(rwy._displ_thresh2 * SG_FEET_TO_METER));
539             HASHSET("stopway1", 8, naNum(rwy._stopway1 * SG_FEET_TO_METER));
540             HASHSET("stopway2", 8, naNum(rwy._stopway2 * SG_FEET_TO_METER));
541 #undef HASHSET
542
543             naRef no = naStr_fromdata(naNewString(c),
544                     const_cast<char *>(rwy._rwy_no.c_str()),
545                     rwy._rwy_no.length());
546             naHash_set(rwys, no, rwydata);
547         } while(rwylst->next(&rwy));
548     }
549
550     // set airport hash
551     naRef aptdata = naNewHash(c);
552 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
553     HASHSET("id", 2, naStr_fromdata(naNewString(c),
554             const_cast<char *>(id.c_str()), id.length()));
555     HASHSET("name", 4, naStr_fromdata(naNewString(c),
556             const_cast<char *>(name.c_str()), name.length()));
557     HASHSET("lat", 3, naNum(apt->getLatitude()));
558     HASHSET("lon", 3, naNum(apt->getLongitude()));
559     HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
560     HASHSET("has_metar", 9, naNum(apt->getMetar()));
561     HASHSET("runways", 7, rwys);
562 #undef HASHSET
563     return aptdata;
564 }
565
566
567 // Table of extension functions.  Terminate with zeros.
568 static struct { char* name; naCFunction func; } funcs[] = {
569     { "getprop",   f_getprop },
570     { "setprop",   f_setprop },
571     { "print",     f_print },
572     { "_fgcommand", f_fgcommand },
573     { "settimer",  f_settimer },
574     { "_setlistener", f_setlistener },
575     { "removelistener", f_removelistener },
576     { "_cmdarg",  f_cmdarg },
577     { "_interpolate",  f_interpolate },
578     { "rand",  f_rand },
579     { "srand",  f_srand },
580     { "directory", f_directory },
581     { "parsexml", f_parsexml },
582     { "systime", f_systime },
583     { "carttogeod", f_carttogeod },
584     { "geodtocart", f_geodtocart },
585     { "geodinfo", f_geodinfo },
586     { "airportinfo", f_airportinfo },
587     { 0, 0 }
588 };
589
590 naRef FGNasalSys::cmdArgGhost()
591 {
592     return propNodeGhost(_cmdArg);
593 }
594
595 void FGNasalSys::init()
596 {
597     int i;
598
599     _context = naNewContext();
600
601     // Start with globals.  Add it to itself as a recursive
602     // sub-reference under the name "globals".  This gives client-code
603     // write access to the namespace if someone wants to do something
604     // fancy.
605     _globals = naInit_std(_context);
606     naSave(_context, _globals);
607     hashset(_globals, "globals", _globals);
608
609     hashset(_globals, "math", naInit_math(_context));
610     hashset(_globals, "bits", naInit_bits(_context));
611     hashset(_globals, "io", naInit_io(_context));
612     hashset(_globals, "thread", naInit_thread(_context));
613     hashset(_globals, "utf8", naInit_utf8(_context));
614
615     // Add our custom extension functions:
616     for(i=0; funcs[i].name; i++)
617         hashset(_globals, funcs[i].name,
618                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
619
620     // And our SGPropertyNode wrapper
621     hashset(_globals, "props", genPropsModule());
622
623     // Make a "__gcsave" hash to hold the naRef objects which get
624     // passed to handles outside the interpreter (to protect them from
625     // begin garbage-collected).
626     _gcHash = naNewHash(_context);
627     hashset(_globals, "__gcsave", _gcHash);
628
629     // Now load the various source files in the Nasal directory
630     SGPath p(globals->get_fg_root());
631     p.append("Nasal");
632     ulDirEnt* dent;
633     ulDir* dir = ulOpenDir(p.c_str());
634     while(dir && (dent = ulReadDir(dir)) != 0) {
635         SGPath fullpath(p);
636         fullpath.append(dent->d_name);
637         SGPath file(dent->d_name);
638         if(file.extension() != "nas") continue;
639         loadModule(fullpath, file.base().c_str());
640     }
641     ulCloseDir(dir);
642
643     // set signal and remove node to avoid restoring at reinit
644     const char *s = "nasal-dir-initialized";
645     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
646     signal->setBoolValue(s, true);
647     signal->removeChildren(s);
648
649     // Pull scripts out of the property tree, too
650     loadPropertyScripts();
651 }
652
653 void FGNasalSys::update(double)
654 {
655     if(_purgeListeners) {
656         _purgeListeners = false;
657         map<int, FGNasalListener *>::iterator it;
658         for(it = _listener.begin(); it != _listener.end();) {
659             FGNasalListener *nl = it->second;
660             if(nl->_dead) {
661                 _listener.erase(it++);
662                 delete nl;
663             } else {
664                 ++it;
665             }
666         }
667     }
668 }
669
670 // Loads the scripts found under /nasal in the global tree
671 void FGNasalSys::loadPropertyScripts()
672 {
673     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
674     if(!nasal) return;
675
676     for(int i=0; i<nasal->nChildren(); i++) {
677         SGPropertyNode* n = nasal->getChild(i);
678
679         const char* module = n->getName();
680         if(n->hasChild("module"))
681             module = n->getStringValue("module");
682
683         // allow multiple files to be specified within in a single
684         // Nasal module tag
685         int j = 0;
686         SGPropertyNode *fn;
687         bool file_specified = false;
688         while ( (fn = n->getChild("file", j)) != NULL ) {
689             file_specified = true;
690             const char* file = fn->getStringValue();
691             SGPath p(globals->get_fg_root());
692             p.append(file);
693             loadModule(p, module);
694             j++;
695         }
696
697         // Old code which only allowed a single file to be specified per module
698         /*
699         const char* file = n->getStringValue("file");
700         if(!n->hasChild("file")) file = 0; // Hrm...
701         if(file) {
702             SGPath p(globals->get_fg_root());
703             p.append(file);
704             loadModule(p, module);
705         }
706         */
707
708         const char* src = n->getStringValue("script");
709         if(!n->hasChild("script")) src = 0; // Hrm...
710         if(src)
711             createModule(module, n->getPath(), src, strlen(src));
712
713         if(!file_specified && !src)
714             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
715                    "no <file> or <script> defined in " <<
716                    "/nasal/" << module);
717     }
718 }
719
720 // Logs a runtime error, with stack trace, to the FlightGear log stream
721 void FGNasalSys::logError(naContext context)
722 {
723     SG_LOG(SG_NASAL, SG_ALERT,
724            "Nasal runtime error: " << naGetError(context));
725     SG_LOG(SG_NASAL, SG_ALERT,
726            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
727            ", line " << naGetLine(context, 0));
728     for(int i=1; i<naStackDepth(context); i++)
729         SG_LOG(SG_NASAL, SG_ALERT,
730                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
731                ", line " << naGetLine(context, i));
732 }
733
734 // Reads a script file, executes it, and places the resulting
735 // namespace into the global namespace under the specified module
736 // name.
737 void FGNasalSys::loadModule(SGPath file, const char* module)
738 {
739     int len = 0;
740     char* buf = readfile(file.c_str(), &len);
741     if(!buf) {
742         SG_LOG(SG_NASAL, SG_ALERT,
743                "Nasal error: could not read script file " << file.c_str()
744                << " into module " << module);
745         return;
746     }
747
748     createModule(module, file.c_str(), buf, len);
749     delete[] buf;
750 }
751
752 // Parse and run.  Save the local variables namespace, as it will
753 // become a sub-object of globals.  The optional "arg" argument can be
754 // used to pass an associated property node to the module, which can then
755 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
756 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
757                               const char* src, int len, const SGPropertyNode* arg)
758 {
759     naRef code = parse(fileName, src, len);
760     if(naIsNil(code))
761         return;
762
763     // See if we already have a module hash to use.  This allows the
764     // user to, for example, add functions to the built-in math
765     // module.  Make a new one if necessary.
766     naRef locals;
767     naRef modname = naNewString(_context);
768     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
769     if(!naHash_get(_globals, modname, &locals))
770         locals = naNewHash(_context);
771
772     _cmdArg = (SGPropertyNode*)arg;
773
774     call(code, locals);
775     hashset(_globals, moduleName, locals);
776 }
777
778 void FGNasalSys::deleteModule(const char* moduleName)
779 {
780     naRef modname = naNewString(_context);
781     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
782     naHash_delete(_globals, modname);
783 }
784
785 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
786 {
787     int errLine = -1;
788     naRef srcfile = naNewString(_context);
789     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
790     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
791     if(naIsNil(code)) {
792         SG_LOG(SG_NASAL, SG_ALERT,
793                "Nasal parse error: " << naGetError(_context) <<
794                " in "<< filename <<", line " << errLine);
795         return naNil();
796     }
797
798     // Bind to the global namespace before returning
799     return naBindFunction(_context, code, _globals);
800 }
801
802 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
803 {
804     const char* nasal = arg->getStringValue("script");
805     const char* moduleName = arg->getStringValue("module");
806     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
807     if(naIsNil(code)) return false;
808
809     // Commands can be run "in" a module.  Make sure that module
810     // exists, and set it up as the local variables hash for the
811     // command.
812     naRef locals = naNil();
813     if(moduleName[0]) {
814         naRef modname = naNewString(_context);
815         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
816         if(!naHash_get(_globals, modname, &locals)) {
817             locals = naNewHash(_context);
818             naHash_set(_globals, modname, locals);
819         }
820     }
821
822     // Cache this command's argument for inspection via cmdarg().  For
823     // performance reasons, we won't bother with it if the invoked
824     // code doesn't need it.
825     _cmdArg = (SGPropertyNode*)arg;
826
827     call(code, locals);
828     return true;
829 }
830
831 // settimer(func, dt, simtime) extension function.  The first argument
832 // is a Nasal function to call, the second is a delta time (from now),
833 // in seconds.  The third, if present, is a boolean value indicating
834 // that "real world" time (rather than simulator time) is to be used.
835 //
836 // Implementation note: the FGTimer objects don't live inside the
837 // garbage collector, so the Nasal handler functions have to be
838 // "saved" somehow lest they be inadvertently cleaned.  In this case,
839 // they are inserted into a globals.__gcsave hash and removed on
840 // expiration.
841 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
842 {
843     // Extract the handler, delta, and simtime arguments:
844     naRef handler = argc > 0 ? args[0] : naNil();
845     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
846         naRuntimeError(c, "settimer() with invalid function argument");
847         return;
848     }
849
850     naRef delta = argc > 1 ? args[1] : naNil();
851     if(naIsNil(delta)) {
852         naRuntimeError(c, "settimer() with invalid time argument");
853         return;
854     }
855
856     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
857
858     // Generate and register a C++ timer handler
859     NasalTimer* t = new NasalTimer;
860     t->handler = handler;
861     t->gcKey = gcSave(handler);
862     t->nasal = this;
863
864     globals->get_event_mgr()->addEvent("NasalTimer",
865                                        t, &NasalTimer::timerExpired,
866                                        delta.num, simtime);
867 }
868
869 void FGNasalSys::handleTimer(NasalTimer* t)
870 {
871     call(t->handler, naNil());
872     gcRelease(t->gcKey);
873 }
874
875 int FGNasalSys::gcSave(naRef r)
876 {
877     int key = _nextGCKey++;
878     naHash_set(_gcHash, naNum(key), r);
879     return key;
880 }
881
882 void FGNasalSys::gcRelease(int key)
883 {
884     naHash_delete(_gcHash, naNum(key));
885 }
886
887 void FGNasalSys::NasalTimer::timerExpired()
888 {
889     nasal->handleTimer(this);
890     delete this;
891 }
892
893 int FGNasalSys::_listenerId = 0;
894
895 // setlistener(property, func, bool) extension function.  The first argument
896 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
897 // path), the second is a Nasal function, the optional third one a bool.
898 // If the bool is true, then the listener is executed initially. The
899 // setlistener() function returns a unique id number, that can be used
900 // as argument to the removelistener() function.
901 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
902 {
903     SGPropertyNode_ptr node;
904     naRef prop = argc > 0 ? args[0] : naNil();
905     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
906     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
907     else {
908         naRuntimeError(c, "setlistener() with invalid property argument");
909         return naNil();
910     }
911
912     if(node->isTied())
913         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
914                 node->getPath());
915
916     naRef handler = argc > 1 ? args[1] : naNil();
917     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
918         naRuntimeError(c, "setlistener() with invalid function argument");
919         return naNil();
920     }
921
922     bool initial = argc > 2 && naTrue(args[2]);
923
924     FGNasalListener *nl = new FGNasalListener(node, handler, this,
925             gcSave(handler), _listenerId);
926     node->addChangeListener(nl, initial);
927
928     _listener[_listenerId] = nl;
929     return naNum(_listenerId++);
930 }
931
932 // removelistener(int) extension function. The argument is the id of
933 // a listener as returned by the setlistener() function.
934 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
935 {
936     naRef id = argc > 0 ? args[0] : naNil();
937     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
938
939     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
940         naRuntimeError(c, "removelistener() with invalid listener id");
941         return naNil();
942     }
943
944     FGNasalListener *nl = it->second;
945     if(nl->_active) {
946         nl->_dead = true;
947         _purgeListeners = true;
948         return naNum(-1);
949     }
950
951     _listener.erase(it);
952     delete nl;
953     return naNum(_listener.size());
954 }
955
956
957
958 // FGNasalListener class.
959
960 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
961                                  FGNasalSys* nasal, int key, int id) :
962     _node(node),
963     _handler(handler),
964     _gcKey(key),
965     _id(id),
966     _nas(nasal),
967     _active(0),
968     _dead(false)
969 {
970 }
971
972 FGNasalListener::~FGNasalListener()
973 {
974     _node->removeChangeListener(this);
975     _nas->gcRelease(_gcKey);
976 }
977
978 void FGNasalListener::valueChanged(SGPropertyNode* node)
979 {
980     // drop recursive listener calls
981     if(_active || _dead)
982         return;
983
984     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
985     _active++;
986     _nas->_cmdArg = node;
987     _nas->call(_handler, naNil());
988     _active--;
989 }
990
991
992
993
994 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
995 // such a class, then it lets modelLoaded() run the <load> script, and the
996 // destructor the <unload> script. The latter happens when the model branch
997 // is removed from the scene graph.
998
999 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1000                                    osg::Node *)
1001 {
1002     SGPropertyNode *n = prop->getNode("nasal"), *load;
1003     if(!n)
1004         return;
1005
1006     load = n->getNode("load");
1007     _unload = n->getNode("unload");
1008     if(!load && !_unload)
1009         return;
1010
1011     _module = path;
1012     if(_props)
1013         _module += ':' + _props->getPath();
1014     const char *s = load ? load->getStringValue() : "";
1015     nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1016 }
1017
1018 FGNasalModelData::~FGNasalModelData()
1019 {
1020     if(_module.empty())
1021         return;
1022
1023     if(!nasalSys) {
1024         SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1025                 "without Nasal subsystem present.");
1026         return;
1027     }
1028
1029     if(_unload) {
1030         const char *s = _unload->getStringValue();
1031         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
1032     }
1033     nasalSys->deleteModule(_module.c_str());
1034 }
1035
1036
1037
1038 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1039 //
1040 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1041     _c(naSubContext(c)),
1042     _start_element(argc > 1 ? args[1] : naNil()),
1043     _end_element(argc > 2 ? args[2] : naNil()),
1044     _data(argc > 3 ? args[3] : naNil()),
1045     _pi(argc > 4 ? args[4] : naNil())
1046 {
1047 }
1048
1049 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1050 {
1051     if(naIsNil(_start_element)) return;
1052     naRef attr = naNewHash(_c);
1053     for(int i=0; i<a.size(); i++) {
1054         naRef name = make_string(a.getName(i));
1055         naRef value = make_string(a.getValue(i));
1056         naHash_set(attr, name, value);
1057     }
1058     call(_start_element, 2, make_string(tag), attr);
1059 }
1060
1061 void NasalXMLVisitor::endElement(const char* tag)
1062 {
1063     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1064 }
1065
1066 void NasalXMLVisitor::data(const char* str, int len)
1067 {
1068     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1069 }
1070
1071 void NasalXMLVisitor::pi(const char* target, const char* data)
1072 {
1073     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1074 }
1075
1076 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1077 {
1078     naRef args[2];
1079     args[0] = a;
1080     args[1] = b;
1081     naCall(_c, func, num, args, naNil(), naNil());
1082     if(naGetError(_c))
1083         naRethrowError(_c);
1084 }
1085
1086 naRef NasalXMLVisitor::make_string(const char* s, int n)
1087 {
1088     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1089                           n < 0 ? strlen(s) : n);
1090 }
1091
1092