]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
a41179366142f0afd823fa66d556db536c4b5afd
[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 #include <simgear/structure/event_mgr.hxx>
27
28 #include <Airports/runways.hxx>
29 #include <Airports/simple.hxx>
30 #include <Main/globals.hxx>
31 #include <Main/fg_props.hxx>
32 #include <Main/util.hxx>
33 #include <Scenery/scenery.hxx>
34
35 #include "NasalSys.hxx"
36
37 static FGNasalSys* nasalSys = 0;
38
39
40 // Read and return file contents in a single buffer.  Note use of
41 // stat() to get the file size.  This is a win32 function, believe it
42 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
43 // Text mode brain damage will kill us if we're trying to do bytewise
44 // I/O.
45 static char* readfile(const char* file, int* lenOut)
46 {
47     struct stat data;
48     if(stat(file, &data) != 0) return 0;
49     FILE* f = fopen(file, "rb");
50     if(!f) return 0;
51     char* buf = new char[data.st_size];
52     *lenOut = fread(buf, 1, data.st_size, f);
53     fclose(f);
54     if(*lenOut != data.st_size) {
55         // Shouldn't happen, but warn anyway since it represents a
56         // platform bug and not a typical runtime error (missing file,
57         // etc...)
58         SG_LOG(SG_NASAL, SG_ALERT,
59                "ERROR in Nasal initialization: " <<
60                "short count returned from fread() of " << file <<
61                ".  Check your C library!");
62         delete[] buf;
63         return 0;
64     }
65     return buf;
66 }
67
68 FGNasalSys::FGNasalSys()
69 {
70     nasalSys = this;
71     _context = 0;
72     _globals = naNil();
73     _gcHash = naNil();
74     _nextGCKey = 0; // Any value will do
75     _callCount = 0;
76 }
77
78 // Does a naCall() in a new context.  Wrapped here to make lock
79 // tracking easier.  Extension functions are called with the lock, but
80 // we have to release it before making a new naCall().  So rather than
81 // drop the lock in every extension function that might call back into
82 // Nasal, we keep a stack depth counter here and only unlock/lock
83 // around the naCall if it isn't the first one.
84 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
85 {
86     naContext ctx = naNewContext();
87     if(_callCount) naModUnlock();
88     _callCount++;
89     naRef result = naCall(ctx, code, argc, args, naNil(), locals);
90     if(naGetError(ctx))
91         logError(ctx);
92     _callCount--;
93     if(_callCount) naModLock();
94     naFreeContext(ctx);
95     return result;
96 }
97
98 FGNasalSys::~FGNasalSys()
99 {
100     nasalSys = 0;
101     map<int, FGNasalListener *>::iterator it, end = _listener.end();
102     for(it = _listener.begin(); it != end; ++it)
103         delete it->second;
104
105     naFreeContext(_context);
106     _globals = naNil();
107 }
108
109 bool FGNasalSys::parseAndRun(const char* sourceCode)
110 {
111     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
112                        strlen(sourceCode));
113     if(naIsNil(code))
114         return false;
115     call(code, 0, 0, naNil());
116     return true;
117 }
118
119 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
120 {
121     FGNasalScript* script = new FGNasalScript();
122     script->_gcKey = -1; // important, if we delete it on a parse
123     script->_nas = this; // error, don't clobber a real handle!
124
125     char buf[256];
126     if(!name) {
127         sprintf(buf, "FGNasalScript@%p", (void *)script);
128         name = buf;
129     }
130
131     script->_code = parse(name, src, strlen(src));
132     if(naIsNil(script->_code)) {
133         delete script;
134         return 0;
135     }
136
137     script->_gcKey = gcSave(script->_code);
138     return script;
139 }
140
141 // Utility.  Sets a named key in a hash by C string, rather than nasal
142 // string object.
143 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
144 {
145     naRef s = naNewString(_context);
146     naStr_fromdata(s, (char*)key, strlen(key));
147     naHash_set(hash, s, val);
148 }
149
150 // The get/setprop functions accept a *list* of strings and walk
151 // through the property tree with them to find the appropriate node.
152 // This allows a Nasal object to hold onto a property path and use it
153 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
154 // is the utility function that walks the property tree.
155 // Future enhancement: support integer arguments to specify array
156 // elements.
157 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
158 {
159     SGPropertyNode* p = globals->get_props();
160     try {
161         for(int i=0; i<len; i++) {
162             naRef a = vec[i];
163             if(!naIsString(a)) return 0;
164             p = p->getNode(naStr_data(a));
165             if(p == 0) return 0;
166         }
167     } catch (const string& err) {
168         naRuntimeError(c, (char *)err.c_str());
169         return 0;
170     }
171     return p;
172 }
173
174 // getprop() extension function.  Concatenates its string arguments as
175 // property names and returns the value of the specified property.  Or
176 // nil if it doesn't exist.
177 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
178 {
179     const SGPropertyNode* p = findnode(c, args, argc);
180     if(!p) return naNil();
181
182     switch(p->getType()) {
183     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
184     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
185     case SGPropertyNode::DOUBLE:
186         return naNum(p->getDoubleValue());
187
188     case SGPropertyNode::STRING:
189     case SGPropertyNode::UNSPECIFIED:
190         {
191             naRef nastr = naNewString(c);
192             const char* val = p->getStringValue();
193             naStr_fromdata(nastr, (char*)val, strlen(val));
194             return nastr;
195         }
196     case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
197     default:
198         return naNil();
199     }
200 }
201
202 // setprop() extension function.  Concatenates its string arguments as
203 // property names and sets the value of the specified property to the
204 // final argument.
205 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
206 {
207 #define BUFLEN 1024
208     char buf[BUFLEN + 1];
209     buf[BUFLEN] = 0;
210     char* p = buf;
211     int buflen = BUFLEN;
212     for(int i=0; i<argc-1; i++) {
213         naRef s = naStringValue(c, args[i]);
214         if(naIsNil(s)) return naNil();
215         strncpy(p, naStr_data(s), buflen);
216         p += naStr_len(s);
217         buflen = BUFLEN - (p - buf);
218         if(i < (argc-2) && buflen > 0) {
219             *p++ = '/';
220             buflen--;
221         }
222     }
223
224     SGPropertyNode* props = globals->get_props();
225     naRef val = args[argc-1];
226     bool result = false;
227     try {
228         if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
229         else {
230             naRef n = naNumValue(val);
231             if(naIsNil(n))
232                 naRuntimeError(c, "setprop() value is not string or number");
233             result = props->setDoubleValue(buf, n.num);
234         }
235     } catch (const string& err) {
236         naRuntimeError(c, (char *)err.c_str());
237     }
238     return naNum(result);
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     delete[] values;
333     delete[] deltas;
334     return naNil();
335 }
336
337 // This is a better RNG than the one in the default Nasal distribution
338 // (which is based on the C library rand() implementation). It will
339 // override.
340 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
341 {
342     return naNum(sg_random());
343 }
344
345 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
346 {
347     sg_srandom_time();
348     return naNum(0);
349 }
350
351 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
352 {
353     abort();
354     return naNil();
355 }
356
357 // Return an array listing of all files in a directory
358 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
359 {
360     if(argc != 1 || !naIsString(args[0]))
361         naRuntimeError(c, "bad arguments to directory()");
362     naRef ldir = args[0];
363     ulDir* dir = ulOpenDir(naStr_data(args[0]));
364     if(!dir) return naNil();
365     naRef result = naNewVector(c);
366     ulDirEnt* dent;
367     while((dent = ulReadDir(dir)))
368         naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
369                                             strlen(dent->d_name)));
370     ulCloseDir(dir);
371     return result;
372 }
373
374 // Parse XML file.
375 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
376 //
377 // <path>      ... absolute path to an XML file
378 // <start-tag> ... callback function with two args: tag name, attribute hash
379 // <end-tag>   ... callback function with one arg:  tag name
380 // <data>      ... callback function with one arg:  data
381 // <pi>        ... callback function with two args: target, data
382 //                 (pi = "processing instruction")
383 // All four callback functions are optional and default to nil.
384 // The function returns nil on error, or the validated file name otherwise.
385 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
386 {
387     if(argc < 1 || !naIsString(args[0]))
388         naRuntimeError(c, "parsexml(): path argument missing or not a string");
389     if(argc > 5) argc = 5;
390     for(int i=1; i<argc; i++)
391         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
392             naRuntimeError(c, "parsexml(): callback argument not a function");
393
394     const char* file = fgValidatePath(naStr_data(args[0]), false);
395     if(!file) {
396         naRuntimeError(c, "parsexml(): reading '%s' denied "
397                 "(unauthorized access)", naStr_data(args[0]));
398         return naNil();
399     }
400     std::ifstream input(file);
401     NasalXMLVisitor visitor(c, argc, args);
402     try {
403         readXML(input, visitor);
404     } catch (const sg_exception& e) {
405         naRuntimeError(c, "parsexml(): file '%s' %s",
406                 file, e.getFormattedMessage().c_str());
407         return naNil();
408     }
409     return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
410 }
411
412 // Return UNIX epoch time in seconds.
413 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
414 {
415 #ifdef WIN32
416     FILETIME ft;
417     GetSystemTimeAsFileTime(&ft);
418     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
419     // Converts from 100ns units in 1601 epoch to unix epoch in sec
420     return naNum((t * 1e-7) - 11644473600.0);
421 #else
422     time_t t;
423     struct timeval td;
424     do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
425     return naNum(t + 1e-6 * td.tv_usec);
426 #endif
427 }
428
429 // Convert a cartesian point to a geodetic lat/lon/altitude.
430 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
431 {
432     double lat, lon, alt, xyz[3];
433     if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
434     for(int i=0; i<3; i++)
435         xyz[i] = naNumValue(args[i]).num;
436     sgCartToGeod(xyz, &lat, &lon, &alt);
437     lat *= SG_RADIANS_TO_DEGREES;
438     lon *= SG_RADIANS_TO_DEGREES;
439     naRef vec = naNewVector(c);
440     naVec_append(vec, naNum(lat));
441     naVec_append(vec, naNum(lon));
442     naVec_append(vec, naNum(alt));
443     return vec;
444 }
445
446 // Convert a geodetic lat/lon/altitude to a cartesian point.
447 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
448 {
449     if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
450     double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
451     double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
452     double alt = naNumValue(args[2]).num;
453     double xyz[3];
454     sgGeodToCart(lat, lon, alt, xyz);
455     naRef vec = naNewVector(c);
456     naVec_append(vec, naNum(xyz[0]));
457     naVec_append(vec, naNum(xyz[1]));
458     naVec_append(vec, naNum(xyz[2]));
459     return vec;
460 }
461
462 // For given geodetic point return array with elevation, and a material data
463 // hash, or nil if there's no information available (tile not loaded). If
464 // information about the material isn't available, then nil is returned instead
465 // of the hash.
466 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
467 {
468 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
469     if(argc < 2 || argc > 3)
470         naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
471     double lat = naNumValue(args[0]).num;
472     double lon = naNumValue(args[1]).num;
473     double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
474     const SGMaterial *mat;
475     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
476     if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
477         return naNil();
478     naRef vec = naNewVector(c);
479     naVec_append(vec, naNum(elev));
480     naRef matdata = naNil();
481     if(mat) {
482         matdata = naNewHash(c);
483         naRef names = naNewVector(c);
484         const vector<string> n = mat->get_names();
485         for(unsigned int i=0; i<n.size(); i++)
486             naVec_append(names, naStr_fromdata(naNewString(c),
487                     const_cast<char*>(n[i].c_str()), n[i].size()));
488         HASHSET("names", 5, names);
489         HASHSET("solid", 5, naNum(mat->get_solid()));
490         HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
491         HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
492         HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
493         HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
494         HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
495     }
496     naVec_append(vec, matdata);
497     return vec;
498 #undef HASHSET
499 }
500
501
502 class AirportInfoFilter : public FGAirport::AirportFilter
503 {
504 public:
505     AirportInfoFilter() : type(FGPositioned::AIRPORT) {
506     }
507
508     virtual FGPositioned::Type minType() const {
509         return type;
510     }
511
512     virtual FGPositioned::Type maxType() const {
513         return type;
514     }
515
516     FGPositioned::Type type;
517 };
518
519 // Returns data hash for particular or nearest airport of a <type>, or nil
520 // on error.
521 //
522 // airportinfo(<id>);                   e.g. "KSFO"
523 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
524 // airportinfo()                        same as  airportinfo("airport")
525 // airportinfo(<lat>, <lon> [, <type>]);
526 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
527 {
528     static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
529     static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
530     SGGeod pos;
531     FGAirport* apt = NULL;
532
533     if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
534         pos = SGGeod::fromDeg(args[1].num, args[0].num);
535         args += 2;
536         argc -= 2;
537     } else {
538         pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
539     }
540
541     double maxRange = 10000.0; // expose this? or pick a smaller value?
542
543     AirportInfoFilter filter; // defaults to airports only
544
545     if(argc == 0) {
546         // fall through and use AIRPORT
547     } else if(argc == 1 && naIsString(args[0])) {
548         const char *s = naStr_data(args[0]);
549         if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
550         else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
551         else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
552         else {
553             // user provided an <id>, hopefully
554             apt = FGAirport::findByIdent(s);
555             if (!apt) {
556                 naRuntimeError(c, "airportinfo() couldn't find airport: %s", s);
557                 return naNil();
558             }
559         }
560     } else {
561         naRuntimeError(c, "airportinfo() with invalid function arguments");
562         return naNil();
563     }
564
565     if(!apt) {
566         apt = FGAirport::findClosest(pos, maxRange, &filter);
567         if(!apt) return naNil();
568     }
569
570     string id = apt->ident();
571     string name = apt->name();
572
573     // set runway hash
574     naRef rwys = naNewHash(c);
575     for(unsigned int r=0; r<apt->numRunways(); ++r) {
576         FGRunway* rwy(apt->getRunwayByIndex(r));
577
578         naRef rwyid = naStr_fromdata(naNewString(c),
579                       const_cast<char *>(rwy->ident().c_str()),
580                       rwy->ident().length());
581
582         naRef rwydata = naNewHash(c);
583 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
584         HASHSET("id", 2, rwyid);
585         HASHSET("lat", 3, naNum(rwy->latitude()));
586         HASHSET("lon", 3, naNum(rwy->longitude()));
587         HASHSET("heading", 7, naNum(rwy->headingDeg()));
588         HASHSET("length", 6, naNum(rwy->lengthM()));
589         HASHSET("width", 5, naNum(rwy->widthM()));
590         HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
591         HASHSET("stopway", 7, naNum(rwy->stopwayM()));
592 #undef HASHSET
593         naHash_set(rwys, rwyid, rwydata);
594     }
595
596     // set airport hash
597     naRef aptdata = naNewHash(c);
598 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
599     HASHSET("id", 2, naStr_fromdata(naNewString(c),
600             const_cast<char *>(id.c_str()), id.length()));
601     HASHSET("name", 4, naStr_fromdata(naNewString(c),
602             const_cast<char *>(name.c_str()), name.length()));
603     HASHSET("lat", 3, naNum(apt->getLatitude()));
604     HASHSET("lon", 3, naNum(apt->getLongitude()));
605     HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
606     HASHSET("has_metar", 9, naNum(apt->getMetar()));
607     HASHSET("runways", 7, rwys);
608 #undef HASHSET
609     return aptdata;
610 }
611
612
613 // Table of extension functions.  Terminate with zeros.
614 static struct { const char* name; naCFunction func; } funcs[] = {
615     { "getprop",   f_getprop },
616     { "setprop",   f_setprop },
617     { "print",     f_print },
618     { "_fgcommand", f_fgcommand },
619     { "settimer",  f_settimer },
620     { "_setlistener", f_setlistener },
621     { "removelistener", f_removelistener },
622     { "_cmdarg",  f_cmdarg },
623     { "_interpolate",  f_interpolate },
624     { "rand",  f_rand },
625     { "srand",  f_srand },
626     { "abort", f_abort },
627     { "directory", f_directory },
628     { "parsexml", f_parsexml },
629     { "systime", f_systime },
630     { "carttogeod", f_carttogeod },
631     { "geodtocart", f_geodtocart },
632     { "geodinfo", f_geodinfo },
633     { "airportinfo", f_airportinfo },
634     { 0, 0 }
635 };
636
637 naRef FGNasalSys::cmdArgGhost()
638 {
639     return propNodeGhost(_cmdArg);
640 }
641
642 void FGNasalSys::init()
643 {
644     int i;
645
646     _context = naNewContext();
647
648     // Start with globals.  Add it to itself as a recursive
649     // sub-reference under the name "globals".  This gives client-code
650     // write access to the namespace if someone wants to do something
651     // fancy.
652     _globals = naInit_std(_context);
653     naSave(_context, _globals);
654     hashset(_globals, "globals", _globals);
655
656     hashset(_globals, "math", naInit_math(_context));
657     hashset(_globals, "bits", naInit_bits(_context));
658     hashset(_globals, "io", naInit_io(_context));
659     hashset(_globals, "thread", naInit_thread(_context));
660     hashset(_globals, "utf8", naInit_utf8(_context));
661
662     // Add our custom extension functions:
663     for(i=0; funcs[i].name; i++)
664         hashset(_globals, funcs[i].name,
665                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
666
667     // And our SGPropertyNode wrapper
668     hashset(_globals, "props", genPropsModule());
669
670     // Make a "__gcsave" hash to hold the naRef objects which get
671     // passed to handles outside the interpreter (to protect them from
672     // begin garbage-collected).
673     _gcHash = naNewHash(_context);
674     hashset(_globals, "__gcsave", _gcHash);
675
676     // Now load the various source files in the Nasal directory
677     SGPath p(globals->get_fg_root());
678     p.append("Nasal");
679     ulDirEnt* dent;
680     ulDir* dir = ulOpenDir(p.c_str());
681     while(dir && (dent = ulReadDir(dir)) != 0) {
682         SGPath fullpath(p);
683         fullpath.append(dent->d_name);
684         SGPath file(dent->d_name);
685         if(file.extension() != "nas") continue;
686         loadModule(fullpath, file.base().c_str());
687     }
688     ulCloseDir(dir);
689
690     // set signal and remove node to avoid restoring at reinit
691     const char *s = "nasal-dir-initialized";
692     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
693     signal->setBoolValue(s, true);
694     signal->removeChildren(s, false);
695
696     // Pull scripts out of the property tree, too
697     loadPropertyScripts();
698 }
699
700 void FGNasalSys::update(double)
701 {
702     if(!_dead_listener.empty()) {
703         vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
704         for(it = _dead_listener.begin(); it != end; ++it) delete *it;
705         _dead_listener.clear();
706     }
707
708     // The global context is a legacy thing.  We use dynamically
709     // created contexts for naCall() now, so that we can call them
710     // recursively.  But there are still spots that want to use it for
711     // naNew*() calls, which end up leaking memory because the context
712     // only clears out its temporary vector when it's *used*.  So just
713     // junk it and fetch a new/reinitialized one every frame.  This is
714     // clumsy: the right solution would use the dynamic context in all
715     // cases and eliminate _context entirely.  But that's more work,
716     // and this works fine (yes, they say "New" and "Free", but
717     // they're very fast, just trust me). -Andy
718     naFreeContext(_context);
719     _context = naNewContext();
720 }
721
722 // Loads the scripts found under /nasal in the global tree
723 void FGNasalSys::loadPropertyScripts()
724 {
725     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
726     if(!nasal) return;
727
728     for(int i=0; i<nasal->nChildren(); i++) {
729         SGPropertyNode* n = nasal->getChild(i);
730
731         const char* module = n->getName();
732         if(n->hasChild("module"))
733             module = n->getStringValue("module");
734
735         // allow multiple files to be specified within a single
736         // Nasal module tag
737         int j = 0;
738         SGPropertyNode *fn;
739         bool file_specified = false;
740         while((fn = n->getChild("file", j)) != NULL) {
741             file_specified = true;
742             const char* file = fn->getStringValue();
743             SGPath p(globals->get_fg_root());
744             p.append(file);
745             loadModule(p, module);
746             j++;
747         }
748
749         const char* src = n->getStringValue("script");
750         if(!n->hasChild("script")) src = 0; // Hrm...
751         if(src)
752             createModule(module, n->getPath(), src, strlen(src));
753
754         if(!file_specified && !src)
755             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
756                    "no <file> or <script> defined in " <<
757                    "/nasal/" << module);
758     }
759 }
760
761 // Logs a runtime error, with stack trace, to the FlightGear log stream
762 void FGNasalSys::logError(naContext context)
763 {
764     SG_LOG(SG_NASAL, SG_ALERT,
765            "Nasal runtime error: " << naGetError(context));
766     SG_LOG(SG_NASAL, SG_ALERT,
767            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
768            ", line " << naGetLine(context, 0));
769     for(int i=1; i<naStackDepth(context); i++)
770         SG_LOG(SG_NASAL, SG_ALERT,
771                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
772                ", line " << naGetLine(context, i));
773 }
774
775 // Reads a script file, executes it, and places the resulting
776 // namespace into the global namespace under the specified module
777 // name.
778 void FGNasalSys::loadModule(SGPath file, const char* module)
779 {
780     int len = 0;
781     char* buf = readfile(file.c_str(), &len);
782     if(!buf) {
783         SG_LOG(SG_NASAL, SG_ALERT,
784                "Nasal error: could not read script file " << file.c_str()
785                << " into module " << module);
786         return;
787     }
788
789     createModule(module, file.c_str(), buf, len);
790     delete[] buf;
791 }
792
793 // Parse and run.  Save the local variables namespace, as it will
794 // become a sub-object of globals.  The optional "arg" argument can be
795 // used to pass an associated property node to the module, which can then
796 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
797 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
798                               const char* src, int len,
799                               const SGPropertyNode* cmdarg,
800                               int argc, naRef* args)
801 {
802     naRef code = parse(fileName, src, len);
803     if(naIsNil(code))
804         return;
805
806     // See if we already have a module hash to use.  This allows the
807     // user to, for example, add functions to the built-in math
808     // module.  Make a new one if necessary.
809     naRef locals;
810     naRef modname = naNewString(_context);
811     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
812     if(!naHash_get(_globals, modname, &locals))
813         locals = naNewHash(_context);
814
815     _cmdArg = (SGPropertyNode*)cmdarg;
816
817     call(code, argc, args, locals);
818     hashset(_globals, moduleName, locals);
819 }
820
821 void FGNasalSys::deleteModule(const char* moduleName)
822 {
823     naRef modname = naNewString(_context);
824     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
825     naHash_delete(_globals, modname);
826 }
827
828 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
829 {
830     int errLine = -1;
831     naRef srcfile = naNewString(_context);
832     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
833     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
834     if(naIsNil(code)) {
835         SG_LOG(SG_NASAL, SG_ALERT,
836                "Nasal parse error: " << naGetError(_context) <<
837                " in "<< filename <<", line " << errLine);
838         return naNil();
839     }
840
841     // Bind to the global namespace before returning
842     return naBindFunction(_context, code, _globals);
843 }
844
845 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
846 {
847     const char* nasal = arg->getStringValue("script");
848     const char* moduleName = arg->getStringValue("module");
849     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
850     if(naIsNil(code)) return false;
851
852     // Commands can be run "in" a module.  Make sure that module
853     // exists, and set it up as the local variables hash for the
854     // command.
855     naRef locals = naNil();
856     if(moduleName[0]) {
857         naRef modname = naNewString(_context);
858         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
859         if(!naHash_get(_globals, modname, &locals)) {
860             locals = naNewHash(_context);
861             naHash_set(_globals, modname, locals);
862         }
863     }
864
865     // Cache this command's argument for inspection via cmdarg().  For
866     // performance reasons, we won't bother with it if the invoked
867     // code doesn't need it.
868     _cmdArg = (SGPropertyNode*)arg;
869
870     call(code, 0, 0, locals);
871     return true;
872 }
873
874 // settimer(func, dt, simtime) extension function.  The first argument
875 // is a Nasal function to call, the second is a delta time (from now),
876 // in seconds.  The third, if present, is a boolean value indicating
877 // that "real world" time (rather than simulator time) is to be used.
878 //
879 // Implementation note: the FGTimer objects don't live inside the
880 // garbage collector, so the Nasal handler functions have to be
881 // "saved" somehow lest they be inadvertently cleaned.  In this case,
882 // they are inserted into a globals.__gcsave hash and removed on
883 // expiration.
884 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
885 {
886     // Extract the handler, delta, and simtime arguments:
887     naRef handler = argc > 0 ? args[0] : naNil();
888     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
889         naRuntimeError(c, "settimer() with invalid function argument");
890         return;
891     }
892
893     naRef delta = argc > 1 ? args[1] : naNil();
894     if(naIsNil(delta)) {
895         naRuntimeError(c, "settimer() with invalid time argument");
896         return;
897     }
898
899     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
900
901     // Generate and register a C++ timer handler
902     NasalTimer* t = new NasalTimer;
903     t->handler = handler;
904     t->gcKey = gcSave(handler);
905     t->nasal = this;
906
907     globals->get_event_mgr()->addEvent("NasalTimer",
908                                        t, &NasalTimer::timerExpired,
909                                        delta.num, simtime);
910 }
911
912 void FGNasalSys::handleTimer(NasalTimer* t)
913 {
914     call(t->handler, 0, 0, naNil());
915     gcRelease(t->gcKey);
916 }
917
918 int FGNasalSys::gcSave(naRef r)
919 {
920     int key = _nextGCKey++;
921     naHash_set(_gcHash, naNum(key), r);
922     return key;
923 }
924
925 void FGNasalSys::gcRelease(int key)
926 {
927     naHash_delete(_gcHash, naNum(key));
928 }
929
930 void FGNasalSys::NasalTimer::timerExpired()
931 {
932     nasal->handleTimer(this);
933     delete this;
934 }
935
936 int FGNasalSys::_listenerId = 0;
937
938 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
939 // Attaches a callback function to a property (specified as a global
940 // property path string or a SGPropertyNode_ptr* ghost). If the third,
941 // optional argument (default=0) is set to 1, then the function is also
942 // called initially. If the fourth, optional argument is set to 0, then the
943 // function is only called when the property node value actually changes.
944 // Otherwise it's called independent of the value whenever the node is
945 // written to (default). The setlistener() function returns a unique
946 // id number, which is to be used as argument to the removelistener()
947 // function.
948 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
949 {
950     SGPropertyNode_ptr node;
951     naRef prop = argc > 0 ? args[0] : naNil();
952     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
953     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
954     else {
955         naRuntimeError(c, "setlistener() with invalid property argument");
956         return naNil();
957     }
958
959     if(node->isTied())
960         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
961                 node->getPath());
962
963     naRef code = argc > 1 ? args[1] : naNil();
964     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
965         naRuntimeError(c, "setlistener() with invalid function argument");
966         return naNil();
967     }
968
969     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
970     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
971     FGNasalListener *nl = new FGNasalListener(node, code, this,
972             gcSave(code), _listenerId, init, type);
973
974     node->addChangeListener(nl, init);
975
976     _listener[_listenerId] = nl;
977     return naNum(_listenerId++);
978 }
979
980 // removelistener(int) extension function. The argument is the id of
981 // a listener as returned by the setlistener() function.
982 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
983 {
984     naRef id = argc > 0 ? args[0] : naNil();
985     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
986
987     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
988         naRuntimeError(c, "removelistener() with invalid listener id");
989         return naNil();
990     }
991
992     it->second->_dead = true;
993     _dead_listener.push_back(it->second);
994     _listener.erase(it);
995     return naNum(_listener.size());
996 }
997
998
999
1000 // FGNasalListener class.
1001
1002 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1003                                  FGNasalSys* nasal, int key, int id,
1004                                  int init, int type) :
1005     _node(node),
1006     _code(code),
1007     _gcKey(key),
1008     _id(id),
1009     _nas(nasal),
1010     _init(init),
1011     _type(type),
1012     _active(0),
1013     _dead(false),
1014     _last_int(0L),
1015     _last_float(0.0)
1016 {
1017     if(_type == 0 && !_init)
1018         changed(node);
1019 }
1020
1021 FGNasalListener::~FGNasalListener()
1022 {
1023     _node->removeChangeListener(this);
1024     _nas->gcRelease(_gcKey);
1025 }
1026
1027 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1028 {
1029     if(_active || _dead) return;
1030     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1031     _active++;
1032     naRef arg[4];
1033     arg[0] = _nas->propNodeGhost(which);
1034     arg[1] = _nas->propNodeGhost(_node);
1035     arg[2] = mode;                  // value changed, child added/removed
1036     arg[3] = naNum(_node != which); // child event?
1037     _nas->call(_code, 4, arg, naNil());
1038     _active--;
1039 }
1040
1041 void FGNasalListener::valueChanged(SGPropertyNode* node)
1042 {
1043     if(_type < 2 && node != _node) return;   // skip child events
1044     if(_type > 0 || changed(_node) || _init)
1045         call(node, naNum(0));
1046
1047     _init = 0;
1048 }
1049
1050 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1051 {
1052     if(_type == 2) call(child, naNum(1));
1053 }
1054
1055 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1056 {
1057     if(_type == 2) call(child, naNum(-1));
1058 }
1059
1060 bool FGNasalListener::changed(SGPropertyNode* node)
1061 {
1062     SGPropertyNode::Type type = node->getType();
1063     if(type == SGPropertyNode::NONE) return false;
1064     if(type == SGPropertyNode::UNSPECIFIED) return true;
1065
1066     bool result;
1067     switch(type) {
1068     case SGPropertyNode::BOOL:
1069     case SGPropertyNode::INT:
1070     case SGPropertyNode::LONG:
1071         {
1072             long l = node->getLongValue();
1073             result = l != _last_int;
1074             _last_int = l;
1075             return result;
1076         }
1077     case SGPropertyNode::FLOAT:
1078     case SGPropertyNode::DOUBLE:
1079         {
1080             double d = node->getDoubleValue();
1081             result = d != _last_float;
1082             _last_float = d;
1083             return result;
1084         }
1085     default:
1086         {
1087             string s = node->getStringValue();
1088             result = s != _last_string;
1089             _last_string = s;
1090             return result;
1091         }
1092     }
1093 }
1094
1095
1096
1097 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
1098 // such a class, then it lets modelLoaded() run the <load> script, and the
1099 // destructor the <unload> script. The latter happens when the model branch
1100 // is removed from the scene graph.
1101
1102 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1103                                    osg::Node *)
1104 {
1105     if(!prop)
1106         return;
1107     SGPropertyNode *nasal = prop->getNode("nasal");
1108     if(!nasal)
1109         return;
1110
1111     SGPropertyNode *load = nasal->getNode("load");
1112     _unload = nasal->getNode("unload");
1113     if(!load && !_unload)
1114         return;
1115
1116     _module = path;
1117     if(_props)
1118         _module += ':' + _props->getPath();
1119     const char *s = load ? load->getStringValue() : "";
1120
1121     naRef arg[2];
1122     arg[0] = nasalSys->propNodeGhost(_root);
1123     arg[1] = nasalSys->propNodeGhost(prop);
1124     nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s),
1125                            _root, 2, arg);
1126     _props = 0;
1127 }
1128
1129 FGNasalModelData::~FGNasalModelData()
1130 {
1131     if(_module.empty())
1132         return;
1133
1134     if(!nasalSys) {
1135         SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1136                 "without Nasal subsystem present.");
1137         return;
1138     }
1139
1140     if(_unload) {
1141         const char *s = _unload->getStringValue();
1142         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1143     }
1144     nasalSys->deleteModule(_module.c_str());
1145 }
1146
1147
1148
1149 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1150 //
1151 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1152     _c(naSubContext(c)),
1153     _start_element(argc > 1 ? args[1] : naNil()),
1154     _end_element(argc > 2 ? args[2] : naNil()),
1155     _data(argc > 3 ? args[3] : naNil()),
1156     _pi(argc > 4 ? args[4] : naNil())
1157 {
1158 }
1159
1160 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1161 {
1162     if(naIsNil(_start_element)) return;
1163     naRef attr = naNewHash(_c);
1164     for(int i=0; i<a.size(); i++) {
1165         naRef name = make_string(a.getName(i));
1166         naRef value = make_string(a.getValue(i));
1167         naHash_set(attr, name, value);
1168     }
1169     call(_start_element, 2, make_string(tag), attr);
1170 }
1171
1172 void NasalXMLVisitor::endElement(const char* tag)
1173 {
1174     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1175 }
1176
1177 void NasalXMLVisitor::data(const char* str, int len)
1178 {
1179     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1180 }
1181
1182 void NasalXMLVisitor::pi(const char* target, const char* data)
1183 {
1184     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1185 }
1186
1187 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1188 {
1189     naRef args[2];
1190     args[0] = a;
1191     args[1] = b;
1192     naCall(_c, func, num, args, naNil(), naNil());
1193     if(naGetError(_c))
1194         naRethrowError(_c);
1195 }
1196
1197 naRef NasalXMLVisitor::make_string(const char* s, int n)
1198 {
1199     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1200                           n < 0 ? strlen(s) : n);
1201 }
1202
1203