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