]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Convert fgLIGHT to FGLight and make it FGSubsystem compatible. Let the subsystem...
[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 #include <simgear/misc/exception.hxx>
7
8 #include STL_STRING
9 #include STL_FSTREAM
10
11 #include <simgear/sg_inlines.h>
12 #include <simgear/debug/logstream.hxx>
13 #include <simgear/math/sg_random.h>
14 #include <simgear/misc/commands.hxx>
15 #include <simgear/props/props.hxx>
16
17 #include <Cockpit/panel.hxx>
18 #include <Cockpit/panel_io.hxx>
19 #include <FDM/flight.hxx>
20 #include <GUI/gui.h>
21 #include <GUI/new_gui.hxx>
22 #include <GUI/dialog.hxx>
23 #include <Replay/replay.hxx>
24 #include <Scenery/tilemgr.hxx>
25 #if defined(HAVE_PLIB_PSL)
26 #  include <Scripting/scriptmgr.hxx>
27 #endif
28 #include <Time/sunsolver.hxx>
29 #include <Time/tmp.hxx>
30
31 #include "fg_init.hxx"
32 #include "fg_commands.hxx"
33 #include "fg_props.hxx"
34
35 SG_USING_STD(string);
36 SG_USING_STD(ifstream);
37 SG_USING_STD(ofstream);
38
39 #include "fg_props.hxx"
40 #include "fg_io.hxx"
41 #include "globals.hxx"
42 #include "util.hxx"
43 #include "viewmgr.hxx"
44
45
46 \f
47 ////////////////////////////////////////////////////////////////////////
48 // Static helper functions.
49 ////////////////////////////////////////////////////////////////////////
50
51
52 static inline SGPropertyNode *
53 get_prop (const SGPropertyNode * arg)
54 {
55     return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
56 }
57
58 static inline SGPropertyNode *
59 get_prop2 (const SGPropertyNode * arg)
60 {
61     return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
62 }
63
64
65 /**
66  * Get a double value and split it as required.
67  */
68 static void
69 split_value (double full_value, const char * mask,
70              double * unmodifiable, double * modifiable)
71 {
72     if (!strcmp("integer", mask)) {
73         *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
74         *unmodifiable = full_value - *modifiable;
75     } else if (!strcmp("decimal", mask)) {
76         *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
77         *modifiable = full_value - *unmodifiable;
78     } else {
79         if (strcmp("all", mask))
80             SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
81                    << " assuming 'all'");
82         *unmodifiable = 0;
83         *modifiable = full_value;
84     }
85 }
86
87
88 /**
89  * Clamp or wrap a value as specified.
90  */
91 static void
92 limit_value (double * value, const SGPropertyNode * arg)
93 {
94     const SGPropertyNode * min_node = arg->getChild("min");
95     const SGPropertyNode * max_node = arg->getChild("max");
96
97     bool wrap = arg->getBoolValue("wrap");
98
99     if (min_node == 0 || max_node == 0)
100         wrap = false;
101   
102     if (wrap) {                 // wrap such that min <= x < max
103         double min_val = min_node->getDoubleValue();
104         double max_val = max_node->getDoubleValue();
105         double resolution = arg->getDoubleValue("resolution");
106         if (resolution > 0.0) {
107             // snap to (min + N*resolution), taking special care to handle imprecision
108             int n = (int)floor((*value - min_val) / resolution + 0.5);
109             int steps = (int)floor((max_val - min_val) / resolution + 0.5);
110             SG_NORMALIZE_RANGE(n, 0, steps);
111             *value = min_val + resolution * n;
112         } else {
113             // plain circular wrapping
114             SG_NORMALIZE_RANGE(*value, min_val, max_val);
115         }
116     } else {                    // clamp such that min <= x <= max
117         if ((min_node != 0) && (*value < min_node->getDoubleValue()))
118             *value = min_node->getDoubleValue();
119         else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
120             *value = max_node->getDoubleValue();
121     }
122 }
123
124 static bool
125 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
126 {
127     switch (value1->getType()) {
128     case SGPropertyNode::BOOL:
129         return (value1->getBoolValue() == value2->getBoolValue());
130     case SGPropertyNode::INT:
131         return (value1->getIntValue() == value2->getIntValue());
132     case SGPropertyNode::LONG:
133         return (value1->getLongValue() == value2->getLongValue());
134     case SGPropertyNode::FLOAT:
135         return (value1->getFloatValue() == value2->getFloatValue());
136     case SGPropertyNode::DOUBLE:
137         return (value1->getDoubleValue() == value2->getDoubleValue());
138     default:
139         return !strcmp(value1->getStringValue(), value2->getStringValue());
140     }
141 }
142
143
144 \f
145 ////////////////////////////////////////////////////////////////////////
146 // Command implementations.
147 ////////////////////////////////////////////////////////////////////////
148
149
150 /**
151  * Built-in command: do nothing.
152  */
153 static bool
154 do_null (const SGPropertyNode * arg)
155 {
156   return true;
157 }
158
159 #if defined(HAVE_PLIB_PSL)
160 /**
161  * Built-in command: run a PSL script.
162  *
163  * script: the PSL script to execute
164  */
165 static bool
166 do_script (const SGPropertyNode * arg)
167 {
168     FGScriptMgr * mgr = (FGScriptMgr *)globals->get_subsystem("scripting");
169     return mgr->run(arg->getStringValue("script"));
170 }
171 #endif // HAVE_PLIB_PSL
172
173
174 /**
175  * Built-in command: exit FlightGear.
176  *
177  * status: the exit status to return to the operating system (defaults to 0)
178  */
179 static bool
180 do_exit (const SGPropertyNode * arg)
181 {
182   SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
183   fgExit(arg->getIntValue("status", 0));
184   return true;
185 }
186
187
188 /**
189  * Built-in command: reinitialize one or more subsystems.
190  *
191  * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
192  * none is specified, reinitialize all of them.
193  */
194 static bool
195 do_reinit (const SGPropertyNode * arg)
196 {
197     bool result = true;
198
199     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
200     if (subsystems.size() == 0) {
201         globals->get_subsystem_mgr()->reinit();
202     } else {
203         for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
204             const char * name = subsystems[i]->getStringValue();
205             FGSubsystem * subsystem = globals->get_subsystem(name);
206             if (subsystem == 0) {
207                 result = false;
208                 SG_LOG( SG_GENERAL, SG_ALERT,
209                         "Subsystem " << name << "not found" );
210             } else {
211                 subsystem->reinit();
212             }
213         }
214     }
215
216     return result;
217 }
218
219 /**
220  * Built-in command: suspend one or more subsystems.
221  *
222  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
223  */
224 static bool
225 do_suspend (const SGPropertyNode * arg)
226 {
227     bool result = true;
228
229     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
230     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
231         const char * name = subsystems[i]->getStringValue();
232         FGSubsystem * subsystem = globals->get_subsystem(name);
233         if (subsystem == 0) {
234             result = false;
235             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
236         } else {
237             subsystem->suspend();
238         }
239     }
240     return result;
241 }
242
243 /**
244  * Built-in command: suspend one or more subsystems.
245  *
246  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
247  */
248 static bool
249 do_resume (const SGPropertyNode * arg)
250 {
251     bool result = true;
252
253     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
254     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
255         const char * name = subsystems[i]->getStringValue();
256         FGSubsystem * subsystem = globals->get_subsystem(name);
257         if (subsystem == 0) {
258             result = false;
259             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
260         } else {
261             subsystem->resume();
262         }
263     }
264     return result;
265 }
266
267
268 /**
269  * Built-in command: load flight.
270  *
271  * file (optional): the name of the file to load (relative to current
272  *   directory).  Defaults to "fgfs.sav"
273  */
274 static bool
275 do_load (const SGPropertyNode * arg)
276 {
277   const string &file = arg->getStringValue("file", "fgfs.sav");
278   ifstream input(file.c_str());
279   if (input.good() && fgLoadFlight(input)) {
280     input.close();
281     SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
282     return true;
283   } else {
284     SG_LOG(SG_INPUT, SG_ALERT, "Cannot load flight from " << file);
285     return false;
286   }
287 }
288
289
290 /**
291  * Built-in command: save flight.
292  *
293  * file (optional): the name of the file to save (relative to the
294  * current directory).  Defaults to "fgfs.sav".
295  */
296 static bool
297 do_save (const SGPropertyNode * arg)
298 {
299   const string &file = arg->getStringValue("file", "fgfs.sav");
300   bool write_all = arg->getBoolValue("write-all", false);
301   SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
302   ofstream output(file.c_str());
303   if (output.good() && fgSaveFlight(output, write_all)) {
304     output.close();
305     SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
306     return true;
307   } else {
308     SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
309     return false;
310   }
311 }
312
313
314 /**
315  * Built-in command: (re)load the panel.
316  *
317  * path (optional): the file name to load the panel from 
318  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
319  * and if that's unspecified, to "Panels/Default/default.xml".
320  */
321 static bool
322 do_panel_load (const SGPropertyNode * arg)
323 {
324   string panel_path =
325     arg->getStringValue("path",
326                         fgGetString("/sim/panel/path",
327                                     "Panels/Default/default.xml"));
328   FGPanel * new_panel = fgReadPanel(panel_path);
329   if (new_panel == 0) {
330     SG_LOG(SG_INPUT, SG_ALERT,
331            "Error reading new panel from " << panel_path);
332     return false;
333   }
334   SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
335   globals->get_current_panel()->unbind();
336   delete globals->get_current_panel();
337   globals->set_current_panel( new_panel );
338   globals->get_current_panel()->bind();
339   return true;
340 }
341
342
343 /**
344  * Built-in command: pass a mouse click to the panel.
345  *
346  * button: the mouse button number, zero-based.
347  * is-down: true if the button is down, false if it is up.
348  * x-pos: the x position of the mouse click.
349  * y-pos: the y position of the mouse click.
350  */
351 static bool
352 do_panel_mouse_click (const SGPropertyNode * arg)
353 {
354   if (globals->get_current_panel() != 0)
355     return globals->get_current_panel()
356       ->doMouseAction(arg->getIntValue("button"),
357                       arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
358                       arg->getIntValue("x-pos"),
359                       arg->getIntValue("y-pos"));
360   else
361     return false;
362 }
363
364
365 /**
366  * Built-in command: (re)load preferences.
367  *
368  * path (optional): the file name to load the panel from (relative
369  * to FG_ROOT). Defaults to "preferences.xml".
370  */
371 static bool
372 do_preferences_load (const SGPropertyNode * arg)
373 {
374   try {
375     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
376                 globals->get_props());
377   } catch (const sg_exception &e) {
378     guiErrorMessage("Error reading global preferences: ", e);
379     return false;
380   }
381   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
382   return true;
383 }
384
385
386 static void
387 fix_hud_visibility()
388 {
389   if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
390       globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
391       if ( globals->get_viewmgr()->get_current() == 1 ) {
392           globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
393       }
394   }
395 }
396
397 static void
398 do_view_next( bool )
399 {
400     globals->get_current_view()->setHeadingOffset_deg(0.0);
401     globals->get_viewmgr()->next_view();
402     fix_hud_visibility();
403     globals->get_tile_mgr()->refresh_view_timestamps();
404 }
405
406 static void
407 do_view_prev( bool )
408 {
409     globals->get_current_view()->setHeadingOffset_deg(0.0);
410     globals->get_viewmgr()->prev_view();
411     fix_hud_visibility();
412     globals->get_tile_mgr()->refresh_view_timestamps();
413 }
414
415 /**
416  * Built-in command: cycle view.
417  */
418 static bool
419 do_view_cycle (const SGPropertyNode * arg)
420 {
421   globals->get_current_view()->setHeadingOffset_deg(0.0);
422   globals->get_viewmgr()->next_view();
423   fix_hud_visibility();
424   globals->get_tile_mgr()->refresh_view_timestamps();
425 //   fgReshape(fgGetInt("/sim/startup/xsize"), fgGetInt("/sim/startup/ysize"));
426   return true;
427 }
428
429 /**
430  * Built-in command: capture screen.
431  */
432 static bool
433 do_screen_capture (const SGPropertyNode * arg)
434 {
435   fgDumpSnapShot();
436   return true;
437 }
438
439
440 /**
441  * Reload the tile cache.
442  */
443 static bool
444 do_tile_cache_reload (const SGPropertyNode * arg)
445 {
446     static const SGPropertyNode *master_freeze
447         = fgGetNode("/sim/freeze/master");
448     bool freeze = master_freeze->getBoolValue();
449     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
450     if ( !freeze ) {
451         fgSetBool("/sim/freeze/master", true);
452     }
453     // BusyCursor(0);
454     if ( globals->get_tile_mgr()->init() ) {
455         // Load the local scenery data
456         double visibility_meters = fgGetDouble("/environment/visibility-m");
457         globals->get_tile_mgr()->update( visibility_meters );
458     } else {
459         SG_LOG( SG_GENERAL, SG_ALERT, 
460                 "Error in Tile Manager initialization!" );
461         exit(-1);
462     }
463     // BusyCursor(1);
464     if ( !freeze ) {
465         fgSetBool("/sim/freeze/master", false);
466     }
467     return true;
468 }
469
470
471 /**
472  * Update the lighting manually.
473  */
474 static bool
475 do_timeofday (const SGPropertyNode * arg)
476 {
477     const string &offset_type = arg->getStringValue("timeofday", "noon");
478
479     static const SGPropertyNode *longitude
480         = fgGetNode("/position/longitude-deg");
481     static const SGPropertyNode *latitude
482         = fgGetNode("/position/latitude-deg");
483     static const SGPropertyNode *cur_time_override
484         = fgGetNode("/sim/time/cur-time-override", true);
485
486     int orig_warp = globals->get_warp();
487     SGTime *t = globals->get_time_params();
488     time_t cur_time = t->get_cur_time();
489     // cout << "cur_time = " << cur_time << endl;
490     // cout << "orig_warp = " << orig_warp << endl;
491
492     int warp = 0;
493     if ( offset_type == "real" ) {
494         warp = -orig_warp;
495     } else if ( offset_type == "dawn" ) {
496         warp = fgTimeSecondsUntilSunAngle( cur_time,
497                                            longitude->getDoubleValue()
498                                              * SGD_DEGREES_TO_RADIANS,
499                                            latitude->getDoubleValue()
500                                              * SGD_DEGREES_TO_RADIANS,
501                                            90.0, true ); 
502     } else if ( offset_type == "morning" ) {
503         warp = fgTimeSecondsUntilSunAngle( cur_time,
504                                            longitude->getDoubleValue()
505                                              * SGD_DEGREES_TO_RADIANS,
506                                            latitude->getDoubleValue()
507                                              * SGD_DEGREES_TO_RADIANS,
508                                            75.0, true ); 
509     } else if ( offset_type == "noon" ) {
510         warp = fgTimeSecondsUntilSunAngle( cur_time,
511                                            longitude->getDoubleValue()
512                                              * SGD_DEGREES_TO_RADIANS,
513                                            latitude->getDoubleValue()
514                                              * SGD_DEGREES_TO_RADIANS,
515                                            0.0, true ); 
516     } else if ( offset_type == "afternoon" ) {
517         warp = fgTimeSecondsUntilSunAngle( cur_time,
518                                            longitude->getDoubleValue()
519                                              * SGD_DEGREES_TO_RADIANS,
520                                            latitude->getDoubleValue()
521                                              * SGD_DEGREES_TO_RADIANS,
522                                            60.0, false ); 
523      } else if ( offset_type == "dusk" ) {
524         warp = fgTimeSecondsUntilSunAngle( cur_time,
525                                            longitude->getDoubleValue()
526                                              * SGD_DEGREES_TO_RADIANS,
527                                            latitude->getDoubleValue()
528                                              * SGD_DEGREES_TO_RADIANS,
529                                            90.0, false ); 
530      } else if ( offset_type == "evening" ) {
531         warp = fgTimeSecondsUntilSunAngle( cur_time,
532                                            longitude->getDoubleValue()
533                                              * SGD_DEGREES_TO_RADIANS,
534                                            latitude->getDoubleValue()
535                                              * SGD_DEGREES_TO_RADIANS,
536                                            100.0, false ); 
537     } else if ( offset_type == "midnight" ) {
538         warp = fgTimeSecondsUntilSunAngle( cur_time,
539                                            longitude->getDoubleValue()
540                                              * SGD_DEGREES_TO_RADIANS,
541                                            latitude->getDoubleValue()
542                                              * SGD_DEGREES_TO_RADIANS,
543                                            180.0, false ); 
544     }
545     // cout << "warp = " << warp << endl;
546     globals->set_warp( orig_warp + warp );
547
548     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
549                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
550                cur_time_override->getLongValue(),
551                globals->get_warp() );
552
553     return true;
554 }
555
556
557 /**
558  * Built-in command: toggle a bool property value.
559  *
560  * property: The name of the property to toggle.
561  */
562 static bool
563 do_property_toggle (const SGPropertyNode * arg)
564 {
565   SGPropertyNode * prop = get_prop(arg);
566   return prop->setBoolValue(!prop->getBoolValue());
567 }
568
569
570 /**
571  * Built-in command: assign a value to a property.
572  *
573  * property: the name of the property to assign.
574  * value: the value to assign; or
575  * property[1]: the property to copy from.
576  */
577 static bool
578 do_property_assign (const SGPropertyNode * arg)
579 {
580   SGPropertyNode * prop = get_prop(arg);
581   const SGPropertyNode * prop2 = get_prop2(arg);
582   const SGPropertyNode * value = arg->getNode("value");
583
584   if (value != 0)
585       return prop->setUnspecifiedValue(value->getStringValue());
586   else if (prop2)
587       return prop->setUnspecifiedValue(prop2->getStringValue());
588   else
589       return false;
590 }
591
592
593 /**
594  * Built-in command: increment or decrement a property value.
595  *
596  * If the 'step' argument is present, it will be used; otherwise,
597  * the command uses 'offset' and 'factor', usually from the mouse.
598  *
599  * property: the name of the property to increment or decrement.
600  * step: the amount of the increment or decrement (default: 0).
601  * offset: offset from the current setting (used for the mouse; multiplied 
602  *         by factor)
603  * factor: scaling amount for the offset (defaults to 1).
604  * min: the minimum allowed value (default: no minimum).
605  * max: the maximum allowed value (default: no maximum).
606  * mask: 'integer' to apply only to the left of the decimal point, 
607  *       'decimal' to apply only to the right of the decimal point,
608  *       or 'all' to apply to the whole number (the default).
609  * wrap: true if the value should be wrapped when it passes min or max;
610  *       both min and max must be present for this to work (default:
611  *       false).
612  */
613 static bool
614 do_property_adjust (const SGPropertyNode * arg)
615 {
616   SGPropertyNode * prop = get_prop(arg);
617
618   double amount = 0;
619   if (arg->hasValue("step"))
620       amount = arg->getDoubleValue("step");
621   else
622       amount = (arg->getDoubleValue("factor", 1)
623                 * arg->getDoubleValue("offset"));
624           
625   double unmodifiable, modifiable;
626   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
627               &unmodifiable, &modifiable);
628   modifiable += amount;
629   limit_value(&modifiable, arg);
630
631   prop->setDoubleValue(unmodifiable + modifiable);
632
633   return true;
634 }
635
636
637 /**
638  * Built-in command: multiply a property value.
639  *
640  * property: the name of the property to multiply.
641  * factor: the amount by which to multiply.
642  * min: the minimum allowed value (default: no minimum).
643  * max: the maximum allowed value (default: no maximum).
644  * mask: 'integer' to apply only to the left of the decimal point, 
645  *       'decimal' to apply only to the right of the decimal point,
646  *       or 'all' to apply to the whole number (the default).
647  * wrap: true if the value should be wrapped when it passes min or max;
648  *       both min and max must be present for this to work (default:
649  *       false).
650  */
651 static bool
652 do_property_multiply (const SGPropertyNode * arg)
653 {
654   SGPropertyNode * prop = get_prop(arg);
655   double factor = arg->getDoubleValue("factor", 1);
656
657   double unmodifiable, modifiable;
658   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
659               &unmodifiable, &modifiable);
660   modifiable *= factor;
661   limit_value(&modifiable, arg);
662
663   prop->setDoubleValue(unmodifiable + modifiable);
664
665   return true;
666 }
667
668
669 /**
670  * Built-in command: swap two property values.
671  *
672  * property[0]: the name of the first property.
673  * property[1]: the name of the second property.
674  */
675 static bool
676 do_property_swap (const SGPropertyNode * arg)
677 {
678   SGPropertyNode * prop1 = get_prop(arg);
679   SGPropertyNode * prop2 = get_prop2(arg);
680
681                                 // FIXME: inefficient
682   const string & tmp = prop1->getStringValue();
683   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
684           prop2->setUnspecifiedValue(tmp.c_str()));
685 }
686
687
688 /**
689  * Built-in command: Set a property to an axis or other moving input.
690  *
691  * property: the name of the property to set.
692  * setting: the current input setting, usually between -1.0 and 1.0.
693  * offset: the offset to shift by, before applying the factor.
694  * factor: the factor to multiply by (use negative to reverse).
695  */
696 static bool
697 do_property_scale (const SGPropertyNode * arg)
698 {
699   SGPropertyNode * prop = get_prop(arg);
700   double setting = arg->getDoubleValue("setting");
701   double offset = arg->getDoubleValue("offset", 0.0);
702   double factor = arg->getDoubleValue("factor", 1.0);
703   bool squared = arg->getBoolValue("squared", false);
704   int power = arg->getIntValue("power", (squared ? 2 : 1));
705
706   int sign = (setting < 0 ? -1 : 1);
707
708   switch (power) {
709   case 1:
710       break;
711   case 2:
712       setting = setting * setting * sign;
713       break;
714   case 3:
715       setting = setting * setting * setting;
716       break;
717   case 4:
718       setting = setting * setting * setting * setting * sign;
719       break;
720   default:
721       setting =  pow(setting, power);
722       if ((power % 2) == 0)
723           setting *= sign;
724       break;
725   }
726
727   return prop->setDoubleValue((setting + offset) * factor);
728 }
729
730
731 /**
732  * Built-in command: cycle a property through a set of values.
733  *
734  * If the current value isn't in the list, the cycle will
735  * (re)start from the beginning.
736  *
737  * property: the name of the property to cycle.
738  * value[*]: the list of values to cycle through.
739  */
740 static bool
741 do_property_cycle (const SGPropertyNode * arg)
742 {
743     SGPropertyNode * prop = get_prop(arg);
744     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
745     int selection = -1;
746     int nSelections = values.size();
747
748     if (nSelections < 1) {
749         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
750         return false;
751     }
752
753                                 // Try to find the current selection
754     for (int i = 0; i < nSelections; i++) {
755         if (compare_values(prop, values[i])) {
756             selection = i + 1;
757             break;
758         }
759     }
760
761                                 // Default or wrap to the first selection
762     if (selection < 0 || selection >= nSelections)
763         selection = 0;
764
765     prop->setUnspecifiedValue(values[selection]->getStringValue());
766     return true;
767 }
768
769
770 /**
771  * Built-in command: randomize a numeric property value.
772  *
773  * property: the name of the property value to randomize.
774  * min: the minimum allowed value.
775  * max: the maximum allowed value.
776  */
777 static bool
778 do_property_randomize (const SGPropertyNode * arg)
779 {
780     SGPropertyNode * prop = get_prop(arg);
781     double min = arg->getDoubleValue("min", DBL_MIN);
782     double max = arg->getDoubleValue("max", DBL_MAX);
783     prop->setDoubleValue(sg_random() * (max - min) + min);
784     return true;
785 }
786
787
788 /**
789  * Built-in command: Show an XML-configured dialog.
790  *
791  * dialog-name: the name of the GUI dialog to display.
792  */
793 static bool
794 do_dialog_show (const SGPropertyNode * arg)
795 {
796     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
797     gui->showDialog(arg->getStringValue("dialog-name"));
798     return true;
799 }
800
801
802 /**
803  * Built-in Command: Hide the active XML-configured dialog.
804  */
805 static bool
806 do_dialog_close (const SGPropertyNode * arg)
807 {
808     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
809     return gui->closeActiveDialog();
810 }
811
812
813 /**
814  * Update a value in the active XML-configured dialog.
815  *
816  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
817  */
818 static bool
819 do_dialog_update (const SGPropertyNode * arg)
820 {
821     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
822     FGDialog * dialog = gui->getActiveDialog();
823     if (dialog != 0) {
824         if (arg->hasValue("object-name")) {
825             dialog->updateValue(arg->getStringValue("object-name"));
826         } else {
827             dialog->updateValues();
828         }
829         return true;
830     } else {
831         return false;
832     }
833 }
834
835
836 /**
837  * Apply a value in the active XML-configured dialog.
838  *
839  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
840  */
841 static bool
842 do_dialog_apply (const SGPropertyNode * arg)
843 {
844     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
845     FGDialog * dialog = gui->getActiveDialog();
846     if (dialog != 0) {
847         if (arg->hasValue("object-name")) {
848             const char * name = arg->getStringValue("object-name");
849             dialog->applyValue(name);
850             dialog->updateValue(name);
851         } else {
852             dialog->applyValues();
853             dialog->updateValues();
854         }
855         return true;
856     } else {
857         return false;
858     }
859 }
860
861
862 /**
863  * Built-in command: commit presets (read from in /sim/presets/)
864  */
865 static bool
866 do_presets_commit (const SGPropertyNode * arg)
867 {
868     // unbind the current fdm state so property changes
869     // don't get lost when we subsequently delete this fdm
870     // and create a new one.
871     cur_fdm_state->unbind();
872         
873     // set position from presets
874     fgInitPosition();
875
876     // BusyCursor(0);
877     fgReInitSubsystems();
878
879     globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
880
881 #if 0
882     if ( ! fgGetBool("/sim/presets/onground") ) {
883         fgSetBool( "/sim/freeze/master", true );
884         fgSetBool( "/sim/freeze/clock", true );
885     }
886 #endif
887
888     return true;
889 }
890
891 /**
892  * Built-in command: set log level (0 ... 7)
893  */
894 static bool
895 do_log_level (const SGPropertyNode * arg)
896 {
897    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
898
899    return true;
900 }
901
902 /**
903  * Built-in command: replay the FDR buffer
904  */
905 static bool
906 do_replay (const SGPropertyNode * arg)
907 {
908     // freeze the master fdm
909     fgSetBool( "/sim/freeze/replay", true );
910
911     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
912
913     fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
914     fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
915     double duration = fgGetDouble( "/sim/replay/duration" );
916     if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
917         fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
918     } else {
919         fgSetDouble( "/sim/replay/time", r->get_start_time() );
920     }
921
922     cout << "start = " << r->get_start_time()
923          << "  end = " << r->get_end_time() << endl;
924
925     return true;
926 }
927
928
929
930 static bool
931 do_decrease_visibility (const SGPropertyNode * arg)
932 {
933     double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
934     fgSetDouble("/environment/visibility-m", new_value);
935     fgDefaultWeatherValue("visibility-m", new_value);
936     globals->get_subsystem("environment")->reinit();
937
938     return true;
939 }
940  
941 static bool
942 do_increase_visibility (const SGPropertyNode * arg)
943 {
944     double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
945     fgSetDouble("/environment/visibility-m", new_value);
946     fgDefaultWeatherValue("visibility-m", new_value);
947     globals->get_subsystem("environment")->reinit();
948
949     return true;
950 }
951
952
953 ////////////////////////////////////////////////////////////////////////
954 // Command setup.
955 ////////////////////////////////////////////////////////////////////////
956
957
958 /**
959  * Table of built-in commands.
960  *
961  * New commands do not have to be added here; any module in the application
962  * can add a new command using globals->get_commands()->addCommand(...).
963  */
964 static struct {
965   const char * name;
966   SGCommandMgr::command_t command;
967 } built_ins [] = {
968     { "null", do_null },
969 #if defined(HAVE_PLIB_PSL)
970     { "script", do_script },
971 #endif // HAVE_PLIB_PSL
972     { "exit", do_exit },
973     { "reinit", do_reinit },
974     { "suspend", do_reinit },
975     { "resume", do_reinit },
976     { "load", do_load },
977     { "save", do_save },
978     { "panel-load", do_panel_load },
979     { "panel-mouse-click", do_panel_mouse_click },
980     { "preferences-load", do_preferences_load },
981     { "view-cycle", do_view_cycle },
982     { "screen-capture", do_screen_capture },
983     { "tile-cache-reload", do_tile_cache_reload },
984     { "timeofday", do_timeofday },
985     { "property-toggle", do_property_toggle },
986     { "property-assign", do_property_assign },
987     { "property-adjust", do_property_adjust },
988     { "property-multiply", do_property_multiply },
989     { "property-swap", do_property_swap },
990     { "property-scale", do_property_scale },
991     { "property-cycle", do_property_cycle },
992     { "property-randomize", do_property_randomize },
993     { "dialog-show", do_dialog_show },
994     { "dialog-close", do_dialog_close },
995     { "dialog-show", do_dialog_show },
996     { "dialog-update", do_dialog_update },
997     { "dialog-apply", do_dialog_apply },
998     { "presets-commit", do_presets_commit },
999     { "log-level", do_log_level },
1000     { "replay", do_replay },
1001     { "decrease-visibility", do_decrease_visibility },
1002     { "increase-visibility", do_increase_visibility },
1003     { 0, 0 }                    // zero-terminated
1004 };
1005
1006
1007 /**
1008  * Initialize the default built-in commands.
1009  *
1010  * Other commands may be added by other parts of the application.
1011  */
1012 void
1013 fgInitCommands ()
1014 {
1015   SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1016   for (int i = 0; built_ins[i].name != 0; i++) {
1017     SG_LOG(SG_GENERAL, SG_INFO, "  " << built_ins[i].name);
1018     globals->get_commands()->addCommand(built_ins[i].name,
1019                                         built_ins[i].command);
1020   }
1021
1022   typedef bool (*dummy)();
1023   fgTie( "/command/view/next", dummy(0), do_view_next );
1024   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1025 }
1026
1027 // end of fg_commands.cxx