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