]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
50ab54f307a660b8a870d5cda425943dbc7824da
[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_lighting_update (const SGPropertyNode * arg)
476 {
477   fgUpdateSkyAndLightingParams();
478   return true;
479 }
480
481
482 /**
483  * Update the lighting manually.
484  */
485 static bool
486 do_timeofday (const SGPropertyNode * arg)
487 {
488     const string &offset_type = arg->getStringValue("timeofday", "noon");
489
490     static const SGPropertyNode *longitude
491         = fgGetNode("/position/longitude-deg");
492     static const SGPropertyNode *latitude
493         = fgGetNode("/position/latitude-deg");
494     static const SGPropertyNode *cur_time_override
495         = fgGetNode("/sim/time/cur-time-override", true);
496
497     SGTime *t = globals->get_time_params();
498     int orig_warp = globals->get_warp();
499     time_t cur_time = t->get_cur_time();
500     cout << "cur_time = " << cur_time << endl;
501     cout << "orig_warp = " << orig_warp << endl;
502
503     int warp = 0;
504     if ( offset_type == "noon" ) {
505         warp = fgTimeSecondsUntilNoon( cur_time,
506                                        longitude->getDoubleValue()
507                                          * SGD_DEGREES_TO_RADIANS,
508                                        latitude->getDoubleValue()
509                                          * SGD_DEGREES_TO_RADIANS ); 
510     } else if ( offset_type == "midnight" ) {
511         warp = fgTimeSecondsUntilMidnight( cur_time,
512                                            longitude->getDoubleValue()
513                                              * SGD_DEGREES_TO_RADIANS,
514                                            latitude->getDoubleValue()
515                                              * SGD_DEGREES_TO_RADIANS ); 
516     } else if ( offset_type == "dawn" ) {
517         warp = fgTimeSecondsUntilDawn( cur_time,
518                                        longitude->getDoubleValue()
519                                          * SGD_DEGREES_TO_RADIANS,
520                                        latitude->getDoubleValue()
521                                          * SGD_DEGREES_TO_RADIANS ); 
522      } else if ( offset_type == "dusk" ) {
523         warp = fgTimeSecondsUntilDusk( cur_time,
524                                        longitude->getDoubleValue()
525                                          * SGD_DEGREES_TO_RADIANS,
526                                        latitude->getDoubleValue()
527                                          * SGD_DEGREES_TO_RADIANS ); 
528     }
529     cout << "warp = " << warp << endl;
530     globals->set_warp( orig_warp + warp );
531
532     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
533                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
534                cur_time_override->getLongValue(),
535                globals->get_warp() );
536
537     fgUpdateSkyAndLightingParams();
538
539     return true;
540 }
541
542
543 /**
544  * Built-in command: toggle a bool property value.
545  *
546  * property: The name of the property to toggle.
547  */
548 static bool
549 do_property_toggle (const SGPropertyNode * arg)
550 {
551   SGPropertyNode * prop = get_prop(arg);
552   return prop->setBoolValue(!prop->getBoolValue());
553 }
554
555
556 /**
557  * Built-in command: assign a value to a property.
558  *
559  * property: the name of the property to assign.
560  * value: the value to assign; or
561  * property[1]: the property to copy from.
562  */
563 static bool
564 do_property_assign (const SGPropertyNode * arg)
565 {
566   SGPropertyNode * prop = get_prop(arg);
567   const SGPropertyNode * prop2 = get_prop2(arg);
568   const SGPropertyNode * value = arg->getNode("value");
569
570   if (value != 0)
571       return prop->setUnspecifiedValue(value->getStringValue());
572   else if (prop2)
573       return prop->setUnspecifiedValue(prop2->getStringValue());
574   else
575       return false;
576 }
577
578
579 /**
580  * Built-in command: increment or decrement a property value.
581  *
582  * If the 'step' argument is present, it will be used; otherwise,
583  * the command uses 'offset' and 'factor', usually from the mouse.
584  *
585  * property: the name of the property to increment or decrement.
586  * step: the amount of the increment or decrement (default: 0).
587  * offset: offset from the current setting (used for the mouse; multiplied 
588  *         by factor)
589  * factor: scaling amount for the offset (defaults to 1).
590  * min: the minimum allowed value (default: no minimum).
591  * max: the maximum allowed value (default: no maximum).
592  * mask: 'integer' to apply only to the left of the decimal point, 
593  *       'decimal' to apply only to the right of the decimal point,
594  *       or 'all' to apply to the whole number (the default).
595  * wrap: true if the value should be wrapped when it passes min or max;
596  *       both min and max must be present for this to work (default:
597  *       false).
598  */
599 static bool
600 do_property_adjust (const SGPropertyNode * arg)
601 {
602   SGPropertyNode * prop = get_prop(arg);
603
604   double amount = 0;
605   if (arg->hasValue("step"))
606       amount = arg->getDoubleValue("step");
607   else
608       amount = (arg->getDoubleValue("factor", 1)
609                 * arg->getDoubleValue("offset"));
610           
611   double unmodifiable, modifiable;
612   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
613               &unmodifiable, &modifiable);
614   modifiable += amount;
615   limit_value(&modifiable, arg);
616
617   prop->setDoubleValue(unmodifiable + modifiable);
618
619   return true;
620 }
621
622
623 /**
624  * Built-in command: multiply a property value.
625  *
626  * property: the name of the property to multiply.
627  * factor: the amount by which to multiply.
628  * min: the minimum allowed value (default: no minimum).
629  * max: the maximum allowed value (default: no maximum).
630  * mask: 'integer' to apply only to the left of the decimal point, 
631  *       'decimal' to apply only to the right of the decimal point,
632  *       or 'all' to apply to the whole number (the default).
633  * wrap: true if the value should be wrapped when it passes min or max;
634  *       both min and max must be present for this to work (default:
635  *       false).
636  */
637 static bool
638 do_property_multiply (const SGPropertyNode * arg)
639 {
640   SGPropertyNode * prop = get_prop(arg);
641   double factor = arg->getDoubleValue("factor", 1);
642
643   double unmodifiable, modifiable;
644   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
645               &unmodifiable, &modifiable);
646   modifiable *= factor;
647   limit_value(&modifiable, arg);
648
649   prop->setDoubleValue(unmodifiable + modifiable);
650
651   return true;
652 }
653
654
655 /**
656  * Built-in command: swap two property values.
657  *
658  * property[0]: the name of the first property.
659  * property[1]: the name of the second property.
660  */
661 static bool
662 do_property_swap (const SGPropertyNode * arg)
663 {
664   SGPropertyNode * prop1 = get_prop(arg);
665   SGPropertyNode * prop2 = get_prop2(arg);
666
667                                 // FIXME: inefficient
668   const string & tmp = prop1->getStringValue();
669   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
670           prop2->setUnspecifiedValue(tmp.c_str()));
671 }
672
673
674 /**
675  * Built-in command: Set a property to an axis or other moving input.
676  *
677  * property: the name of the property to set.
678  * setting: the current input setting, usually between -1.0 and 1.0.
679  * offset: the offset to shift by, before applying the factor.
680  * factor: the factor to multiply by (use negative to reverse).
681  */
682 static bool
683 do_property_scale (const SGPropertyNode * arg)
684 {
685   SGPropertyNode * prop = get_prop(arg);
686   double setting = arg->getDoubleValue("setting");
687   double offset = arg->getDoubleValue("offset", 0.0);
688   double factor = arg->getDoubleValue("factor", 1.0);
689   bool squared = arg->getBoolValue("squared", false);
690   int power = arg->getIntValue("power", (squared ? 2 : 1));
691
692   int sign = (setting < 0 ? -1 : 1);
693
694   switch (power) {
695   case 1:
696       break;
697   case 2:
698       setting = setting * setting * sign;
699       break;
700   case 3:
701       setting = setting * setting * setting;
702       break;
703   case 4:
704       setting = setting * setting * setting * setting * sign;
705       break;
706   default:
707       setting =  pow(setting, power);
708       if ((power % 2) == 0)
709           setting *= sign;
710       break;
711   }
712
713   return prop->setDoubleValue((setting + offset) * factor);
714 }
715
716
717 /**
718  * Built-in command: cycle a property through a set of values.
719  *
720  * If the current value isn't in the list, the cycle will
721  * (re)start from the beginning.
722  *
723  * property: the name of the property to cycle.
724  * value[*]: the list of values to cycle through.
725  */
726 static bool
727 do_property_cycle (const SGPropertyNode * arg)
728 {
729     SGPropertyNode * prop = get_prop(arg);
730     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
731     int selection = -1;
732     int nSelections = values.size();
733
734     if (nSelections < 1) {
735         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
736         return false;
737     }
738
739                                 // Try to find the current selection
740     for (int i = 0; i < nSelections; i++) {
741         if (compare_values(prop, values[i])) {
742             selection = i + 1;
743             break;
744         }
745     }
746
747                                 // Default or wrap to the first selection
748     if (selection < 0 || selection >= nSelections)
749         selection = 0;
750
751     prop->setUnspecifiedValue(values[selection]->getStringValue());
752     return true;
753 }
754
755
756 /**
757  * Built-in command: randomize a numeric property value.
758  *
759  * property: the name of the property value to randomize.
760  * min: the minimum allowed value.
761  * max: the maximum allowed value.
762  */
763 static bool
764 do_property_randomize (const SGPropertyNode * arg)
765 {
766     SGPropertyNode * prop = get_prop(arg);
767     double min = arg->getDoubleValue("min", DBL_MIN);
768     double max = arg->getDoubleValue("max", DBL_MAX);
769     prop->setDoubleValue(sg_random() * (max - min) + min);
770     return true;
771 }
772
773
774 /**
775  * Built-in command: Show an XML-configured dialog.
776  *
777  * dialog-name: the name of the GUI dialog to display.
778  */
779 static bool
780 do_dialog_show (const SGPropertyNode * arg)
781 {
782     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
783     gui->showDialog(arg->getStringValue("dialog-name"));
784     return true;
785 }
786
787
788 /**
789  * Built-in Command: Hide the active XML-configured dialog.
790  */
791 static bool
792 do_dialog_close (const SGPropertyNode * arg)
793 {
794     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
795     return gui->closeActiveDialog();
796 }
797
798
799 /**
800  * Update a value in the active XML-configured dialog.
801  *
802  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
803  */
804 static bool
805 do_dialog_update (const SGPropertyNode * arg)
806 {
807     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
808     FGDialog * dialog = gui->getActiveDialog();
809     if (dialog != 0) {
810         if (arg->hasValue("object-name")) {
811             dialog->updateValue(arg->getStringValue("object-name"));
812         } else {
813             dialog->updateValues();
814         }
815         return true;
816     } else {
817         return false;
818     }
819 }
820
821
822 /**
823  * Apply a value in the active XML-configured dialog.
824  *
825  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
826  */
827 static bool
828 do_dialog_apply (const SGPropertyNode * arg)
829 {
830     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
831     FGDialog * dialog = gui->getActiveDialog();
832     if (dialog != 0) {
833         if (arg->hasValue("object-name")) {
834             const char * name = arg->getStringValue("object-name");
835             dialog->applyValue(name);
836             dialog->updateValue(name);
837         } else {
838             dialog->applyValues();
839             dialog->updateValues();
840         }
841         return true;
842     } else {
843         return false;
844     }
845 }
846
847
848 /**
849  * Built-in command: commit presets (read from in /sim/presets/)
850  */
851 static bool
852 do_presets_commit (const SGPropertyNode * arg)
853 {
854     // unbind the current fdm state so property changes
855     // don't get lost when we subsequently delete this fdm
856     // and create a new one.
857     cur_fdm_state->unbind();
858         
859     // set position from presets
860     fgInitPosition();
861
862     // BusyCursor(0);
863     fgReInitSubsystems();
864
865     globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
866
867 #if 0
868     if ( ! fgGetBool("/sim/presets/onground") ) {
869         fgSetBool( "/sim/freeze/master", true );
870         fgSetBool( "/sim/freeze/clock", true );
871     }
872 #endif
873
874     return true;
875 }
876
877 /**
878  * Built-in command: set log level (0 ... 7)
879  */
880 static bool
881 do_log_level (const SGPropertyNode * arg)
882 {
883    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
884
885    return true;
886 }
887
888 /**
889  * Built-in command: replay the FDR buffer
890  */
891 static bool
892 do_replay (const SGPropertyNode * arg)
893 {
894     // freeze the master fdm
895     fgSetBool( "/sim/freeze/replay", true );
896
897     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
898
899     fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
900     fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
901     double duration = fgGetDouble( "/sim/replay/duration" );
902     if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
903         fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
904     } else {
905         fgSetDouble( "/sim/replay/time", r->get_start_time() );
906     }
907
908     cout << "start = " << r->get_start_time()
909          << "  end = " << r->get_end_time() << endl;
910
911     return true;
912 }
913
914
915
916 static bool
917 do_decrease_visibility (const SGPropertyNode * arg)
918 {
919     double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
920     fgSetDouble("/environment/visibility-m", new_value);
921     fgDefaultWeatherValue("visibility-m", new_value);
922     globals->get_subsystem("environment")->reinit();
923
924     return true;
925 }
926  
927 static bool
928 do_increase_visibility (const SGPropertyNode * arg)
929 {
930     double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
931     fgSetDouble("/environment/visibility-m", new_value);
932     fgDefaultWeatherValue("visibility-m", new_value);
933     globals->get_subsystem("environment")->reinit();
934
935     return true;
936 }
937
938
939 ////////////////////////////////////////////////////////////////////////
940 // Command setup.
941 ////////////////////////////////////////////////////////////////////////
942
943
944 /**
945  * Table of built-in commands.
946  *
947  * New commands do not have to be added here; any module in the application
948  * can add a new command using globals->get_commands()->addCommand(...).
949  */
950 static struct {
951   const char * name;
952   SGCommandMgr::command_t command;
953 } built_ins [] = {
954     { "null", do_null },
955 #if defined(HAVE_PLIB_PSL)
956     { "script", do_script },
957 #endif // HAVE_PLIB_PSL
958     { "exit", do_exit },
959     { "reinit", do_reinit },
960     { "suspend", do_reinit },
961     { "resume", do_reinit },
962     { "load", do_load },
963     { "save", do_save },
964     { "panel-load", do_panel_load },
965     { "panel-mouse-click", do_panel_mouse_click },
966     { "preferences-load", do_preferences_load },
967     { "view-cycle", do_view_cycle },
968     { "screen-capture", do_screen_capture },
969     { "tile-cache-reload", do_tile_cache_reload },
970     { "lighting-update", do_lighting_update },
971     { "timeofday", do_timeofday },
972     { "property-toggle", do_property_toggle },
973     { "property-assign", do_property_assign },
974     { "property-adjust", do_property_adjust },
975     { "property-multiply", do_property_multiply },
976     { "property-swap", do_property_swap },
977     { "property-scale", do_property_scale },
978     { "property-cycle", do_property_cycle },
979     { "property-randomize", do_property_randomize },
980     { "dialog-show", do_dialog_show },
981     { "dialog-close", do_dialog_close },
982     { "dialog-show", do_dialog_show },
983     { "dialog-update", do_dialog_update },
984     { "dialog-apply", do_dialog_apply },
985     { "presets-commit", do_presets_commit },
986     { "log-level", do_log_level },
987     { "replay", do_replay },
988     { "decrease-visibility", do_decrease_visibility },
989     { "increase-visibility", do_increase_visibility },
990     { 0, 0 }                    // zero-terminated
991 };
992
993
994 /**
995  * Initialize the default built-in commands.
996  *
997  * Other commands may be added by other parts of the application.
998  */
999 void
1000 fgInitCommands ()
1001 {
1002   SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1003   for (int i = 0; built_ins[i].name != 0; i++) {
1004     SG_LOG(SG_GENERAL, SG_INFO, "  " << built_ins[i].name);
1005     globals->get_commands()->addCommand(built_ins[i].name,
1006                                         built_ins[i].command);
1007   }
1008
1009   typedef bool (*dummy)();
1010   fgTie( "/command/view/next", dummy(0), do_view_next );
1011   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1012 }
1013
1014 // end of fg_commands.cxx