]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Support for multiple data dirs.
[flightgear.git] / src / Main / fg_commands.cxx
1 // fg_commands.cxx - internal FGFS commands.
2
3 #ifdef HAVE_CONFIG_H
4 #  include "config.h"
5 #endif
6
7 #include <string.h>             // strcmp()
8
9 #include <simgear/compiler.h>
10
11 #include <string>
12 #include <fstream>
13
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/scene/material/mat.hxx>
18 #include <simgear/scene/material/matlib.hxx>
19 #include <simgear/structure/exception.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/props/props.hxx>
22 #include <simgear/props/props_io.hxx>
23 #include <simgear/structure/event_mgr.hxx>
24 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <simgear/timing/sg_time.hxx>
26 #include <simgear/io/HTTPRequest.hxx>
27
28 #include <FDM/flight.hxx>
29 #include <GUI/gui.h>
30 #include <GUI/new_gui.hxx>
31 #include <GUI/dialog.hxx>
32 #include <Aircraft/replay.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scripting/NasalSys.hxx>
35 #include <Sound/sample_queue.hxx>
36 #include <Airports/xmlloader.hxx>
37 #include <Network/HTTPClient.hxx>
38 #include <Viewer/viewmgr.hxx>
39 #include <Viewer/viewer.hxx>
40 #include <Environment/presets.hxx>
41
42 #include "fg_init.hxx"
43 #include "fg_io.hxx"
44 #include "fg_os.hxx"
45 #include "fg_commands.hxx"
46 #include "fg_props.hxx"
47 #include "globals.hxx"
48 #include "logger.hxx"
49 #include "util.hxx"
50 #include "main.hxx"
51 #include "positioninit.hxx"
52
53 #include <boost/scoped_array.hpp>
54
55 #ifdef FG_HAVE_GPERFTOOLS
56 # include <google/profiler.h>
57 #endif
58
59 using std::string;
60 using std::ifstream;
61 using std::ofstream;
62
63
64 ////////////////////////////////////////////////////////////////////////
65 // Static helper functions.
66 ////////////////////////////////////////////////////////////////////////
67
68
69 static inline SGPropertyNode *
70 get_prop (const SGPropertyNode * arg)
71 {
72     return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
73 }
74
75 static inline SGPropertyNode *
76 get_prop2 (const SGPropertyNode * arg)
77 {
78     return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
79 }
80
81
82 /**
83  * Get a double value and split it as required.
84  */
85 static void
86 split_value (double full_value, const char * mask,
87              double * unmodifiable, double * modifiable)
88 {
89     if (!strcmp("integer", mask)) {
90         *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
91         *unmodifiable = full_value - *modifiable;
92     } else if (!strcmp("decimal", mask)) {
93         *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
94         *modifiable = full_value - *unmodifiable;
95     } else {
96         if (strcmp("all", mask))
97             SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
98                    << " assuming 'all'");
99         *unmodifiable = 0;
100         *modifiable = full_value;
101     }
102 }
103
104
105 /**
106  * Clamp or wrap a value as specified.
107  */
108 static void
109 limit_value (double * value, const SGPropertyNode * arg)
110 {
111     const SGPropertyNode * min_node = arg->getChild("min");
112     const SGPropertyNode * max_node = arg->getChild("max");
113
114     bool wrap = arg->getBoolValue("wrap");
115
116     if (min_node == 0 || max_node == 0)
117         wrap = false;
118   
119     if (wrap) {                 // wrap such that min <= x < max
120         double min_val = min_node->getDoubleValue();
121         double max_val = max_node->getDoubleValue();
122         double resolution = arg->getDoubleValue("resolution");
123         if (resolution > 0.0) {
124             // snap to (min + N*resolution), taking special care to handle imprecision
125             int n = (int)floor((*value - min_val) / resolution + 0.5);
126             int steps = (int)floor((max_val - min_val) / resolution + 0.5);
127             SG_NORMALIZE_RANGE(n, 0, steps);
128             *value = min_val + resolution * n;
129         } else {
130             // plain circular wrapping
131             SG_NORMALIZE_RANGE(*value, min_val, max_val);
132         }
133     } else {                    // clamp such that min <= x <= max
134         if ((min_node != 0) && (*value < min_node->getDoubleValue()))
135             *value = min_node->getDoubleValue();
136         else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
137             *value = max_node->getDoubleValue();
138     }
139 }
140
141 static bool
142 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
143 {
144     switch (value1->getType()) {
145     case simgear::props::BOOL:
146         return (value1->getBoolValue() == value2->getBoolValue());
147     case simgear::props::INT:
148         return (value1->getIntValue() == value2->getIntValue());
149     case simgear::props::LONG:
150         return (value1->getLongValue() == value2->getLongValue());
151     case simgear::props::FLOAT:
152         return (value1->getFloatValue() == value2->getFloatValue());
153     case simgear::props::DOUBLE:
154         return (value1->getDoubleValue() == value2->getDoubleValue());
155     default:
156         return !strcmp(value1->getStringValue(), value2->getStringValue());
157     }
158 }
159
160
161
162 ////////////////////////////////////////////////////////////////////////
163 // Command implementations.
164 ////////////////////////////////////////////////////////////////////////
165
166
167 /**
168  * Built-in command: do nothing.
169  */
170 static bool
171 do_null (const SGPropertyNode * arg)
172 {
173   return true;
174 }
175
176 /**
177  * Built-in command: run a Nasal script.
178  */
179 static bool
180 do_nasal (const SGPropertyNode * arg)
181 {
182     return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
183 }
184
185 /**
186  * Built-in command: exit FlightGear.
187  *
188  * status: the exit status to return to the operating system (defaults to 0)
189  */
190 static bool
191 do_exit (const SGPropertyNode * arg)
192 {
193     SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
194     fgSetBool("/sim/signals/exit", true);
195     globals->saveUserSettings();
196     fgOSExit(arg->getIntValue("status", 0));
197     return true;
198 }
199
200
201 /**
202  * Reset FlightGear (Shift-Escape or Menu->File->Reset)
203  */
204 static bool
205 do_reset (const SGPropertyNode * arg)
206 {
207     fgReInitSubsystems();
208     return true;
209 }
210
211 /**
212  * Built-in command: replay the FDR buffer
213  */
214 static bool
215 do_replay (const SGPropertyNode * arg)
216 {
217     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
218     return r->start();
219 }
220
221 /**
222  * Built-in command: pause/unpause the sim
223  */
224 static bool
225 do_pause (const SGPropertyNode * arg)
226 {
227     bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
228     if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
229     {
230         do_replay(NULL);
231     }
232     else
233     {
234         fgSetBool("/sim/freeze/master",!paused);
235         fgSetBool("/sim/freeze/clock",!paused);
236     }
237   
238     SGPropertyNode_ptr args(new SGPropertyNode);
239     args->setStringValue("id", "sim-pause");
240     if (!paused) {
241       args->setStringValue("label", "Simulation is paused");
242       globals->get_commands()->execute("show-message", args);
243     } else {
244       globals->get_commands()->execute("clear-message", args);
245     }
246   
247     return true;
248 }
249
250 /**
251  * Built-in command: load flight.
252  *
253  * file (optional): the name of the file to load (relative to current
254  *   directory).  Defaults to "fgfs.sav"
255  */
256 static bool
257 do_load (const SGPropertyNode * arg)
258 {
259     string file = arg->getStringValue("file", "fgfs.sav");
260     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
261         file += ".sav";
262
263     if (!fgValidatePath(file.c_str(), false)) {
264         SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
265                 "(unauthorized access)");
266         return false;
267     }
268
269     ifstream input(file.c_str());
270     if (input.good() && fgLoadFlight(input)) {
271         input.close();
272         SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
273         return true;
274     } else {
275         SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
276         return false;
277     }
278 }
279
280
281 /**
282  * Built-in command: save flight.
283  *
284  * file (optional): the name of the file to save (relative to the
285  * current directory).  Defaults to "fgfs.sav".
286  */
287 static bool
288 do_save (const SGPropertyNode * arg)
289 {
290     string file = arg->getStringValue("file", "fgfs.sav");
291     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
292         file += ".sav";
293
294     if (!fgValidatePath(file.c_str(), false)) {
295         SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
296                 "(unauthorized access)");
297         return false;
298     }
299
300     bool write_all = arg->getBoolValue("write-all", false);
301     SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
302     ofstream output(file.c_str());
303     if (output.good() && fgSaveFlight(output, write_all)) {
304         output.close();
305         SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
306         return true;
307     } else {
308         SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
309         return false;
310     }
311 }
312
313 /**
314  * Built-in command: save flight recorder tape.
315  *
316  */
317 static bool
318 do_save_tape (const SGPropertyNode * arg)
319 {
320     FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
321     replay->saveTape(arg);
322
323     return true;
324 }
325 /**
326  * Built-in command: load flight recorder tape.
327  *
328  */
329 static bool
330 do_load_tape (const SGPropertyNode * arg)
331 {
332     FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
333     replay->loadTape(arg);
334
335     return true;
336 }
337
338 /**
339  * Built-in command: (re)load the panel.
340  *
341  * path (optional): the file name to load the panel from 
342  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
343  * and if that's unspecified, to "Panels/Default/default.xml".
344  */
345 static bool
346 do_panel_load (const SGPropertyNode * arg)
347 {
348   string panel_path = arg->getStringValue("path");
349   if (!panel_path.empty()) {
350     // write to the standard property, which will force a load
351     fgSetString("/sim/panel/path", panel_path.c_str());
352   }
353   
354   return true;
355 }
356
357 /**
358  * Built-in command: (re)load preferences.
359  *
360  * path (optional): the file name to load the panel from (relative
361  * to FG_ROOT). Defaults to "preferences.xml".
362  */
363 static bool
364 do_preferences_load (const SGPropertyNode * arg)
365 {
366   try {
367     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
368                 globals->get_props());
369   } catch (const sg_exception &e) {
370     guiErrorMessage("Error reading global preferences: ", e);
371     return false;
372   }
373   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
374   return true;
375 }
376
377 static void
378 do_view_next(bool do_it)
379 {
380   // Only switch view if really requested to do so (and not for example while
381   // reset/reposition where /command/view/next is set to false)
382   if( do_it )
383   {
384     globals->get_current_view()->setHeadingOffset_deg(0.0);
385     globals->get_viewmgr()->next_view();
386   }
387 }
388
389 static void
390 do_view_prev(bool do_it)
391 {
392   if( do_it )
393   {
394     globals->get_current_view()->setHeadingOffset_deg(0.0);
395     globals->get_viewmgr()->prev_view();
396   }
397 }
398
399 /**
400  * An fgcommand to toggle fullscreen mode.
401  * No parameters.
402  */
403 static bool
404 do_toggle_fullscreen(const SGPropertyNode *arg)
405 {
406     fgOSFullScreen();
407     return true;
408 }
409
410 /**
411  * Built-in command: cycle view.
412  */
413 static bool
414 do_view_cycle (const SGPropertyNode * arg)
415 {
416   globals->get_current_view()->setHeadingOffset_deg(0.0);
417   globals->get_viewmgr()->next_view();
418   return true;
419 }
420
421 /**
422  * Built-in command: capture screen.
423  */
424 static bool
425 do_screen_capture (const SGPropertyNode * arg)
426 {
427   return fgDumpSnapShot();
428 }
429
430 static bool
431 do_reload_shaders (const SGPropertyNode*)
432 {
433     simgear::reload_shaders();
434     return true;
435 }
436
437 static bool
438 do_dump_scene_graph (const SGPropertyNode*)
439 {
440     fgDumpSceneGraph();
441     return true;
442 }
443
444 static bool
445 do_dump_terrain_branch (const SGPropertyNode*)
446 {
447     fgDumpTerrainBranch();
448
449     double lon_deg = fgGetDouble("/position/longitude-deg");
450     double lat_deg = fgGetDouble("/position/latitude-deg");
451     SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
452     SGVec3d zero = SGVec3d::fromGeod(geodPos);
453
454     SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
455     SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
456     SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
457
458     return true;
459 }
460
461 static bool
462 do_print_visible_scene_info(const SGPropertyNode*)
463 {
464     fgPrintVisibleSceneInfoCommand();
465     return true;
466 }
467
468 /**
469  * Built-in command: hires capture screen.
470  */
471 static bool
472 do_hires_screen_capture (const SGPropertyNode * arg)
473 {
474   fgHiResDump();
475   return true;
476 }
477
478
479 /**
480  * Reload the tile cache.
481  */
482 static bool
483 do_tile_cache_reload (const SGPropertyNode * arg)
484 {
485     SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
486     bool freeze = master_freeze->getBoolValue();
487     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
488     if ( !freeze ) {
489         master_freeze->setBoolValue(true);
490     }
491
492     globals->get_subsystem("tile-manager")->reinit();
493
494     if ( !freeze ) {
495         master_freeze->setBoolValue(false);
496     }
497     return true;
498 }
499
500 /**
501  * Reload the materials definition
502  */
503  static bool
504  do_materials_reload (const SGPropertyNode * arg)
505  {
506    SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
507    SGMaterialLib* new_matlib =  new SGMaterialLib;
508    SGPath mpath( globals->get_fg_root() );
509    mpath.append( fgGetString("/sim/rendering/materials-file") );
510    bool loaded = new_matlib->load(globals->get_fg_root(), 
511                                   mpath.str(), 
512                                   globals->get_props());
513    
514    if ( ! loaded ) {
515        SG_LOG( SG_GENERAL, SG_ALERT,
516                "Error loading materials file " << mpath.str() );
517        return false;
518    }  
519    
520    globals->set_matlib(new_matlib);    
521    return true;   
522  }
523
524
525 #if 0
526 These do_set_(some-environment-parameters) are deprecated and no longer 
527 useful/functional - Torsten Dreyer, January 2011
528 /**
529  * Set the sea level outside air temperature and assigning that to all
530  * boundary and aloft environment layers.
531  */
532 static bool
533 do_set_sea_level_degc ( double temp_sea_level_degc)
534 {
535     SGPropertyNode *node, *child;
536
537     // boundary layers
538     node = fgGetNode( "/environment/config/boundary" );
539     if ( node != NULL ) {
540       int i = 0;
541       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
542         child->setDoubleValue( "temperature-sea-level-degc",
543                                temp_sea_level_degc );
544         ++i;
545       }
546     }
547
548     // aloft layers
549     node = fgGetNode( "/environment/config/aloft" );
550     if ( node != NULL ) {
551       int i = 0;
552       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
553         child->setDoubleValue( "temperature-sea-level-degc",
554                                temp_sea_level_degc );
555         ++i;
556       }
557     }
558
559     return true;
560 }
561
562 static bool
563 do_set_sea_level_degc (const SGPropertyNode * arg)
564 {
565     return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
566 }
567
568
569 /**
570  * Set the outside air temperature at the "current" altitude by first
571  * calculating the corresponding sea level temp, and assigning that to
572  * all boundary and aloft environment layers.
573  */
574 static bool
575 do_set_oat_degc (const SGPropertyNode * arg)
576 {
577     double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
578     // check for an altitude specified in the arguments, otherwise use
579     // current aircraft altitude.
580     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
581     if ( altitude_ft == NULL ) {
582         altitude_ft = fgGetNode("/position/altitude-ft");
583     }
584
585     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
586     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
587     dummy.set_temperature_degc( oat_degc );
588     return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
589 }
590
591 /**
592  * Set the sea level outside air dewpoint and assigning that to all
593  * boundary and aloft environment layers.
594  */
595 static bool
596 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
597 {
598
599     SGPropertyNode *node, *child;
600
601     // boundary layers
602     node = fgGetNode( "/environment/config/boundary" );
603     if ( node != NULL ) {
604       int i = 0;
605       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
606         child->setDoubleValue( "dewpoint-sea-level-degc",
607                                dewpoint_sea_level_degc );
608         ++i;
609       }
610     }
611
612     // aloft layers
613     node = fgGetNode( "/environment/config/aloft" );
614     if ( node != NULL ) {
615       int i = 0;
616       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
617         child->setDoubleValue( "dewpoint-sea-level-degc",
618                                dewpoint_sea_level_degc );
619         ++i;
620       }
621     }
622
623     return true;
624 }
625
626 static bool
627 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
628 {
629     return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
630 }
631
632 /**
633  * Set the outside air dewpoint at the "current" altitude by first
634  * calculating the corresponding sea level dewpoint, and assigning
635  * that to all boundary and aloft environment layers.
636  */
637 static bool
638 do_set_dewpoint_degc (const SGPropertyNode * arg)
639 {
640     double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
641
642     // check for an altitude specified in the arguments, otherwise use
643     // current aircraft altitude.
644     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
645     if ( altitude_ft == NULL ) {
646         altitude_ft = fgGetNode("/position/altitude-ft");
647     }
648
649     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
650     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
651     dummy.set_dewpoint_degc( dewpoint_degc );
652     return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
653 }
654 #endif
655
656 /**
657  * Built-in command: toggle a bool property value.
658  *
659  * property: The name of the property to toggle.
660  */
661 static bool
662 do_property_toggle (const SGPropertyNode * arg)
663 {
664   SGPropertyNode * prop = get_prop(arg);
665   return prop->setBoolValue(!prop->getBoolValue());
666 }
667
668
669 /**
670  * Built-in command: assign a value to a property.
671  *
672  * property: the name of the property to assign.
673  * value: the value to assign; or
674  * property[1]: the property to copy from.
675  */
676 static bool
677 do_property_assign (const SGPropertyNode * arg)
678 {
679   SGPropertyNode * prop = get_prop(arg);
680   const SGPropertyNode * value = arg->getNode("value");
681
682   if (value != 0)
683       return prop->setUnspecifiedValue(value->getStringValue());
684   else
685   {
686       const SGPropertyNode * prop2 = get_prop2(arg);
687       if (prop2)
688           return prop->setUnspecifiedValue(prop2->getStringValue());
689       else
690           return false;
691   }
692 }
693
694
695 /**
696  * Built-in command: increment or decrement a property value.
697  *
698  * If the 'step' argument is present, it will be used; otherwise,
699  * the command uses 'offset' and 'factor', usually from the mouse.
700  *
701  * property: the name of the property to increment or decrement.
702  * step: the amount of the increment or decrement (default: 0).
703  * offset: offset from the current setting (used for the mouse; multiplied 
704  *         by factor)
705  * factor: scaling amount for the offset (defaults to 1).
706  * min: the minimum allowed value (default: no minimum).
707  * max: the maximum allowed value (default: no maximum).
708  * mask: 'integer' to apply only to the left of the decimal point, 
709  *       'decimal' to apply only to the right of the decimal point,
710  *       or 'all' to apply to the whole number (the default).
711  * wrap: true if the value should be wrapped when it passes min or max;
712  *       both min and max must be present for this to work (default:
713  *       false).
714  */
715 static bool
716 do_property_adjust (const SGPropertyNode * arg)
717 {
718   SGPropertyNode * prop = get_prop(arg);
719
720   double amount = 0;
721   if (arg->hasValue("step"))
722       amount = arg->getDoubleValue("step");
723   else
724       amount = (arg->getDoubleValue("factor", 1)
725                 * arg->getDoubleValue("offset"));
726           
727   double unmodifiable, modifiable;
728   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
729               &unmodifiable, &modifiable);
730   modifiable += amount;
731   limit_value(&modifiable, arg);
732
733   prop->setDoubleValue(unmodifiable + modifiable);
734
735   return true;
736 }
737
738
739 /**
740  * Built-in command: multiply a property value.
741  *
742  * property: the name of the property to multiply.
743  * factor: the amount by which to multiply.
744  * min: the minimum allowed value (default: no minimum).
745  * max: the maximum allowed value (default: no maximum).
746  * mask: 'integer' to apply only to the left of the decimal point, 
747  *       'decimal' to apply only to the right of the decimal point,
748  *       or 'all' to apply to the whole number (the default).
749  * wrap: true if the value should be wrapped when it passes min or max;
750  *       both min and max must be present for this to work (default:
751  *       false).
752  */
753 static bool
754 do_property_multiply (const SGPropertyNode * arg)
755 {
756   SGPropertyNode * prop = get_prop(arg);
757   double factor = arg->getDoubleValue("factor", 1);
758
759   double unmodifiable, modifiable;
760   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
761               &unmodifiable, &modifiable);
762   modifiable *= factor;
763   limit_value(&modifiable, arg);
764
765   prop->setDoubleValue(unmodifiable + modifiable);
766
767   return true;
768 }
769
770
771 /**
772  * Built-in command: swap two property values.
773  *
774  * property[0]: the name of the first property.
775  * property[1]: the name of the second property.
776  */
777 static bool
778 do_property_swap (const SGPropertyNode * arg)
779 {
780   SGPropertyNode * prop1 = get_prop(arg);
781   SGPropertyNode * prop2 = get_prop2(arg);
782
783                                 // FIXME: inefficient
784   const string & tmp = prop1->getStringValue();
785   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
786           prop2->setUnspecifiedValue(tmp.c_str()));
787 }
788
789
790 /**
791  * Built-in command: Set a property to an axis or other moving input.
792  *
793  * property: the name of the property to set.
794  * setting: the current input setting, usually between -1.0 and 1.0.
795  * offset: the offset to shift by, before applying the factor.
796  * factor: the factor to multiply by (use negative to reverse).
797  */
798 static bool
799 do_property_scale (const SGPropertyNode * arg)
800 {
801   SGPropertyNode * prop = get_prop(arg);
802   double setting = arg->getDoubleValue("setting");
803   double offset = arg->getDoubleValue("offset", 0.0);
804   double factor = arg->getDoubleValue("factor", 1.0);
805   bool squared = arg->getBoolValue("squared", false);
806   int power = arg->getIntValue("power", (squared ? 2 : 1));
807
808   int sign = (setting < 0 ? -1 : 1);
809
810   switch (power) {
811   case 1:
812       break;
813   case 2:
814       setting = setting * setting * sign;
815       break;
816   case 3:
817       setting = setting * setting * setting;
818       break;
819   case 4:
820       setting = setting * setting * setting * setting * sign;
821       break;
822   default:
823       setting =  pow(setting, power);
824       if ((power % 2) == 0)
825           setting *= sign;
826       break;
827   }
828
829   return prop->setDoubleValue((setting + offset) * factor);
830 }
831
832
833 /**
834  * Built-in command: cycle a property through a set of values.
835  *
836  * If the current value isn't in the list, the cycle will
837  * (re)start from the beginning.
838  *
839  * property: the name of the property to cycle.
840  * value[*]: the list of values to cycle through.
841  */
842 static bool
843 do_property_cycle (const SGPropertyNode * arg)
844 {
845     SGPropertyNode * prop = get_prop(arg);
846     std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
847     
848     bool wrap = arg->getBoolValue("wrap", true);
849     // compatible with knob/pick animations
850     int offset = arg->getIntValue("offset", 1);
851     
852     int selection = -1;
853     int nSelections = values.size();
854
855     if (nSelections < 1) {
856         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
857         return false;
858     }
859
860                                 // Try to find the current selection
861     for (int i = 0; i < nSelections; i++) {
862         if (compare_values(prop, values[i])) {
863             selection = i;
864             break;
865         }
866     }
867
868     if (selection < 0) { // default to first selection
869         selection = 0;
870     } else {
871         selection += offset;
872         if (wrap) {
873             selection = (selection + nSelections) % nSelections;
874         } else {
875             SG_CLAMP_RANGE(selection, 0, nSelections - 1);
876         }
877     }
878     
879     prop->setUnspecifiedValue(values[selection]->getStringValue());
880     return true;
881 }
882
883
884 /**
885  * Built-in command: randomize a numeric property value.
886  *
887  * property: the name of the property value to randomize.
888  * min: the minimum allowed value.
889  * max: the maximum allowed value.
890  */
891 static bool
892 do_property_randomize (const SGPropertyNode * arg)
893 {
894     SGPropertyNode * prop = get_prop(arg);
895     double min = arg->getDoubleValue("min", DBL_MIN);
896     double max = arg->getDoubleValue("max", DBL_MAX);
897     prop->setDoubleValue(sg_random() * (max - min) + min);
898     return true;
899 }
900
901 /**
902  * Built-in command: interpolate a property value over time
903  *
904  * property:        the name of the property value to interpolate.
905  * type:            the interpolation type ("numeric", "color", etc.)
906  * easing:          name of easing function (see http://easings.net/)
907  * value[0..n]      any number of constant values to interpolate
908  * time/rate[0..n]  time between each value, number of time elements must
909  *                  match those of value elements. Instead of time also rate can
910  *                  be used which automatically calculates the time to change
911  *                  the property value at the given speed.
912  * -or-
913  * property[1..n+1] any number of target values taken from named properties
914  * time/rate[0..n]  time between each value, number of time elements must
915  *                  match those of value elements. Instead of time also rate can
916  *                  be used which automatically calculates the time to change
917  *                  the property value at the given speed.
918  */
919 static bool
920 do_property_interpolate (const SGPropertyNode * arg)
921 {
922   SGPropertyNode * prop = get_prop(arg);
923   if( !prop )
924     return false;
925
926   simgear::PropertyList time_nodes = arg->getChildren("time");
927   simgear::PropertyList rate_nodes = arg->getChildren("rate");
928
929   if( !time_nodes.empty() && !rate_nodes.empty() )
930     // mustn't specify time and rate
931     return false;
932
933   simgear::PropertyList::size_type num_times = time_nodes.empty()
934                                              ? rate_nodes.size()
935                                              : time_nodes.size();
936
937   simgear::PropertyList value_nodes = arg->getChildren("value");
938   if( value_nodes.empty() )
939   {
940     simgear::PropertyList prop_nodes = arg->getChildren("property");
941
942     // must have one more property node
943     if( prop_nodes.size() != num_times + 1 )
944       return false;
945
946     value_nodes.reserve(num_times);
947     for( size_t i = 1; i < prop_nodes.size(); ++i )
948       value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
949   }
950
951   // must match
952   if( value_nodes.size() != num_times )
953     return false;
954
955   double_list deltas;
956   deltas.reserve(num_times);
957
958   if( !time_nodes.empty() )
959   {
960     for( size_t i = 0; i < num_times; ++i )
961       deltas.push_back( time_nodes[i]->getDoubleValue() );
962   }
963   else
964   {
965     for( size_t i = 0; i < num_times; ++i )
966     {
967       // TODO calculate delta based on property type
968       double delta = value_nodes[i]->getDoubleValue()
969                    - ( i > 0
970                      ? value_nodes[i - 1]->getDoubleValue()
971                      : prop->getDoubleValue()
972                      );
973       deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
974     }
975   }
976
977   return prop->interpolate
978   (
979     arg->getStringValue("type", "numeric"),
980     value_nodes,
981     deltas,
982     arg->getStringValue("easing", "linear")
983   );
984 }
985
986 /**
987  * Built-in command: reinit the data logging system based on the
988  * current contents of the /logger tree.
989  */
990 static bool
991 do_data_logging_commit (const SGPropertyNode * arg)
992 {
993     FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
994     log->reinit();
995     return true;
996 }
997
998 /**
999  * Built-in command: Add a dialog to the GUI system.  Does *not*
1000  * display the dialog.  The property node should have the same format
1001  * as a dialog XML configuration.  It must include:
1002  *
1003  * name: the name of the GUI dialog for future reference.
1004  */
1005 static bool
1006 do_dialog_new (const SGPropertyNode * arg)
1007 {
1008     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1009     if (!gui) {
1010       return false;
1011     }
1012   
1013     // Note the casting away of const: this is *real*.  Doing a
1014     // "dialog-apply" command later on will mutate this property node.
1015     // I'm not convinced that this isn't the Right Thing though; it
1016     // allows client to create a node, pass it to dialog-new, and get
1017     // the values back from the dialog by reading the same node.
1018     // Perhaps command arguments are not as "const" as they would
1019     // seem?
1020     gui->newDialog((SGPropertyNode*)arg);
1021     return true;
1022 }
1023
1024 /**
1025  * Built-in command: Show an XML-configured dialog.
1026  *
1027  * dialog-name: the name of the GUI dialog to display.
1028  */
1029 static bool
1030 do_dialog_show (const SGPropertyNode * arg)
1031 {
1032     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1033     gui->showDialog(arg->getStringValue("dialog-name"));
1034     return true;
1035 }
1036
1037
1038 /**
1039  * Built-in Command: Hide the active XML-configured dialog.
1040  */
1041 static bool
1042 do_dialog_close (const SGPropertyNode * arg)
1043 {
1044     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1045     if(arg->hasValue("dialog-name"))
1046         return gui->closeDialog(arg->getStringValue("dialog-name"));
1047     return gui->closeActiveDialog();
1048 }
1049
1050
1051 /**
1052  * Update a value in the active XML-configured dialog.
1053  *
1054  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1055  */
1056 static bool
1057 do_dialog_update (const SGPropertyNode * arg)
1058 {
1059     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1060     FGDialog * dialog;
1061     if (arg->hasValue("dialog-name"))
1062         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1063     else
1064         dialog = gui->getActiveDialog();
1065
1066     if (dialog != 0) {
1067         dialog->updateValues(arg->getStringValue("object-name"));
1068         return true;
1069     } else {
1070         return false;
1071     }
1072 }
1073
1074 static bool
1075 do_open_browser (const SGPropertyNode * arg)
1076 {
1077     string path;
1078     if (arg->hasValue("path"))
1079         path = arg->getStringValue("path");
1080     else
1081     if (arg->hasValue("url"))
1082         path = arg->getStringValue("url");
1083     else
1084         return false;
1085
1086     return openBrowser(path);
1087 }
1088
1089 /**
1090  * Apply a value in the active XML-configured dialog.
1091  *
1092  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1093  */
1094 static bool
1095 do_dialog_apply (const SGPropertyNode * arg)
1096 {
1097     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1098     FGDialog * dialog;
1099     if (arg->hasValue("dialog-name"))
1100         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1101     else
1102         dialog = gui->getActiveDialog();
1103
1104     if (dialog != 0) {
1105         dialog->applyValues(arg->getStringValue("object-name"));
1106         return true;
1107     } else {
1108         return false;
1109     }
1110 }
1111
1112
1113 /**
1114  * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1115  * unlike reinit().
1116  */
1117 static bool
1118 do_gui_redraw (const SGPropertyNode * arg)
1119 {
1120     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1121     gui->redraw();
1122     return true;
1123 }
1124
1125
1126 /**
1127  * Adds model to the scenery. The path to the added branch (/models/model[*])
1128  * is returned in property "property".
1129  */
1130 static bool
1131 do_add_model (const SGPropertyNode * arg)
1132 {
1133     SGPropertyNode * model = fgGetNode("models", true);
1134     int i;
1135     for (i = 0; model->hasChild("model",i); i++);
1136     model = model->getChild("model", i, true);
1137     copyProperties(arg, model);
1138     if (model->hasValue("elevation-m"))
1139         model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1140                 * SG_METER_TO_FEET);
1141     model->getNode("load", true);
1142     model->removeChildren("load");
1143     const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1144     return true;
1145 }
1146
1147 /**
1148  * Built-in command: play an audio message (i.e. a wav file) This is
1149  * fire and forget.  Call this once per message and it will get dumped
1150  * into a queue.  Messages are played sequentially so they do not
1151  * overlap.
1152  */
1153 static bool
1154 do_play_audio_sample (const SGPropertyNode * arg)
1155 {
1156     SGSoundMgr *smgr = globals->get_soundmgr();
1157     if (!smgr) {
1158         SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1159         return false;
1160     }
1161   
1162     string path = arg->getStringValue("path");
1163     string file = arg->getStringValue("file");
1164     float volume = arg->getFloatValue("volume");
1165     // cout << "playing " << path << " / " << file << endl;
1166     try {
1167         static FGSampleQueue *queue = 0;
1168         if ( !queue ) {
1169            queue = new FGSampleQueue(smgr, "chatter");
1170            queue->tie_to_listener();
1171         }
1172
1173         SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1174         msg->set_volume( volume );
1175         queue->add( msg );
1176
1177         return true;
1178
1179     } catch (const sg_io_exception&) {
1180         SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1181                 "failed to load" << path << '/' << file);
1182         return false;
1183     }
1184 }
1185
1186 /**
1187  * Built-in command: commit presets (read from in /sim/presets/)
1188  */
1189 static bool
1190 do_presets_commit (const SGPropertyNode * arg)
1191 {
1192     if (fgGetBool("/sim/initialized", false)) {
1193       fgReInitSubsystems();
1194     } else {
1195       // Nasal can trigger this during initial init, which confuses
1196       // the logic in ReInitSubsystems, since initial state has not been
1197       // saved at that time. Short-circuit everything here.
1198       flightgear::initPosition();
1199     }
1200     
1201     return true;
1202 }
1203
1204 /**
1205  * Built-in command: set log level (0 ... 7)
1206  */
1207 static bool
1208 do_log_level (const SGPropertyNode * arg)
1209 {
1210    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1211
1212    return true;
1213 }
1214
1215 /*
1216 static bool
1217 do_decrease_visibility (const SGPropertyNode * arg)
1218 {
1219     Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1220     return true;
1221 }
1222  
1223 static bool
1224 do_increase_visibility (const SGPropertyNode * arg)
1225 {
1226     Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1227     return true;
1228 }
1229 */
1230 /**
1231  * An fgcommand to allow loading of xml files via nasal,
1232  * the xml file's structure will be made available within
1233  * a property tree node defined under argument "targetnode",
1234  * or in the given argument tree under "data" otherwise.
1235  *
1236  * @param filename a string to hold the complete path & filename of an XML file
1237  * @param targetnode a string pointing to a location within the property tree
1238  * where to store the parsed XML file. If <targetnode> is undefined, then the
1239  * file contents are stored under a node <data> in the argument tree.
1240  */
1241
1242 static bool
1243 do_load_xml_to_proptree(const SGPropertyNode * arg)
1244 {
1245     SGPath file(arg->getStringValue("filename"));
1246     if (file.str().empty())
1247         return false;
1248
1249     if (file.extension() != "xml")
1250         file.concat(".xml");
1251     
1252     std::string icao = arg->getStringValue("icao");
1253     if (icao.empty()) {
1254         if (file.isRelative()) {
1255           SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1256           if (!absPath.isNull())
1257               file = absPath;
1258           else
1259           {
1260               SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"  
1261                           << file.str() << "'.");
1262               return false;
1263           }
1264         }
1265     } else {
1266         if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1267           SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1268             << file.str() << " at ICAO:" << icao);
1269           return false;
1270         }
1271     }
1272     
1273     if (!fgValidatePath(file.c_str(), false)) {
1274         SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1275                 "(unauthorized access)");
1276         return false;
1277     }
1278
1279     SGPropertyNode *targetnode;
1280     if (arg->hasValue("targetnode"))
1281         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1282     else
1283         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1284
1285     try {
1286         readProperties(file.c_str(), targetnode, true);
1287     } catch (const sg_exception &e) {
1288         SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1289         return false;
1290     }
1291
1292     return true;
1293 }
1294
1295 class RemoteXMLRequest : public simgear::HTTP::Request
1296 {
1297 public:
1298     SGPropertyNode_ptr _complete;
1299     SGPropertyNode_ptr _status;
1300     SGPropertyNode_ptr _failed;
1301     SGPropertyNode_ptr _target;
1302     string propsData;
1303     mutable string _requestBody;
1304     int _requestBodyLength;
1305     string _method;
1306     
1307     RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1308         simgear::HTTP::Request(url),
1309         _target(targetNode),
1310         _requestBodyLength(-1),
1311         _method("GET")
1312     {
1313     }
1314     
1315     void setCompletionProp(SGPropertyNode_ptr p)
1316     {
1317         _complete = p;
1318     }
1319     
1320     void setStatusProp(SGPropertyNode_ptr p)
1321     {
1322         _status = p;
1323     }
1324     
1325     void setFailedProp(SGPropertyNode_ptr p)
1326     {
1327         _failed = p;
1328     }
1329   
1330     void setRequestData(const SGPropertyNode* body)
1331     {
1332         _method = "POST";
1333         std::stringstream buf;
1334         writeProperties(buf, body, true);
1335         _requestBody = buf.str();
1336         _requestBodyLength = _requestBody.size();
1337     }
1338     
1339     virtual std::string method() const
1340     {
1341         return _method;
1342     }
1343 protected:
1344     virtual int requestBodyLength() const
1345     {
1346         return _requestBodyLength;
1347     }
1348     
1349     virtual void getBodyData(char* s, int& count) const
1350     {
1351         int toRead = std::min(count, (int) _requestBody.size());
1352         memcpy(s, _requestBody.c_str(), toRead);
1353         count = toRead;
1354         _requestBody = _requestBody.substr(count);
1355     }
1356     
1357     virtual std::string requestBodyType() const
1358     {
1359         return "application/xml";
1360     }
1361     
1362     virtual void gotBodyData(const char* s, int n)
1363     {
1364         propsData += string(s, n);
1365     }
1366     
1367     virtual void failed()
1368     {
1369         SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1370         if (_failed) {
1371             _failed->setBoolValue(true);
1372         }
1373     }
1374     
1375     virtual void responseComplete()
1376     {
1377         simgear::HTTP::Request::responseComplete();
1378         
1379         int response = responseCode();
1380         bool failed = false;
1381         if (response == 200) {
1382             try {
1383                 const char* buffer = propsData.c_str();
1384                 readProperties(buffer, propsData.size(), _target, true);
1385             } catch (const sg_exception &e) {
1386                 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1387                 failed = true;
1388                 response = 406; // 'not acceptable', anything better?
1389             }
1390         } else {
1391             failed = true;
1392         }
1393     // now the response data is output, signal Nasal / listeners
1394         if (_complete) _complete->setBoolValue(true);
1395         if (_status) _status->setIntValue(response);
1396         if (_failed && failed) _failed->setBoolValue(true);
1397     }
1398 };
1399
1400
1401 static bool
1402 do_load_xml_from_url(const SGPropertyNode * arg)
1403 {
1404     FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1405     if (!http) {
1406         SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1407         return false;
1408     }
1409   
1410     std::string url(arg->getStringValue("url"));
1411     if (url.empty())
1412         return false;
1413         
1414     SGPropertyNode *targetnode;
1415     if (arg->hasValue("targetnode"))
1416         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1417     else
1418         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1419     
1420     RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1421     
1422     if (arg->hasChild("body"))
1423         req->setRequestData(arg->getChild("body"));
1424     
1425 // connect up optional reporting properties
1426     if (arg->hasValue("complete")) 
1427         req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1428     if (arg->hasValue("failure")) 
1429         req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1430     if (arg->hasValue("status")) 
1431         req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1432         
1433     http->makeRequest(req);
1434     return true;
1435 }
1436
1437
1438 /**
1439  * An fgcommand to allow saving of xml files via nasal,
1440  * the file's structure will be determined based on what's
1441  * encountered in the passed (source) property tree node
1442  *
1443  * @param filename a string to hold the complete path & filename of the (new)
1444  * XML file
1445  * @param sourcenode a string pointing to a location within the property tree
1446  * where to find the nodes that should be written recursively into an XML file
1447  * @param data if no sourcenode is given, then the file contents are taken from
1448  * the argument tree's "data" node.
1449  */
1450
1451 static bool
1452 do_save_xml_from_proptree(const SGPropertyNode * arg)
1453 {
1454     SGPath file(arg->getStringValue("filename"));
1455     if (file.str().empty())
1456         return false;
1457
1458     if (file.extension() != "xml")
1459         file.concat(".xml");
1460
1461     if (!fgValidatePath(file.c_str(), true)) {
1462         SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1463                 "(unauthorized access)");
1464         return false;
1465     }
1466
1467     SGPropertyNode *sourcenode;
1468     if (arg->hasValue("sourcenode"))
1469         sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1470     else if (arg->getNode("data", false))
1471         sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1472     else
1473         return false;
1474
1475     try {
1476         writeProperties (file.c_str(), sourcenode, true);
1477     } catch (const sg_exception &e) {
1478         SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1479         return false;
1480     }
1481
1482     return true;
1483 }
1484
1485 static bool
1486 do_press_cockpit_button (const SGPropertyNode *arg)
1487 {
1488   const char *prefix = arg->getStringValue("prefix");
1489
1490   if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1491     return true;
1492
1493   string prop = string(prefix) + "-button";
1494   double value;
1495
1496   if (arg->getBoolValue("latching"))
1497     value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1498   else
1499     value = 1;
1500
1501   fgSetDouble(prop.c_str(), value);
1502   fgSetBool(arg->getStringValue("discrete"), value > 0);
1503
1504   return true;
1505 }
1506
1507 static bool
1508 do_release_cockpit_button (const SGPropertyNode *arg)
1509 {
1510   const char *prefix = arg->getStringValue("prefix");
1511
1512   if (arg->getBoolValue("guarded")) {
1513     string prop = string(prefix) + "-guard";
1514     if (fgGetDouble(prop.c_str()) < 1) {
1515       fgSetDouble(prop.c_str(), 1);
1516       return true;
1517     }
1518   }
1519
1520   if (! arg->getBoolValue("latching")) {
1521     fgSetDouble((string(prefix) + "-button").c_str(), 0);
1522     fgSetBool(arg->getStringValue("discrete"), false);
1523   }
1524
1525   return true;
1526 }
1527
1528 // Optional profiling commands using gperftools:
1529 // http://code.google.com/p/gperftools/
1530
1531 #ifndef FG_HAVE_GPERFTOOLS
1532 static void
1533 no_profiling_support()
1534 {
1535   SG_LOG
1536   (
1537     SG_GENERAL,
1538     SG_WARN,
1539     "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1540   );
1541 }
1542 #endif
1543
1544 static bool
1545 do_profiler_start(const SGPropertyNode *arg)
1546 {
1547 #ifdef FG_HAVE_GPERFTOOLS
1548   const char *filename = arg->getStringValue("filename", "fgfs.profile");
1549   ProfilerStart(filename);
1550   return true;
1551 #else
1552   no_profiling_support();
1553   return false;
1554 #endif
1555 }
1556
1557 static bool
1558 do_profiler_stop(const SGPropertyNode *arg)
1559 {
1560 #ifdef FG_HAVE_GPERFTOOLS
1561   ProfilerStop();
1562   return true;
1563 #else
1564   no_profiling_support();
1565   return false;
1566 #endif
1567 }
1568
1569
1570 ////////////////////////////////////////////////////////////////////////
1571 // Command setup.
1572 ////////////////////////////////////////////////////////////////////////
1573
1574
1575 /**
1576  * Table of built-in commands.
1577  *
1578  * New commands do not have to be added here; any module in the application
1579  * can add a new command using globals->get_commands()->addCommand(...).
1580  */
1581 static struct {
1582   const char * name;
1583   SGCommandMgr::command_t command;
1584 } built_ins [] = {
1585     { "null", do_null },
1586     { "nasal", do_nasal },
1587     { "exit", do_exit },
1588     { "reset", do_reset },
1589     { "pause", do_pause },
1590     { "load", do_load },
1591     { "save", do_save },
1592     { "save-tape", do_save_tape },
1593     { "load-tape", do_load_tape },
1594     { "panel-load", do_panel_load },
1595     { "preferences-load", do_preferences_load },
1596     { "toggle-fullscreen", do_toggle_fullscreen },
1597     { "view-cycle", do_view_cycle },
1598     { "screen-capture", do_screen_capture },
1599     { "hires-screen-capture", do_hires_screen_capture },
1600     { "tile-cache-reload", do_tile_cache_reload },
1601     /*
1602     { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1603     { "set-outside-air-temp-degc", do_set_oat_degc },
1604     { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1605     { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1606     */
1607     { "property-toggle", do_property_toggle },
1608     { "property-assign", do_property_assign },
1609     { "property-adjust", do_property_adjust },
1610     { "property-multiply", do_property_multiply },
1611     { "property-swap", do_property_swap },
1612     { "property-scale", do_property_scale },
1613     { "property-cycle", do_property_cycle },
1614     { "property-randomize", do_property_randomize },
1615     { "property-interpolate", do_property_interpolate },
1616     { "data-logging-commit", do_data_logging_commit },
1617     { "dialog-new", do_dialog_new },
1618     { "dialog-show", do_dialog_show },
1619     { "dialog-close", do_dialog_close },
1620     { "dialog-update", do_dialog_update },
1621     { "dialog-apply", do_dialog_apply },
1622     { "open-browser", do_open_browser },
1623     { "gui-redraw", do_gui_redraw },
1624     { "add-model", do_add_model },
1625     { "play-audio-sample", do_play_audio_sample },
1626     { "presets-commit", do_presets_commit },
1627     { "log-level", do_log_level },
1628     { "replay", do_replay },
1629     /*
1630     { "decrease-visibility", do_decrease_visibility },
1631     { "increase-visibility", do_increase_visibility },
1632     */
1633     { "loadxml", do_load_xml_to_proptree},
1634     { "savexml", do_save_xml_from_proptree },
1635     { "xmlhttprequest", do_load_xml_from_url },
1636     { "press-cockpit-button", do_press_cockpit_button },
1637     { "release-cockpit-button", do_release_cockpit_button },
1638     { "dump-scenegraph", do_dump_scene_graph },
1639     { "dump-terrainbranch", do_dump_terrain_branch },
1640     { "print-visible-scene", do_print_visible_scene_info },
1641     { "reload-shaders", do_reload_shaders },
1642     { "reload-materials", do_materials_reload },
1643
1644     { "profiler-start", do_profiler_start },
1645     { "profiler-stop",  do_profiler_stop },
1646
1647     { 0, 0 }                    // zero-terminated
1648 };
1649
1650
1651 /**
1652  * Initialize the default built-in commands.
1653  *
1654  * Other commands may be added by other parts of the application.
1655  */
1656 void
1657 fgInitCommands ()
1658 {
1659   SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1660   for (int i = 0; built_ins[i].name != 0; i++) {
1661     SG_LOG(SG_GENERAL, SG_BULK, "  " << built_ins[i].name);
1662     globals->get_commands()->addCommand(built_ins[i].name,
1663                                         built_ins[i].command);
1664   }
1665
1666   typedef bool (*dummy)();
1667   fgTie( "/command/view/next", dummy(0), do_view_next );
1668   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1669
1670   SGPropertyNode* profiler_available =
1671     globals->get_props()->getNode("/sim/debug/profiler-available", true);
1672 #ifdef FG_HAVE_GPERFTOOLS
1673   profiler_available->setBoolValue(true);
1674 #else
1675   profiler_available->setBoolValue(false);
1676 #endif
1677   profiler_available->setAttributes(SGPropertyNode::READ);
1678 }
1679
1680 // end of fg_commands.cxx