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