]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Land the GPS/route-manager re-write. Many things are better, many other things will...
[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
24 #include <Cockpit/panel.hxx>
25 #include <Cockpit/panel_io.hxx>
26 #include <Cockpit/hud.hxx>
27 #include <Environment/environment.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/tilemgr.hxx>
34 #include <Scenery/scenery.hxx>
35 #include <Scripting/NasalSys.hxx>
36 #include <Sound/fg_fx.hxx>
37 #include <Time/sunsolver.hxx>
38 #include <Time/tmp.hxx>
39
40 #include "fg_init.hxx"
41 #include "fg_io.hxx"
42 #include "fg_os.hxx"
43 #include "fg_commands.hxx"
44 #include "fg_props.hxx"
45 #include "globals.hxx"
46 #include "logger.hxx"
47 #include "util.hxx"
48 #include "viewmgr.hxx"
49 #include "main.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 _MSC_VER
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     fgExit(arg->getIntValue("status", 0));
213     return true;
214 }
215
216
217 /**
218  * Reset FlightGear (Shift-Escape or Menu->File->Reset)
219  */
220 static bool
221 do_reset (const SGPropertyNode * arg)
222 {
223     reInit();
224     return true;
225 }
226
227
228 /**
229  * Built-in command: reinitialize one or more subsystems.
230  *
231  * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
232  * none is specified, reinitialize all of them.
233  */
234 static bool
235 do_reinit (const SGPropertyNode * arg)
236 {
237     bool result = true;
238
239     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
240     if (subsystems.size() == 0) {
241         globals->get_subsystem_mgr()->reinit();
242     } else {
243         for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
244             const char * name = subsystems[i]->getStringValue();
245             SGSubsystem * subsystem = globals->get_subsystem(name);
246             if (subsystem == 0) {
247                 result = false;
248                 SG_LOG( SG_GENERAL, SG_ALERT,
249                         "Subsystem " << name << "not found" );
250             } else {
251                 subsystem->reinit();
252             }
253         }
254     }
255
256     globals->get_event_mgr()->reinit();
257
258     return result;
259 }
260
261 #if 0
262   //
263   // these routines look useful ??? but are never used in the code ???
264   //
265
266 /**
267  * Built-in command: suspend one or more subsystems.
268  *
269  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
270  */
271 static bool
272 do_suspend (const SGPropertyNode * arg)
273 {
274     bool result = true;
275
276     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
277     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
278         const char * name = subsystems[i]->getStringValue();
279         SGSubsystem * subsystem = globals->get_subsystem(name);
280         if (subsystem == 0) {
281             result = false;
282             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
283         } else {
284             subsystem->suspend();
285         }
286     }
287     return result;
288 }
289
290 /**
291  * Built-in command: suspend one or more subsystems.
292  *
293  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
294  */
295 static bool
296 do_resume (const SGPropertyNode * arg)
297 {
298     bool result = true;
299
300     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
301     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
302         const char * name = subsystems[i]->getStringValue();
303         SGSubsystem * subsystem = globals->get_subsystem(name);
304         if (subsystem == 0) {
305             result = false;
306             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
307         } else {
308             subsystem->resume();
309         }
310     }
311     return result;
312 }
313
314 #endif
315
316
317 /**
318  * Built-in command: load flight.
319  *
320  * file (optional): the name of the file to load (relative to current
321  *   directory).  Defaults to "fgfs.sav"
322  */
323 static bool
324 do_load (const SGPropertyNode * arg)
325 {
326     string file = arg->getStringValue("file", "fgfs.sav");
327     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
328         file += ".sav";
329
330     if (!fgValidatePath(file.c_str(), false)) {
331         SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
332                 "(unauthorized access)");
333         return false;
334     }
335
336     ifstream input(file.c_str());
337     if (input.good() && fgLoadFlight(input)) {
338         input.close();
339         SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
340         return true;
341     } else {
342         SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
343         return false;
344     }
345 }
346
347
348 /**
349  * Built-in command: save flight.
350  *
351  * file (optional): the name of the file to save (relative to the
352  * current directory).  Defaults to "fgfs.sav".
353  */
354 static bool
355 do_save (const SGPropertyNode * arg)
356 {
357     string file = arg->getStringValue("file", "fgfs.sav");
358     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
359         file += ".sav";
360
361     if (!fgValidatePath(file.c_str(), false)) {
362         SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
363                 "(unauthorized access)");
364         return false;
365     }
366
367     bool write_all = arg->getBoolValue("write-all", false);
368     SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
369     ofstream output(file.c_str());
370     if (output.good() && fgSaveFlight(output, write_all)) {
371         output.close();
372         SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
373         return true;
374     } else {
375         SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
376         return false;
377     }
378 }
379
380
381 /**
382  * Built-in command: (re)load the panel.
383  *
384  * path (optional): the file name to load the panel from 
385  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
386  * and if that's unspecified, to "Panels/Default/default.xml".
387  */
388 static bool
389 do_panel_load (const SGPropertyNode * arg)
390 {
391   string panel_path =
392     arg->getStringValue("path",
393                         fgGetString("/sim/panel/path",
394                                     "Panels/Default/default.xml"));
395   FGPanel * new_panel = fgReadPanel(panel_path);
396   if (new_panel == 0) {
397     SG_LOG(SG_INPUT, SG_ALERT,
398            "Error reading new panel from " << panel_path);
399     return false;
400   }
401   SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
402   globals->get_current_panel()->unbind();
403   delete globals->get_current_panel();
404   globals->set_current_panel( new_panel );
405   globals->get_current_panel()->bind();
406   return true;
407 }
408
409
410 /**
411  * Built-in command: pass a mouse click to the panel.
412  *
413  * button: the mouse button number, zero-based.
414  * is-down: true if the button is down, false if it is up.
415  * x-pos: the x position of the mouse click.
416  * y-pos: the y position of the mouse click.
417  */
418 static bool
419 do_panel_mouse_click (const SGPropertyNode * arg)
420 {
421   if (globals->get_current_panel() != 0)
422     return globals->get_current_panel()
423       ->doMouseAction(arg->getIntValue("button"),
424                       arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
425                       arg->getIntValue("x-pos"),
426                       arg->getIntValue("y-pos"));
427   else
428     return false;
429 }
430
431
432 /**
433  * Built-in command: (re)load preferences.
434  *
435  * path (optional): the file name to load the panel from (relative
436  * to FG_ROOT). Defaults to "preferences.xml".
437  */
438 static bool
439 do_preferences_load (const SGPropertyNode * arg)
440 {
441   try {
442     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
443                 globals->get_props());
444   } catch (const sg_exception &e) {
445     guiErrorMessage("Error reading global preferences: ", e);
446     return false;
447   }
448   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
449   return true;
450 }
451
452
453 static void
454 fix_hud_visibility()
455 {
456   if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
457       globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
458       if ( globals->get_viewmgr()->get_current() == 1 ) {
459           globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
460       }
461   }
462 }
463
464 static void
465 do_view_next( bool )
466 {
467     globals->get_current_view()->setHeadingOffset_deg(0.0);
468     globals->get_viewmgr()->next_view();
469     fix_hud_visibility();
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     fix_hud_visibility();
478 }
479
480 /**
481  * Built-in command: cycle view.
482  */
483 static bool
484 do_view_cycle (const SGPropertyNode * arg)
485 {
486   globals->get_current_view()->setHeadingOffset_deg(0.0);
487   globals->get_viewmgr()->next_view();
488   fix_hud_visibility();
489   return true;
490 }
491
492 /**
493  * Built-in command: capture screen.
494  */
495 static bool
496 do_screen_capture (const SGPropertyNode * arg)
497 {
498   return fgDumpSnapShot();
499 }
500
501 static bool
502 do_reload_shaders (const SGPropertyNode*)
503 {
504     simgear::reload_shaders();
505     return true;
506 }
507
508 static bool
509 do_dump_scene_graph (const SGPropertyNode*)
510 {
511     fgDumpSceneGraph();
512     return true;
513 }
514
515 static bool
516 do_dump_terrain_branch (const SGPropertyNode*)
517 {
518     fgDumpTerrainBranch();
519
520     double lon_deg = fgGetDouble("/position/longitude-deg");
521     double lat_deg = fgGetDouble("/position/latitude-deg");
522     SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
523     SGVec3d zero = SGVec3d::fromGeod(geodPos);
524
525     SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
526     SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
527     SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
528
529     return true;
530 }
531
532 /**
533  * Built-in command: hires capture screen.
534  */
535 static bool
536 do_hires_screen_capture (const SGPropertyNode * arg)
537 {
538   fgHiResDump();
539   return true;
540 }
541
542
543 /**
544  * Reload the tile cache.
545  */
546 static bool
547 do_tile_cache_reload (const SGPropertyNode * arg)
548 {
549     static const SGPropertyNode *master_freeze
550         = fgGetNode("/sim/freeze/master");
551     bool freeze = master_freeze->getBoolValue();
552     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
553     if ( !freeze ) {
554         fgSetBool("/sim/freeze/master", true);
555     }
556     if ( globals->get_tile_mgr()->init() ) {
557         // Load the local scenery data
558         double visibility_meters = fgGetDouble("/environment/visibility-m");
559         globals->get_tile_mgr()->update( visibility_meters );
560     } else {
561         SG_LOG( SG_GENERAL, SG_ALERT, 
562                 "Error in Tile Manager initialization!" );
563         exit(-1);
564     }
565     if ( !freeze ) {
566         fgSetBool("/sim/freeze/master", false);
567     }
568     return true;
569 }
570
571
572 /**
573  * Set the sea level outside air temperature and assigning that to all
574  * boundary and aloft environment layers.
575  */
576 static bool
577 do_set_sea_level_degc (const SGPropertyNode * arg)
578 {
579     double temp_sea_level_degc = arg->getDoubleValue("temp-degc", 15.0);
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
609 /**
610  * Set the outside air temperature at the "current" altitude by first
611  * calculating the corresponding sea level temp, and assigning that to
612  * all boundary and aloft environment layers.
613  */
614 static bool
615 do_set_oat_degc (const SGPropertyNode * arg)
616 {
617     const string &temp_str = arg->getStringValue("temp-degc", "15.0");
618
619     // check for an altitude specified in the arguments, otherwise use
620     // current aircraft altitude.
621     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
622     if ( altitude_ft == NULL ) {
623         altitude_ft = fgGetNode("/position/altitude-ft");
624     }
625
626     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
627     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
628     dummy.set_temperature_degc( atof( temp_str.c_str() ) );
629     double temp_sea_level_degc = dummy.get_temperature_sea_level_degc();
630
631     //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
632     //cout << "Temp at alt (C) = " << atof( temp_str.c_str() ) << endl;
633     //cout << "Temp sea level (C) = " << temp_sea_level_degc << endl;
634  
635     SGPropertyNode *node, *child;
636
637     // boundary layers
638     node = fgGetNode( "/environment/config/boundary" );
639     if ( node != NULL ) {
640       int i = 0;
641       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
642         child->setDoubleValue( "temperature-sea-level-degc",
643                                temp_sea_level_degc );
644         ++i;
645       }
646     }
647
648     // aloft layers
649     node = fgGetNode( "/environment/config/aloft" );
650     if ( node != NULL ) {
651       int i = 0;
652       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
653         child->setDoubleValue( "temperature-sea-level-degc",
654                                temp_sea_level_degc );
655         ++i;
656       }
657     }
658
659     return true;
660 }
661
662 /**
663  * Set the sea level outside air dewpoint and assigning that to all
664  * boundary and aloft environment layers.
665  */
666 static bool
667 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
668 {
669     double dewpoint_sea_level_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
670
671     SGPropertyNode *node, *child;
672
673     // boundary layers
674     node = fgGetNode( "/environment/config/boundary" );
675     if ( node != NULL ) {
676       int i = 0;
677       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
678         child->setDoubleValue( "dewpoint-sea-level-degc",
679                                dewpoint_sea_level_degc );
680         ++i;
681       }
682     }
683
684     // aloft layers
685     node = fgGetNode( "/environment/config/aloft" );
686     if ( node != NULL ) {
687       int i = 0;
688       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
689         child->setDoubleValue( "dewpoint-sea-level-degc",
690                                dewpoint_sea_level_degc );
691         ++i;
692       }
693     }
694
695     return true;
696 }
697
698
699 /**
700  * Set the outside air dewpoint at the "current" altitude by first
701  * calculating the corresponding sea level dewpoint, and assigning
702  * that to all boundary and aloft environment layers.
703  */
704 static bool
705 do_set_dewpoint_degc (const SGPropertyNode * arg)
706 {
707     const string &dewpoint_str = arg->getStringValue("dewpoint-degc", "5.0");
708
709     // check for an altitude specified in the arguments, otherwise use
710     // current aircraft altitude.
711     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
712     if ( altitude_ft == NULL ) {
713         altitude_ft = fgGetNode("/position/altitude-ft");
714     }
715
716     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
717     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
718     dummy.set_dewpoint_degc( atof( dewpoint_str.c_str() ) );
719     double dewpoint_sea_level_degc = dummy.get_dewpoint_sea_level_degc();
720
721     //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
722     //cout << "Dewpoint at alt (C) = " << atof( dewpoint_str.c_str() ) << endl;
723     //cout << "Dewpoint at sea level (C) = " << dewpoint_sea_level_degc << endl;
724  
725     SGPropertyNode *node, *child;
726
727     // boundary layers
728     node = fgGetNode( "/environment/config/boundary" );
729     if ( node != NULL ) {
730       int i = 0;
731       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
732         child->setDoubleValue( "dewpoint-sea-level-degc",
733                                dewpoint_sea_level_degc );
734         ++i;
735       }
736     }
737
738     // aloft layers
739     node = fgGetNode( "/environment/config/aloft" );
740     if ( node != NULL ) {
741       int i = 0;
742       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
743         child->setDoubleValue( "dewpoint-sea-level-degc",
744                                dewpoint_sea_level_degc );
745         ++i;
746       }
747     }
748
749     return true;
750 }
751
752 /**
753  * Update the lighting manually.
754  */
755 static bool
756 do_timeofday (const SGPropertyNode * arg)
757 {
758     const string &offset_type = arg->getStringValue("timeofday", "noon");
759
760     static const SGPropertyNode *longitude
761         = fgGetNode("/position/longitude-deg");
762     static const SGPropertyNode *latitude
763         = fgGetNode("/position/latitude-deg");
764     static const SGPropertyNode *cur_time_override
765         = fgGetNode("/sim/time/cur-time-override", true);
766
767     int orig_warp = globals->get_warp();
768     SGTime *t = globals->get_time_params();
769     time_t cur_time = t->get_cur_time();
770     // cout << "cur_time = " << cur_time << endl;
771     // cout << "orig_warp = " << orig_warp << endl;
772
773     int warp = 0;
774     if ( offset_type == "real" ) {
775         warp = -orig_warp;
776     } else if ( offset_type == "dawn" ) {
777         warp = fgTimeSecondsUntilSunAngle( cur_time,
778                                            longitude->getDoubleValue()
779                                              * SGD_DEGREES_TO_RADIANS,
780                                            latitude->getDoubleValue()
781                                              * SGD_DEGREES_TO_RADIANS,
782                                            90.0, true ); 
783     } else if ( offset_type == "morning" ) {
784         warp = fgTimeSecondsUntilSunAngle( cur_time,
785                                            longitude->getDoubleValue()
786                                              * SGD_DEGREES_TO_RADIANS,
787                                            latitude->getDoubleValue()
788                                              * SGD_DEGREES_TO_RADIANS,
789                                            75.0, true ); 
790     } else if ( offset_type == "noon" ) {
791         warp = fgTimeSecondsUntilSunAngle( cur_time,
792                                            longitude->getDoubleValue()
793                                              * SGD_DEGREES_TO_RADIANS,
794                                            latitude->getDoubleValue()
795                                              * SGD_DEGREES_TO_RADIANS,
796                                            0.0, true ); 
797     } else if ( offset_type == "afternoon" ) {
798         warp = fgTimeSecondsUntilSunAngle( cur_time,
799                                            longitude->getDoubleValue()
800                                              * SGD_DEGREES_TO_RADIANS,
801                                            latitude->getDoubleValue()
802                                              * SGD_DEGREES_TO_RADIANS,
803                                            60.0, false ); 
804      } else if ( offset_type == "dusk" ) {
805         warp = fgTimeSecondsUntilSunAngle( cur_time,
806                                            longitude->getDoubleValue()
807                                              * SGD_DEGREES_TO_RADIANS,
808                                            latitude->getDoubleValue()
809                                              * SGD_DEGREES_TO_RADIANS,
810                                            90.0, false ); 
811      } else if ( offset_type == "evening" ) {
812         warp = fgTimeSecondsUntilSunAngle( cur_time,
813                                            longitude->getDoubleValue()
814                                              * SGD_DEGREES_TO_RADIANS,
815                                            latitude->getDoubleValue()
816                                              * SGD_DEGREES_TO_RADIANS,
817                                            100.0, false ); 
818     } else if ( offset_type == "midnight" ) {
819         warp = fgTimeSecondsUntilSunAngle( cur_time,
820                                            longitude->getDoubleValue()
821                                              * SGD_DEGREES_TO_RADIANS,
822                                            latitude->getDoubleValue()
823                                              * SGD_DEGREES_TO_RADIANS,
824                                            180.0, false ); 
825     }
826     // cout << "warp = " << warp << endl;
827     globals->set_warp( orig_warp + warp );
828
829     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
830                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
831                cur_time_override->getLongValue(),
832                globals->get_warp() );
833
834     return true;
835 }
836
837
838 /**
839  * Built-in command: toggle a bool property value.
840  *
841  * property: The name of the property to toggle.
842  */
843 static bool
844 do_property_toggle (const SGPropertyNode * arg)
845 {
846   SGPropertyNode * prop = get_prop(arg);
847   return prop->setBoolValue(!prop->getBoolValue());
848 }
849
850
851 /**
852  * Built-in command: assign a value to a property.
853  *
854  * property: the name of the property to assign.
855  * value: the value to assign; or
856  * property[1]: the property to copy from.
857  */
858 static bool
859 do_property_assign (const SGPropertyNode * arg)
860 {
861   SGPropertyNode * prop = get_prop(arg);
862   const SGPropertyNode * prop2 = get_prop2(arg);
863   const SGPropertyNode * value = arg->getNode("value");
864
865   if (value != 0)
866       return prop->setUnspecifiedValue(value->getStringValue());
867   else if (prop2)
868       return prop->setUnspecifiedValue(prop2->getStringValue());
869   else
870       return false;
871 }
872
873
874 /**
875  * Built-in command: increment or decrement a property value.
876  *
877  * If the 'step' argument is present, it will be used; otherwise,
878  * the command uses 'offset' and 'factor', usually from the mouse.
879  *
880  * property: the name of the property to increment or decrement.
881  * step: the amount of the increment or decrement (default: 0).
882  * offset: offset from the current setting (used for the mouse; multiplied 
883  *         by factor)
884  * factor: scaling amount for the offset (defaults to 1).
885  * min: the minimum allowed value (default: no minimum).
886  * max: the maximum allowed value (default: no maximum).
887  * mask: 'integer' to apply only to the left of the decimal point, 
888  *       'decimal' to apply only to the right of the decimal point,
889  *       or 'all' to apply to the whole number (the default).
890  * wrap: true if the value should be wrapped when it passes min or max;
891  *       both min and max must be present for this to work (default:
892  *       false).
893  */
894 static bool
895 do_property_adjust (const SGPropertyNode * arg)
896 {
897   SGPropertyNode * prop = get_prop(arg);
898
899   double amount = 0;
900   if (arg->hasValue("step"))
901       amount = arg->getDoubleValue("step");
902   else
903       amount = (arg->getDoubleValue("factor", 1)
904                 * arg->getDoubleValue("offset"));
905           
906   double unmodifiable, modifiable;
907   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
908               &unmodifiable, &modifiable);
909   modifiable += amount;
910   limit_value(&modifiable, arg);
911
912   prop->setDoubleValue(unmodifiable + modifiable);
913
914   return true;
915 }
916
917
918 /**
919  * Built-in command: multiply a property value.
920  *
921  * property: the name of the property to multiply.
922  * factor: the amount by which to multiply.
923  * min: the minimum allowed value (default: no minimum).
924  * max: the maximum allowed value (default: no maximum).
925  * mask: 'integer' to apply only to the left of the decimal point, 
926  *       'decimal' to apply only to the right of the decimal point,
927  *       or 'all' to apply to the whole number (the default).
928  * wrap: true if the value should be wrapped when it passes min or max;
929  *       both min and max must be present for this to work (default:
930  *       false).
931  */
932 static bool
933 do_property_multiply (const SGPropertyNode * arg)
934 {
935   SGPropertyNode * prop = get_prop(arg);
936   double factor = arg->getDoubleValue("factor", 1);
937
938   double unmodifiable, modifiable;
939   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
940               &unmodifiable, &modifiable);
941   modifiable *= factor;
942   limit_value(&modifiable, arg);
943
944   prop->setDoubleValue(unmodifiable + modifiable);
945
946   return true;
947 }
948
949
950 /**
951  * Built-in command: swap two property values.
952  *
953  * property[0]: the name of the first property.
954  * property[1]: the name of the second property.
955  */
956 static bool
957 do_property_swap (const SGPropertyNode * arg)
958 {
959   SGPropertyNode * prop1 = get_prop(arg);
960   SGPropertyNode * prop2 = get_prop2(arg);
961
962                                 // FIXME: inefficient
963   const string & tmp = prop1->getStringValue();
964   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
965           prop2->setUnspecifiedValue(tmp.c_str()));
966 }
967
968
969 /**
970  * Built-in command: Set a property to an axis or other moving input.
971  *
972  * property: the name of the property to set.
973  * setting: the current input setting, usually between -1.0 and 1.0.
974  * offset: the offset to shift by, before applying the factor.
975  * factor: the factor to multiply by (use negative to reverse).
976  */
977 static bool
978 do_property_scale (const SGPropertyNode * arg)
979 {
980   SGPropertyNode * prop = get_prop(arg);
981   double setting = arg->getDoubleValue("setting");
982   double offset = arg->getDoubleValue("offset", 0.0);
983   double factor = arg->getDoubleValue("factor", 1.0);
984   bool squared = arg->getBoolValue("squared", false);
985   int power = arg->getIntValue("power", (squared ? 2 : 1));
986
987   int sign = (setting < 0 ? -1 : 1);
988
989   switch (power) {
990   case 1:
991       break;
992   case 2:
993       setting = setting * setting * sign;
994       break;
995   case 3:
996       setting = setting * setting * setting;
997       break;
998   case 4:
999       setting = setting * setting * setting * setting * sign;
1000       break;
1001   default:
1002       setting =  pow(setting, power);
1003       if ((power % 2) == 0)
1004           setting *= sign;
1005       break;
1006   }
1007
1008   return prop->setDoubleValue((setting + offset) * factor);
1009 }
1010
1011
1012 /**
1013  * Built-in command: cycle a property through a set of values.
1014  *
1015  * If the current value isn't in the list, the cycle will
1016  * (re)start from the beginning.
1017  *
1018  * property: the name of the property to cycle.
1019  * value[*]: the list of values to cycle through.
1020  */
1021 static bool
1022 do_property_cycle (const SGPropertyNode * arg)
1023 {
1024     SGPropertyNode * prop = get_prop(arg);
1025     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
1026     int selection = -1;
1027     int nSelections = values.size();
1028
1029     if (nSelections < 1) {
1030         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
1031         return false;
1032     }
1033
1034                                 // Try to find the current selection
1035     for (int i = 0; i < nSelections; i++) {
1036         if (compare_values(prop, values[i])) {
1037             selection = i + 1;
1038             break;
1039         }
1040     }
1041
1042                                 // Default or wrap to the first selection
1043     if (selection < 0 || selection >= nSelections)
1044         selection = 0;
1045
1046     prop->setUnspecifiedValue(values[selection]->getStringValue());
1047     return true;
1048 }
1049
1050
1051 /**
1052  * Built-in command: randomize a numeric property value.
1053  *
1054  * property: the name of the property value to randomize.
1055  * min: the minimum allowed value.
1056  * max: the maximum allowed value.
1057  */
1058 static bool
1059 do_property_randomize (const SGPropertyNode * arg)
1060 {
1061     SGPropertyNode * prop = get_prop(arg);
1062     double min = arg->getDoubleValue("min", DBL_MIN);
1063     double max = arg->getDoubleValue("max", DBL_MAX);
1064     prop->setDoubleValue(sg_random() * (max - min) + min);
1065     return true;
1066 }
1067
1068
1069 /**
1070  * Built-in command: reinit the data logging system based on the
1071  * current contents of the /logger tree.
1072  */
1073 static bool
1074 do_data_logging_commit (const SGPropertyNode * arg)
1075 {
1076     FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1077     log->reinit();
1078     return true;
1079 }
1080
1081 /**
1082  * Built-in command: Add a dialog to the GUI system.  Does *not*
1083  * display the dialog.  The property node should have the same format
1084  * as a dialog XML configuration.  It must include:
1085  *
1086  * name: the name of the GUI dialog for future reference.
1087  */
1088 static bool
1089 do_dialog_new (const SGPropertyNode * arg)
1090 {
1091     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1092
1093     // Note the casting away of const: this is *real*.  Doing a
1094     // "dialog-apply" command later on will mutate this property node.
1095     // I'm not convinced that this isn't the Right Thing though; it
1096     // allows client to create a node, pass it to dialog-new, and get
1097     // the values back from the dialog by reading the same node.
1098     // Perhaps command arguments are not as "const" as they would
1099     // seem?
1100     gui->newDialog((SGPropertyNode*)arg);
1101     return true;
1102 }
1103
1104 /**
1105  * Built-in command: Show an XML-configured dialog.
1106  *
1107  * dialog-name: the name of the GUI dialog to display.
1108  */
1109 static bool
1110 do_dialog_show (const SGPropertyNode * arg)
1111 {
1112     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1113     gui->showDialog(arg->getStringValue("dialog-name"));
1114     return true;
1115 }
1116
1117
1118 /**
1119  * Built-in Command: Hide the active XML-configured dialog.
1120  */
1121 static bool
1122 do_dialog_close (const SGPropertyNode * arg)
1123 {
1124     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1125     if(arg->hasValue("dialog-name"))
1126         return gui->closeDialog(arg->getStringValue("dialog-name"));
1127     return gui->closeActiveDialog();
1128 }
1129
1130
1131 /**
1132  * Update a value in the active XML-configured dialog.
1133  *
1134  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1135  */
1136 static bool
1137 do_dialog_update (const SGPropertyNode * arg)
1138 {
1139     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1140     FGDialog * dialog;
1141     if (arg->hasValue("dialog-name"))
1142         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1143     else
1144         dialog = gui->getActiveDialog();
1145
1146     if (dialog != 0) {
1147         dialog->updateValues(arg->getStringValue("object-name"));
1148         return true;
1149     } else {
1150         return false;
1151     }
1152 }
1153
1154
1155 /**
1156  * Apply a value in the active XML-configured dialog.
1157  *
1158  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1159  */
1160 static bool
1161 do_dialog_apply (const SGPropertyNode * arg)
1162 {
1163     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1164     FGDialog * dialog;
1165     if (arg->hasValue("dialog-name"))
1166         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1167     else
1168         dialog = gui->getActiveDialog();
1169
1170     if (dialog != 0) {
1171         dialog->applyValues(arg->getStringValue("object-name"));
1172         return true;
1173     } else {
1174         return false;
1175     }
1176 }
1177
1178
1179 /**
1180  * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1181  * unlike reinit().
1182  */
1183 static bool
1184 do_gui_redraw (const SGPropertyNode * arg)
1185 {
1186     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1187     gui->redraw();
1188     return true;
1189 }
1190
1191
1192 /**
1193  * Adds model to the scenery. The path to the added branch (/models/model[*])
1194  * is returned in property "property".
1195  */
1196 static bool
1197 do_add_model (const SGPropertyNode * arg)
1198 {
1199     SGPropertyNode * model = fgGetNode("models", true);
1200     for (int i = 0;; i++) {
1201         if (i < 0)
1202             return false;
1203         if (!model->getChild("model", i, false)) {
1204             model = model->getChild("model", i, true);
1205             break;
1206         }
1207     }
1208     copyProperties(arg, model);
1209     if (model->hasValue("elevation-m"))
1210         model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1211                 * SG_METER_TO_FEET);
1212     model->getNode("load", true);
1213     model->removeChildren("load");
1214     const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1215     return true;
1216 }
1217
1218
1219 /**
1220  * Set mouse cursor coordinates and cursor shape.
1221  */
1222 static bool
1223 do_set_cursor (const SGPropertyNode * arg)
1224 {
1225     if (arg->hasValue("x") || arg->hasValue("y")) {
1226         SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1227         SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1228         int x = arg->getIntValue("x", mx->getIntValue());
1229         int y = arg->getIntValue("y", my->getIntValue());
1230         fgWarpMouse(x, y);
1231         mx->setIntValue(x);
1232         my->setIntValue(y);
1233     }
1234
1235     SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1236     if (cursor->getType() != simgear::props::NONE)
1237         fgSetMouseCursor(cursor->getIntValue());
1238
1239     cursor->setIntValue(fgGetMouseCursor());
1240     return true;
1241 }
1242
1243
1244 /**
1245  * Built-in command: play an audio message (i.e. a wav file) This is
1246  * fire and forget.  Call this once per message and it will get dumped
1247  * into a queue.  Messages are played sequentially so they do not
1248  * overlap.
1249  */
1250 static bool
1251 do_play_audio_sample (const SGPropertyNode * arg)
1252 {
1253     FGFX *fx = (FGFX *)globals->get_subsystem("fx");
1254     string path = arg->getStringValue("path");
1255     string file = arg->getStringValue("file");
1256     double volume = arg->getDoubleValue("volume");
1257     // cout << "playing " << path << " / " << file << endl;
1258     try {
1259         fx->play_message( path, file, volume );
1260         return true;
1261
1262     } catch (const sg_io_exception&) {
1263         SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1264                 "failed to load" << path << '/' << file);
1265         return false;
1266     }
1267 }
1268
1269 /**
1270  * Built-in command: commit presets (read from in /sim/presets/)
1271  */
1272 static bool
1273 do_presets_commit (const SGPropertyNode * arg)
1274 {
1275     // unbind the current fdm state so property changes
1276     // don't get lost when we subsequently delete this fdm
1277     // and create a new one.
1278     cur_fdm_state->unbind();
1279
1280     // set position from presets
1281     fgInitPosition();
1282
1283     fgReInitSubsystems();
1284
1285     globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
1286
1287 #if 0
1288     if ( ! fgGetBool("/sim/presets/onground") ) {
1289         fgSetBool( "/sim/freeze/master", true );
1290         fgSetBool( "/sim/freeze/clock", true );
1291     }
1292 #endif
1293
1294     return true;
1295 }
1296
1297 /**
1298  * Built-in command: set log level (0 ... 7)
1299  */
1300 static bool
1301 do_log_level (const SGPropertyNode * arg)
1302 {
1303    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1304
1305    return true;
1306 }
1307
1308 /**
1309  * Built-in command: replay the FDR buffer
1310  */
1311 static bool
1312 do_replay (const SGPropertyNode * arg)
1313 {
1314     // freeze the master fdm
1315     fgSetInt( "/sim/freeze/replay-state", 1 );
1316
1317     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
1318
1319     fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
1320     fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
1321     double duration = fgGetDouble( "/sim/replay/duration" );
1322     if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
1323         fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
1324     } else {
1325         fgSetDouble( "/sim/replay/time", r->get_start_time() );
1326     }
1327
1328     // cout << "start = " << r->get_start_time()
1329     //      << "  end = " << r->get_end_time() << endl;
1330
1331     return true;
1332 }
1333
1334
1335 static bool
1336 do_decrease_visibility (const SGPropertyNode * arg)
1337 {
1338     double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
1339     fgSetDouble("/environment/visibility-m", new_value);
1340     fgDefaultWeatherValue("visibility-m", new_value);
1341     globals->get_subsystem("environment")->reinit();
1342
1343     return true;
1344 }
1345  
1346 static bool
1347 do_increase_visibility (const SGPropertyNode * arg)
1348 {
1349     double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
1350     fgSetDouble("/environment/visibility-m", new_value);
1351     fgDefaultWeatherValue("visibility-m", new_value);
1352     globals->get_subsystem("environment")->reinit();
1353
1354     return true;
1355 }
1356
1357 static bool
1358 do_hud_init(const SGPropertyNode *)
1359 {
1360     fgHUDInit(0); // minimal HUD
1361     return true;
1362 }
1363
1364 static bool
1365 do_hud_init2(const SGPropertyNode *)
1366 {
1367     fgHUDInit2(0);  // normal HUD
1368     return true;
1369 }
1370
1371
1372 /**
1373  * An fgcommand to allow loading of xml files via nasal,
1374  * the xml file's structure will be made available within
1375  * a property tree node defined under argument "targetnode",
1376  * or in the given argument tree under "data" otherwise.
1377  *
1378  * @param filename a string to hold the complete path & filename of an XML file
1379  * @param targetnode a string pointing to a location within the property tree
1380  * where to store the parsed XML file. If <targetnode> is undefined, then the
1381  * file contents are stored under a node <data> in the argument tree.
1382  */
1383
1384 static bool
1385 do_load_xml_to_proptree(const SGPropertyNode * arg)
1386 {
1387     SGPath file(arg->getStringValue("filename"));
1388     if (file.str().empty())
1389         return false;
1390
1391     if (file.extension() != "xml")
1392         file.concat(".xml");
1393
1394     if (!fgValidatePath(file.c_str(), false)) {
1395         SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1396                 "(unauthorized access)");
1397         return false;
1398     }
1399
1400     SGPropertyNode *targetnode;
1401     if (arg->hasValue("targetnode"))
1402         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1403     else
1404         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1405
1406     try {
1407         readProperties(file.c_str(), targetnode, true);
1408     } catch (const sg_exception &e) {
1409         SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1410         return false;
1411     }
1412
1413     return true;
1414 }
1415
1416
1417 /**
1418  * An fgcommand to allow saving of xml files via nasal,
1419  * the file's structure will be determined based on what's
1420  * encountered in the passed (source) property tree node
1421  *
1422  * @param filename a string to hold the complete path & filename of the (new)
1423  * XML file
1424  * @param sourcenode a string pointing to a location within the property tree
1425  * where to find the nodes that should be written recursively into an XML file
1426  * @param data if no sourcenode is given, then the file contents are taken from
1427  * the argument tree's "data" node.
1428  */
1429
1430 static bool
1431 do_save_xml_from_proptree(const SGPropertyNode * arg)
1432 {
1433     SGPath file(arg->getStringValue("filename"));
1434     if (file.str().empty())
1435         return false;
1436
1437     if (file.extension() != "xml")
1438         file.concat(".xml");
1439
1440     if (!fgValidatePath(file.c_str(), true)) {
1441         SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1442                 "(unauthorized access)");
1443         return false;
1444     }
1445
1446     SGPropertyNode *sourcenode;
1447     if (arg->hasValue("sourcenode"))
1448         sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1449     else if (arg->getNode("data", false))
1450         sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1451     else
1452         return false;
1453
1454     try {
1455         writeProperties (file.c_str(), sourcenode, true);
1456     } catch (const sg_exception &e) {
1457         SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1458         return false;
1459     }
1460
1461     return true;
1462 }
1463
1464 static bool
1465 do_press_cockpit_button (const SGPropertyNode *arg)
1466 {
1467   const char *prefix = arg->getStringValue("prefix");
1468
1469   if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1470     return true;
1471
1472   string prop = string(prefix) + "-button";
1473   double value;
1474
1475   if (arg->getBoolValue("latching"))
1476     value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1477   else
1478     value = 1;
1479
1480   fgSetDouble(prop.c_str(), value);
1481   fgSetBool(arg->getStringValue("discrete"), value > 0);
1482
1483   return true;
1484 }
1485
1486 static bool
1487 do_release_cockpit_button (const SGPropertyNode *arg)
1488 {
1489   const char *prefix = arg->getStringValue("prefix");
1490
1491   if (arg->getBoolValue("guarded")) {
1492     string prop = string(prefix) + "-guard";
1493     if (fgGetDouble(prop.c_str()) < 1) {
1494       fgSetDouble(prop.c_str(), 1);
1495       return true;
1496     }
1497   }
1498
1499   if (! arg->getBoolValue("latching")) {
1500     fgSetDouble((string(prefix) + "-button").c_str(), 0);
1501     fgSetBool(arg->getStringValue("discrete"), false);
1502   }
1503
1504   return true;
1505 }
1506
1507
1508 ////////////////////////////////////////////////////////////////////////
1509 // Command setup.
1510 ////////////////////////////////////////////////////////////////////////
1511
1512
1513 /**
1514  * Table of built-in commands.
1515  *
1516  * New commands do not have to be added here; any module in the application
1517  * can add a new command using globals->get_commands()->addCommand(...).
1518  */
1519 static struct {
1520   const char * name;
1521   SGCommandMgr::command_t command;
1522 } built_ins [] = {
1523     { "null", do_null },
1524     { "nasal", do_nasal },
1525     { "exit", do_exit },
1526     { "reset", do_reset },
1527     { "reinit", do_reinit },
1528     { "suspend", do_reinit },
1529     { "resume", do_reinit },
1530     { "load", do_load },
1531     { "save", do_save },
1532     { "panel-load", do_panel_load },
1533     { "panel-mouse-click", do_panel_mouse_click },
1534     { "preferences-load", do_preferences_load },
1535     { "view-cycle", do_view_cycle },
1536     { "screen-capture", do_screen_capture },
1537     { "hires-screen-capture", do_hires_screen_capture },
1538     { "tile-cache-reload", do_tile_cache_reload },
1539     { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1540     { "set-outside-air-temp-degc", do_set_oat_degc },
1541     { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1542     { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1543     { "timeofday", do_timeofday },
1544     { "property-toggle", do_property_toggle },
1545     { "property-assign", do_property_assign },
1546     { "property-adjust", do_property_adjust },
1547     { "property-multiply", do_property_multiply },
1548     { "property-swap", do_property_swap },
1549     { "property-scale", do_property_scale },
1550     { "property-cycle", do_property_cycle },
1551     { "property-randomize", do_property_randomize },
1552     { "data-logging-commit", do_data_logging_commit },
1553     { "dialog-new", do_dialog_new },
1554     { "dialog-show", do_dialog_show },
1555     { "dialog-close", do_dialog_close },
1556     { "dialog-update", do_dialog_update },
1557     { "dialog-apply", do_dialog_apply },
1558     { "gui-redraw", do_gui_redraw },
1559     { "add-model", do_add_model },
1560     { "set-cursor", do_set_cursor },
1561     { "play-audio-sample", do_play_audio_sample },
1562     { "presets-commit", do_presets_commit },
1563     { "log-level", do_log_level },
1564     { "replay", do_replay },
1565     { "decrease-visibility", do_decrease_visibility },
1566     { "increase-visibility", do_increase_visibility },
1567     { "hud-init", do_hud_init },
1568     { "hud-init2", do_hud_init2 },
1569     { "loadxml", do_load_xml_to_proptree},
1570     { "savexml", do_save_xml_from_proptree },
1571     { "press-cockpit-button", do_press_cockpit_button },
1572     { "release-cockpit-button", do_release_cockpit_button },
1573     { "dump-scenegraph", do_dump_scene_graph },
1574     { "dump-terrainbranch", do_dump_terrain_branch },
1575     { "reload-shaders", do_reload_shaders },
1576     { 0, 0 }                    // zero-terminated
1577 };
1578
1579
1580 /**
1581  * Initialize the default built-in commands.
1582  *
1583  * Other commands may be added by other parts of the application.
1584  */
1585 void
1586 fgInitCommands ()
1587 {
1588   SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1589   for (int i = 0; built_ins[i].name != 0; i++) {
1590     SG_LOG(SG_GENERAL, SG_INFO, "  " << built_ins[i].name);
1591     globals->get_commands()->addCommand(built_ins[i].name,
1592                                         built_ins[i].command);
1593   }
1594
1595   typedef bool (*dummy)();
1596   fgTie( "/command/view/next", dummy(0), do_view_next );
1597   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1598 }
1599
1600 // end of fg_commands.cxx