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