]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/nasal-props.cxx
Expose position along the flight-path to Nasal.
[flightgear.git] / src / Scripting / nasal-props.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #include <cstring>
7
8 #include <simgear/nasal/nasal.h>
9 #include <simgear/props/props.hxx>
10 #include <simgear/props/vectorPropTemplates.hxx>
11
12 #include <Main/globals.hxx>
13
14 #include "NasalSys.hxx"
15
16 using namespace std;
17
18 // Implementation of a Nasal wrapper for the SGPropertyNode class,
19 // using the Nasal "ghost" (er... Garbage collection Handle for
20 // OutSide Thingy) facility.
21 //
22 // Note that these functions appear in Nasal with prepended
23 // underscores.  They work on the low-level "ghost" objects and aren't
24 // intended for use from user code, but from Nasal code you will find
25 // in props.nas.  That is where the Nasal props.Node class is defined,
26 // which provides a saner interface along the lines of SGPropertyNode.
27
28 static void propNodeGhostDestroy(void* ghost)
29 {
30     SGPropertyNode_ptr* prop = (SGPropertyNode_ptr*)ghost;
31     delete prop;
32 }
33
34 naGhostType PropNodeGhostType = { propNodeGhostDestroy, "prop" };
35
36 naRef propNodeGhostCreate(naContext c, SGPropertyNode* n)
37 {
38     if(!n) return naNil();
39     SGPropertyNode_ptr* ghost = new SGPropertyNode_ptr(n);
40     return naNewGhost(c, &PropNodeGhostType, ghost);
41 }
42
43 naRef FGNasalSys::propNodeGhost(SGPropertyNode* handle)
44 {
45     return propNodeGhostCreate(_context, handle);
46 }
47
48 SGPropertyNode* ghostToPropNode(naRef ref)
49 {
50   if (!naIsGhost(ref) || (naGhost_type(ref) != &PropNodeGhostType))
51     return NULL;
52   
53   SGPropertyNode_ptr* pp = (SGPropertyNode_ptr*) naGhost_ptr(ref);
54   return pp->ptr();
55 }
56
57 #define NASTR(s) s ? naStr_fromdata(naNewString(c),(char*)(s),strlen(s)) : naNil()
58
59 //
60 // Standard header for the extension functions.  It turns the "ghost"
61 // found in arg[0] into a SGPropertyNode_ptr*, and then "unwraps" the
62 // vector found in the second argument into a normal-looking args
63 // array.  This allows the Nasal handlers to do things like:
64 //   Node.getChild = func { _getChild(me.ghost, arg) }
65 //
66 #define NODENOARG()                                                       \
67     if(argc < 2 || !naIsGhost(args[0]) ||                               \
68        naGhost_type(args[0]) != &PropNodeGhostType)                       \
69         naRuntimeError(c, "bad argument to props function");            \
70     SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(args[0]);
71
72 #define NODEARG()                                                       \
73     NODENOARG();                                                        \
74     naRef argv = args[1]
75
76 static naRef f_getType(naContext c, naRef me, int argc, naRef* args)
77 {
78     using namespace simgear;
79     NODENOARG();
80     const char* t = "unknown";
81     switch((*node)->getType()) {
82     case props::NONE:   t = "NONE";   break;
83     case props::ALIAS:  t = "ALIAS";  break;
84     case props::BOOL:   t = "BOOL";   break;
85     case props::INT:    t = "INT";    break;
86     case props::LONG:   t = "LONG";   break;
87     case props::FLOAT:  t = "FLOAT";  break;
88     case props::DOUBLE: t = "DOUBLE"; break;
89     case props::STRING: t = "STRING"; break;
90     case props::UNSPECIFIED: t = "UNSPECIFIED"; break;
91     case props::VEC3D:  t = "VEC3D";  break;
92     case props::VEC4D:  t = "VEC4D";  break;
93     case props::EXTENDED: t = "EXTENDED";  break; // shouldn't happen
94     }
95     return NASTR(t);
96 }
97
98 static naRef f_getAttribute(naContext c, naRef me, int argc, naRef* args)
99 {
100     NODEARG();
101     if(naVec_size(argv) == 0) return naNum(unsigned((*node)->getAttributes()));
102     naRef val = naVec_get(argv, 0);
103     const char *a = naStr_data(val);
104     SGPropertyNode::Attribute attr;
105     if(!a) a = "";
106     if(!strcmp(a, "last")) return naNum(SGPropertyNode::LAST_USED_ATTRIBUTE);
107     else if(!strcmp(a, "children"))    return naNum((*node)->nChildren());
108     else if(!strcmp(a, "listeners"))   return naNum((*node)->nListeners());
109     else if(!strcmp(a, "references"))  return naNum(node->getNumRefs());
110     else if(!strcmp(a, "tied"))        return naNum((*node)->isTied());
111     else if(!strcmp(a, "alias"))       return naNum((*node)->isAlias());
112     else if(!strcmp(a, "readable"))    attr = SGPropertyNode::READ;
113     else if(!strcmp(a, "writable"))    attr = SGPropertyNode::WRITE;
114     else if(!strcmp(a, "archive"))     attr = SGPropertyNode::ARCHIVE;
115     else if(!strcmp(a, "trace-read"))  attr = SGPropertyNode::TRACE_READ;
116     else if(!strcmp(a, "trace-write")) attr = SGPropertyNode::TRACE_WRITE;
117     else if(!strcmp(a, "userarchive")) attr = SGPropertyNode::USERARCHIVE;
118     else if(!strcmp(a, "preserve"))    attr = SGPropertyNode::PRESERVE;
119     else {
120         naRuntimeError(c, "props.getAttribute() with invalid attribute");
121         return naNil();
122     }
123     return naNum((*node)->getAttribute(attr));
124 }
125
126 static naRef f_setAttribute(naContext c, naRef me, int argc, naRef* args)
127 {
128     NODEARG();
129     naRef val = naVec_get(argv, 0);
130     if(naVec_size(argv) == 1 && naIsNum(val)) {
131         naRef ret = naNum((*node)->getAttributes());
132         (*node)->setAttributes((int)val.num);
133         return ret;
134     }
135     SGPropertyNode::Attribute attr;
136     const char *a = naStr_data(val);
137     if(!a) a = "";
138     if(!strcmp(a, "readable"))         attr = SGPropertyNode::READ;
139     else if(!strcmp(a, "writable"))    attr = SGPropertyNode::WRITE;
140     else if(!strcmp(a, "archive"))     attr = SGPropertyNode::ARCHIVE;
141     else if(!strcmp(a, "trace-read"))  attr = SGPropertyNode::TRACE_READ;
142     else if(!strcmp(a, "trace-write")) attr = SGPropertyNode::TRACE_WRITE;
143     else if(!strcmp(a, "userarchive")) attr = SGPropertyNode::USERARCHIVE;
144     else if(!strcmp(a, "preserve"))    attr = SGPropertyNode::PRESERVE;
145     else {
146         naRuntimeError(c, "props.setAttribute() with invalid attribute");
147         return naNil();
148     }
149     naRef ret = naNum((*node)->getAttribute(attr));
150     (*node)->setAttribute(attr, naTrue(naVec_get(argv, 1)) ? true : false);
151     return ret;
152 }
153
154 static naRef f_getName(naContext c, naRef me, int argc, naRef* args)
155 {
156     NODENOARG();
157     return NASTR((*node)->getName());
158 }
159
160 static naRef f_getIndex(naContext c, naRef me, int argc, naRef* args)
161 {
162     NODENOARG();
163     return naNum((*node)->getIndex());
164 }
165
166 template<typename T>
167 naRef makeVectorFromVec(naContext c, const T& vec)
168 {
169     const int num_components
170         = sizeof(vec.data()) / sizeof(typename T::value_type);
171     naRef vector = naNewVector(c);
172     naVec_setsize(c, vector, num_components);
173     for (int i = 0; i < num_components; ++i)
174         naVec_set(vector, i, naNum(vec[i]));
175     return vector;
176 }
177
178 static naRef f_getValue(naContext c, naRef me, int argc, naRef* args)
179 {
180     using namespace simgear;
181     NODENOARG();
182     switch((*node)->getType()) {
183     case props::BOOL:   case props::INT:
184     case props::LONG:   case props::FLOAT:
185     case props::DOUBLE:
186     {
187         double dv = (*node)->getDoubleValue();
188         if (SGMisc<double>::isNaN(dv)) {
189           SG_LOG(SG_NASAL, SG_ALERT, "Nasal getValue: property " << (*node)->getPath() << " is NaN");
190           return naNil();
191         }
192
193         return naNum(dv);
194     }
195
196     case props::STRING:
197     case props::UNSPECIFIED:
198         return NASTR((*node)->getStringValue());
199     case props::VEC3D:
200         return makeVectorFromVec(c, (*node)->getValue<SGVec3d>());
201     case props::VEC4D:
202         return makeVectorFromVec(c, (*node)->getValue<SGVec4d>());
203     default:
204         return naNil();
205     }
206 }
207
208 template<typename T>
209 T makeVecFromVector(naRef vector)
210 {
211     T vec;
212     const int num_components
213         = sizeof(vec.data()) / sizeof(typename T::value_type);
214     int size = naVec_size(vector);
215
216     for (int i = 0; i < num_components && i < size; ++i) {
217         naRef element = naVec_get(vector, i);
218         naRef n = naNumValue(element);
219         if (!naIsNil(n))
220             vec[i] = n.num;
221     }
222     return vec;
223 }
224
225 static naRef f_setValue(naContext c, naRef me, int argc, naRef* args)
226 {
227     NODEARG();
228     naRef val = naVec_get(argv, 0);
229     bool result = false;
230     if(naIsString(val)) {
231         result = (*node)->setStringValue(naStr_data(val));
232     } else if(naIsVector(val)) {
233         if(naVec_size(val) == 3)
234             result = (*node)->setValue(makeVecFromVector<SGVec3d>(val));
235         else if(naVec_size(val) == 4)
236             result = (*node)->setValue(makeVecFromVector<SGVec4d>(val));
237         else
238             naRuntimeError(c, "props.setValue() vector value has wrong size");
239     } else {
240         naRef n = naNumValue(val);
241         if(naIsNil(n))
242             naRuntimeError(c, "props.setValue() with non-number");
243
244         double d = naNumValue(val).num;
245         if (SGMisc<double>::isNaN(d)) {
246           naRuntimeError(c, "props.setValue() passed a NaN");
247         }
248
249         result = (*node)->setDoubleValue(d);
250     }
251     return naNum(result);
252 }
253
254 static naRef f_setIntValue(naContext c, naRef me, int argc, naRef* args)
255 {
256     NODEARG();
257     // Original code:
258     //   int iv = (int)naNumValue(naVec_get(argv, 0)).num;
259
260     // Junk to pacify the gcc-2.95.3 optimizer:
261     naRef tmp0 = naVec_get(argv, 0);
262     naRef tmp1 = naNumValue(tmp0);
263     if(naIsNil(tmp1))
264         naRuntimeError(c, "props.setIntValue() with non-number");
265     double tmp2 = tmp1.num;
266     int iv = (int)tmp2;
267
268     return naNum((*node)->setIntValue(iv));
269 }
270
271 static naRef f_setBoolValue(naContext c, naRef me, int argc, naRef* args)
272 {
273     NODEARG();
274     naRef val = naVec_get(argv, 0);
275     return naNum((*node)->setBoolValue(naTrue(val) ? true : false));
276 }
277
278 static naRef f_setDoubleValue(naContext c, naRef me, int argc, naRef* args)
279 {
280     NODEARG();
281     naRef r = naNumValue(naVec_get(argv, 0));
282     if (naIsNil(r))
283         naRuntimeError(c, "props.setDoubleValue() with non-number");
284
285     if (SGMisc<double>::isNaN(r.num)) {
286       naRuntimeError(c, "props.setDoubleValue() passed a NaN");
287     }
288
289     return naNum((*node)->setDoubleValue(r.num));
290 }
291
292 static naRef f_getParent(naContext c, naRef me, int argc, naRef* args)
293 {
294     NODENOARG();
295     SGPropertyNode* n = (*node)->getParent();
296     if(!n) return naNil();
297     return propNodeGhostCreate(c, n);
298 }
299
300 static naRef f_getChild(naContext c, naRef me, int argc, naRef* args)
301 {
302     NODEARG();
303     naRef child = naVec_get(argv, 0);
304     if(!naIsString(child)) return naNil();
305     naRef idx = naNumValue(naVec_get(argv, 1));
306     bool create = naTrue(naVec_get(argv, 2)) != 0;
307     SGPropertyNode* n;
308     try {
309         if(naIsNil(idx) || !naIsNum(idx)) {
310             n = (*node)->getChild(naStr_data(child), create);
311         } else {
312             n = (*node)->getChild(naStr_data(child), (int)idx.num, create);
313         }
314     } catch (const string& err) {
315         naRuntimeError(c, (char *)err.c_str());
316         return naNil();
317     }
318     if(!n) return naNil();
319     return propNodeGhostCreate(c, n);
320 }
321
322 static naRef f_getChildren(naContext c, naRef me, int argc, naRef* args)
323 {
324     NODEARG();
325     naRef result = naNewVector(c);
326     if(naIsNil(argv) || naVec_size(argv) == 0) {
327         // Get all children
328         for(int i=0; i<(*node)->nChildren(); i++)
329             naVec_append(result, propNodeGhostCreate(c, (*node)->getChild(i)));
330     } else {
331         // Get all children of a specified name
332         naRef name = naVec_get(argv, 0);
333         if(!naIsString(name)) return naNil();
334         try {
335             vector<SGPropertyNode_ptr> children
336                 = (*node)->getChildren(naStr_data(name));
337             for(unsigned int i=0; i<children.size(); i++)
338                 naVec_append(result, propNodeGhostCreate(c, children[i]));
339         } catch (const string& err) {
340             naRuntimeError(c, (char *)err.c_str());
341             return naNil();
342         }
343     }
344     return result;
345 }
346
347 static naRef f_addChild(naContext c, naRef me, int argc, naRef* args)
348 {
349     NODEARG();
350     naRef child = naVec_get(argv, 0);
351     if(!naIsString(child)) return naNil();
352     naRef ref_min_index = naNumValue(naVec_get(argv, 1));
353     naRef ref_append = naVec_get(argv, 2);
354     SGPropertyNode* n;
355     try
356     {
357       int min_index = 0;
358       if( !naIsNil(ref_min_index) && naIsNum(ref_min_index) )
359         min_index = ref_min_index.num;
360
361       bool append = true;
362       if( !naIsNil(ref_append) )
363         append = naTrue(ref_append) != 0;
364
365       n = (*node)->addChild(naStr_data(child), min_index, append);
366     }
367     catch (const string& err)
368     {
369       naRuntimeError(c, (char *)err.c_str());
370       return naNil();
371     }
372
373     return propNodeGhostCreate(c, n);
374 }
375
376 static naRef f_addChildren(naContext c, naRef me, int argc, naRef* args)
377 {
378     NODEARG();
379     naRef child = naVec_get(argv, 0);
380     if(!naIsString(child)) return naNil();
381     naRef ref_count = naNumValue(naVec_get(argv, 1));
382     naRef ref_min_index = naNumValue(naVec_get(argv, 2));
383     naRef ref_append = naVec_get(argv, 3);
384     try
385     {
386       size_t count = 0;
387       if( !naIsNum(ref_count) )
388         throw string("props.addChildren() missing number of children");
389       count = ref_count.num;
390
391       int min_index = 0;
392       if( !naIsNil(ref_min_index) && naIsNum(ref_min_index) )
393         min_index = ref_min_index.num;
394
395       bool append = true;
396       if( !naIsNil(ref_append) )
397         append = naTrue(ref_append) != 0;
398
399       const simgear::PropertyList& nodes =
400         (*node)->addChildren(naStr_data(child), count, min_index, append);
401
402       naRef result = naNewVector(c);
403       for( size_t i = 0; i < nodes.size(); ++i )
404         naVec_append(result, propNodeGhostCreate(c, nodes[i]));
405       return result;
406     }
407     catch (const string& err)
408     {
409       naRuntimeError(c, (char *)err.c_str());
410     }
411
412     return naNil();
413 }
414
415 static naRef f_removeChild(naContext c, naRef me, int argc, naRef* args)
416 {
417     NODEARG();
418     naRef child = naVec_get(argv, 0);
419     naRef index = naVec_get(argv, 1);
420     if(!naIsString(child) || !naIsNum(index)) return naNil();
421     SGPropertyNode_ptr n = 0;
422     try {
423         n = (*node)->removeChild(naStr_data(child), (int)index.num, false);
424     } catch (const string& err) {
425         naRuntimeError(c, (char *)err.c_str());
426     }
427     return propNodeGhostCreate(c, n);
428 }
429
430 static naRef f_removeChildren(naContext c, naRef me, int argc, naRef* args)
431 {
432     NODEARG();
433     naRef result = naNewVector(c);
434     if(naIsNil(argv) || naVec_size(argv) == 0) {
435         // Remove all children
436         for(int i = (*node)->nChildren() - 1; i >=0; i--)
437             naVec_append(result, propNodeGhostCreate(c, (*node)->removeChild(i, false)));
438     } else {
439         // Remove all children of a specified name
440         naRef name = naVec_get(argv, 0);
441         if(!naIsString(name)) return naNil();
442         try {
443             vector<SGPropertyNode_ptr> children
444                 = (*node)->removeChildren(naStr_data(name), false);
445             for(unsigned int i=0; i<children.size(); i++)
446                 naVec_append(result, propNodeGhostCreate(c, children[i]));
447         } catch (const string& err) {
448             naRuntimeError(c, (char *)err.c_str());
449             return naNil();
450         }
451     }
452     return result;
453 }
454
455 static naRef f_alias(naContext c, naRef me, int argc, naRef* args)
456 {
457     NODEARG();
458     SGPropertyNode* al;
459     naRef prop = naVec_get(argv, 0);
460     try {
461         if(naIsString(prop)) al = globals->get_props()->getNode(naStr_data(prop), true);
462         else if(naIsGhost(prop)) al = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
463         else throw string("props.alias() with bad argument");
464     } catch (const string& err) {
465         naRuntimeError(c, (char *)err.c_str());
466         return naNil();
467     }
468     return naNum((*node)->alias(al));
469 }
470
471 static naRef f_unalias(naContext c, naRef me, int argc, naRef* args)
472 {
473     NODENOARG();
474     return naNum((*node)->unalias());
475 }
476
477 static naRef f_getAliasTarget(naContext c, naRef me, int argc, naRef* args)
478 {
479     NODENOARG();
480     return propNodeGhostCreate(c, (*node)->getAliasTarget());
481 }
482
483 static naRef f_getNode(naContext c, naRef me, int argc, naRef* args)
484 {
485     NODEARG();
486     naRef path = naVec_get(argv, 0);
487     bool create = naTrue(naVec_get(argv, 1)) != 0;
488     if(!naIsString(path)) return naNil();
489     SGPropertyNode* n;
490     try {
491         n = (*node)->getNode(naStr_data(path), create);
492     } catch (const string& err) {
493         naRuntimeError(c, (char *)err.c_str());
494         return naNil();
495     }
496     return propNodeGhostCreate(c, n);
497 }
498
499 static naRef f_new(naContext c, naRef me, int argc, naRef* args)
500 {
501     return propNodeGhostCreate(c, new SGPropertyNode());
502 }
503
504 static naRef f_globals(naContext c, naRef me, int argc, naRef* args)
505 {
506     return propNodeGhostCreate(c, globals->get_props());
507 }
508
509 static struct {
510     naCFunction func;
511     const char* name;
512 } propfuncs[] = {
513     { f_getType, "_getType" },
514     { f_getAttribute, "_getAttribute" },
515     { f_setAttribute, "_setAttribute" },
516     { f_getName, "_getName" },
517     { f_getIndex, "_getIndex" },
518     { f_getValue, "_getValue" },
519     { f_setValue, "_setValue" },
520     { f_setIntValue, "_setIntValue" },
521     { f_setBoolValue, "_setBoolValue" },
522     { f_setDoubleValue, "_setDoubleValue" },
523     { f_getParent, "_getParent" },
524     { f_getChild, "_getChild" },
525     { f_getChildren, "_getChildren" },
526     { f_addChild, "_addChild" },
527     { f_addChildren, "_addChildren" },
528     { f_removeChild, "_removeChild" },
529     { f_removeChildren, "_removeChildren" },
530     { f_alias, "_alias" },
531     { f_unalias, "_unalias" },
532     { f_getAliasTarget, "_getAliasTarget" },
533     { f_getNode, "_getNode" },
534     { f_new, "_new" },
535     { f_globals, "_globals" },
536     { 0, 0 }
537 };
538
539 naRef FGNasalSys::genPropsModule()
540 {
541     naRef namespc = naNewHash(_context);
542     for(int i=0; propfuncs[i].name; i++)
543         hashset(namespc, propfuncs[i].name,
544                 naNewFunc(_context, naNewCCode(_context, propfuncs[i].func)));
545     return namespc;
546 }