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