]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
ff079276e6d134c2e8ac88d9e7b2446fc4761b75
[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 <Environment/environment.hxx>
20 #include <FDM/flight.hxx>
21 #include <GUI/gui.h>
22 #include <GUI/new_gui.hxx>
23 #include <GUI/dialog.hxx>
24 #include <Replay/replay.hxx>
25 #include <Scenery/tilemgr.hxx>
26 #if defined(HAVE_PLIB_PSL)
27 #  include <Scripting/scriptmgr.hxx>
28 #endif
29 #include <Time/sunsolver.hxx>
30 #include <Time/tmp.hxx>
31
32 #include "fg_init.hxx"
33 #include "fg_io.hxx"
34 #include "fg_commands.hxx"
35 #include "fg_props.hxx"
36 #include "globals.hxx"
37 #include "logger.cxx"
38 #include "util.hxx"
39 #include "viewmgr.hxx"
40
41 SG_USING_STD(string);
42 SG_USING_STD(ifstream);
43 SG_USING_STD(ofstream);
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             SGSubsystem * 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     globals->get_event_mgr()->reinit();
217
218     return result;
219 }
220
221 /**
222  * Built-in command: suspend one or more subsystems.
223  *
224  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
225  */
226 static bool
227 do_suspend (const SGPropertyNode * arg)
228 {
229     bool result = true;
230
231     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
232     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
233         const char * name = subsystems[i]->getStringValue();
234         SGSubsystem * subsystem = globals->get_subsystem(name);
235         if (subsystem == 0) {
236             result = false;
237             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
238         } else {
239             subsystem->suspend();
240         }
241     }
242     return result;
243 }
244
245 /**
246  * Built-in command: suspend one or more subsystems.
247  *
248  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
249  */
250 static bool
251 do_resume (const SGPropertyNode * arg)
252 {
253     bool result = true;
254
255     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
256     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
257         const char * name = subsystems[i]->getStringValue();
258         SGSubsystem * subsystem = globals->get_subsystem(name);
259         if (subsystem == 0) {
260             result = false;
261             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
262         } else {
263             subsystem->resume();
264         }
265     }
266     return result;
267 }
268
269
270 /**
271  * Built-in command: load flight.
272  *
273  * file (optional): the name of the file to load (relative to current
274  *   directory).  Defaults to "fgfs.sav"
275  */
276 static bool
277 do_load (const SGPropertyNode * arg)
278 {
279   const string &file = arg->getStringValue("file", "fgfs.sav");
280   ifstream input(file.c_str());
281   if (input.good() && fgLoadFlight(input)) {
282     input.close();
283     SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
284     return true;
285   } else {
286     SG_LOG(SG_INPUT, SG_ALERT, "Cannot load flight from " << file);
287     return false;
288   }
289 }
290
291
292 /**
293  * Built-in command: save flight.
294  *
295  * file (optional): the name of the file to save (relative to the
296  * current directory).  Defaults to "fgfs.sav".
297  */
298 static bool
299 do_save (const SGPropertyNode * arg)
300 {
301   const string &file = arg->getStringValue("file", "fgfs.sav");
302   bool write_all = arg->getBoolValue("write-all", false);
303   SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
304   ofstream output(file.c_str());
305   if (output.good() && fgSaveFlight(output, write_all)) {
306     output.close();
307     SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
308     return true;
309   } else {
310     SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
311     return false;
312   }
313 }
314
315
316 /**
317  * Built-in command: (re)load the panel.
318  *
319  * path (optional): the file name to load the panel from 
320  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
321  * and if that's unspecified, to "Panels/Default/default.xml".
322  */
323 static bool
324 do_panel_load (const SGPropertyNode * arg)
325 {
326   string panel_path =
327     arg->getStringValue("path",
328                         fgGetString("/sim/panel/path",
329                                     "Panels/Default/default.xml"));
330   FGPanel * new_panel = fgReadPanel(panel_path);
331   if (new_panel == 0) {
332     SG_LOG(SG_INPUT, SG_ALERT,
333            "Error reading new panel from " << panel_path);
334     return false;
335   }
336   SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
337   globals->get_current_panel()->unbind();
338   delete globals->get_current_panel();
339   globals->set_current_panel( new_panel );
340   globals->get_current_panel()->bind();
341   return true;
342 }
343
344
345 /**
346  * Built-in command: pass a mouse click to the panel.
347  *
348  * button: the mouse button number, zero-based.
349  * is-down: true if the button is down, false if it is up.
350  * x-pos: the x position of the mouse click.
351  * y-pos: the y position of the mouse click.
352  */
353 static bool
354 do_panel_mouse_click (const SGPropertyNode * arg)
355 {
356   if (globals->get_current_panel() != 0)
357     return globals->get_current_panel()
358       ->doMouseAction(arg->getIntValue("button"),
359                       arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
360                       arg->getIntValue("x-pos"),
361                       arg->getIntValue("y-pos"));
362   else
363     return false;
364 }
365
366
367 /**
368  * Built-in command: (re)load preferences.
369  *
370  * path (optional): the file name to load the panel from (relative
371  * to FG_ROOT). Defaults to "preferences.xml".
372  */
373 static bool
374 do_preferences_load (const SGPropertyNode * arg)
375 {
376   try {
377     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
378                 globals->get_props());
379   } catch (const sg_exception &e) {
380     guiErrorMessage("Error reading global preferences: ", e);
381     return false;
382   }
383   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
384   return true;
385 }
386
387
388 static void
389 fix_hud_visibility()
390 {
391   if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
392       globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
393       if ( globals->get_viewmgr()->get_current() == 1 ) {
394           globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
395       }
396   }
397 }
398
399 static void
400 do_view_next( bool )
401 {
402     globals->get_current_view()->setHeadingOffset_deg(0.0);
403     globals->get_viewmgr()->next_view();
404     fix_hud_visibility();
405     globals->get_tile_mgr()->refresh_view_timestamps();
406 }
407
408 static void
409 do_view_prev( bool )
410 {
411     globals->get_current_view()->setHeadingOffset_deg(0.0);
412     globals->get_viewmgr()->prev_view();
413     fix_hud_visibility();
414     globals->get_tile_mgr()->refresh_view_timestamps();
415 }
416
417 /**
418  * Built-in command: cycle view.
419  */
420 static bool
421 do_view_cycle (const SGPropertyNode * arg)
422 {
423   globals->get_current_view()->setHeadingOffset_deg(0.0);
424   globals->get_viewmgr()->next_view();
425   fix_hud_visibility();
426   globals->get_tile_mgr()->refresh_view_timestamps();
427 //   fgReshape(fgGetInt("/sim/startup/xsize"), fgGetInt("/sim/startup/ysize"));
428   return true;
429 }
430
431 /**
432  * Built-in command: capture screen.
433  */
434 static bool
435 do_screen_capture (const SGPropertyNode * arg)
436 {
437   fgDumpSnapShot();
438   return true;
439 }
440
441
442 /**
443  * Reload the tile cache.
444  */
445 static bool
446 do_tile_cache_reload (const SGPropertyNode * arg)
447 {
448     static const SGPropertyNode *master_freeze
449         = fgGetNode("/sim/freeze/master");
450     bool freeze = master_freeze->getBoolValue();
451     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
452     if ( !freeze ) {
453         fgSetBool("/sim/freeze/master", true);
454     }
455     // BusyCursor(0);
456     if ( globals->get_tile_mgr()->init() ) {
457         // Load the local scenery data
458         double visibility_meters = fgGetDouble("/environment/visibility-m");
459         globals->get_tile_mgr()->update( visibility_meters );
460     } else {
461         SG_LOG( SG_GENERAL, SG_ALERT, 
462                 "Error in Tile Manager initialization!" );
463         exit(-1);
464     }
465     // BusyCursor(1);
466     if ( !freeze ) {
467         fgSetBool("/sim/freeze/master", false);
468     }
469     return true;
470 }
471
472
473 /**
474  * Set the outside air temperature at the "current" altitude by first
475  * calculating the corresponding sea level temp, and assigning that to
476  * all boundary and aloft environment layers.
477  */
478 static bool
479 do_set_oat_degc (const SGPropertyNode * arg)
480 {
481     const string &temp_str = arg->getStringValue("temp-degc", "15.0");
482
483     static const SGPropertyNode *altitude_ft
484       = fgGetNode("/position/altitude-ft");
485
486     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
487     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
488     dummy.set_temperature_degc( atof( temp_str.c_str() ) );
489     double temp_sea_level_degc = dummy.get_temperature_sea_level_degc();
490
491     cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
492     cout << "Temp at alt (C) = " << atof( temp_str.c_str() ) << endl;
493     cout << "Temp sea level (C) = " << temp_sea_level_degc << endl;
494  
495     SGPropertyNode *node, *child;
496
497     // boundary layers
498     node = fgGetNode( "/environment/config/boundary" );
499     if ( node != NULL ) {
500       int i = 0;
501       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
502         child->setDoubleValue( "temperature-sea-level-degc",
503                                temp_sea_level_degc );
504         ++i;
505       }
506     }
507
508     // aloft layers
509     node = fgGetNode( "/environment/config/aloft" );
510     if ( node != NULL ) {
511       int i = 0;
512       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
513         child->setDoubleValue( "temperature-sea-level-degc",
514                                temp_sea_level_degc );
515         ++i;
516       }
517     }
518
519     return true;
520 }
521
522 /**
523  * Update the lighting manually.
524  */
525 static bool
526 do_timeofday (const SGPropertyNode * arg)
527 {
528     const string &offset_type = arg->getStringValue("timeofday", "noon");
529
530     static const SGPropertyNode *longitude
531         = fgGetNode("/position/longitude-deg");
532     static const SGPropertyNode *latitude
533         = fgGetNode("/position/latitude-deg");
534     static const SGPropertyNode *cur_time_override
535         = fgGetNode("/sim/time/cur-time-override", true);
536
537     int orig_warp = globals->get_warp();
538     SGTime *t = globals->get_time_params();
539     time_t cur_time = t->get_cur_time();
540     // cout << "cur_time = " << cur_time << endl;
541     // cout << "orig_warp = " << orig_warp << endl;
542
543     int warp = 0;
544     if ( offset_type == "real" ) {
545         warp = -orig_warp;
546     } else if ( offset_type == "dawn" ) {
547         warp = fgTimeSecondsUntilSunAngle( cur_time,
548                                            longitude->getDoubleValue()
549                                              * SGD_DEGREES_TO_RADIANS,
550                                            latitude->getDoubleValue()
551                                              * SGD_DEGREES_TO_RADIANS,
552                                            90.0, true ); 
553     } else if ( offset_type == "morning" ) {
554         warp = fgTimeSecondsUntilSunAngle( cur_time,
555                                            longitude->getDoubleValue()
556                                              * SGD_DEGREES_TO_RADIANS,
557                                            latitude->getDoubleValue()
558                                              * SGD_DEGREES_TO_RADIANS,
559                                            75.0, true ); 
560     } else if ( offset_type == "noon" ) {
561         warp = fgTimeSecondsUntilSunAngle( cur_time,
562                                            longitude->getDoubleValue()
563                                              * SGD_DEGREES_TO_RADIANS,
564                                            latitude->getDoubleValue()
565                                              * SGD_DEGREES_TO_RADIANS,
566                                            0.0, true ); 
567     } else if ( offset_type == "afternoon" ) {
568         warp = fgTimeSecondsUntilSunAngle( cur_time,
569                                            longitude->getDoubleValue()
570                                              * SGD_DEGREES_TO_RADIANS,
571                                            latitude->getDoubleValue()
572                                              * SGD_DEGREES_TO_RADIANS,
573                                            60.0, false ); 
574      } else if ( offset_type == "dusk" ) {
575         warp = fgTimeSecondsUntilSunAngle( cur_time,
576                                            longitude->getDoubleValue()
577                                              * SGD_DEGREES_TO_RADIANS,
578                                            latitude->getDoubleValue()
579                                              * SGD_DEGREES_TO_RADIANS,
580                                            90.0, false ); 
581      } else if ( offset_type == "evening" ) {
582         warp = fgTimeSecondsUntilSunAngle( cur_time,
583                                            longitude->getDoubleValue()
584                                              * SGD_DEGREES_TO_RADIANS,
585                                            latitude->getDoubleValue()
586                                              * SGD_DEGREES_TO_RADIANS,
587                                            100.0, false ); 
588     } else if ( offset_type == "midnight" ) {
589         warp = fgTimeSecondsUntilSunAngle( cur_time,
590                                            longitude->getDoubleValue()
591                                              * SGD_DEGREES_TO_RADIANS,
592                                            latitude->getDoubleValue()
593                                              * SGD_DEGREES_TO_RADIANS,
594                                            180.0, false ); 
595     }
596     // cout << "warp = " << warp << endl;
597     globals->set_warp( orig_warp + warp );
598
599     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
600                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
601                cur_time_override->getLongValue(),
602                globals->get_warp() );
603
604     return true;
605 }
606
607
608 /**
609  * Built-in command: toggle a bool property value.
610  *
611  * property: The name of the property to toggle.
612  */
613 static bool
614 do_property_toggle (const SGPropertyNode * arg)
615 {
616   SGPropertyNode * prop = get_prop(arg);
617   return prop->setBoolValue(!prop->getBoolValue());
618 }
619
620
621 /**
622  * Built-in command: assign a value to a property.
623  *
624  * property: the name of the property to assign.
625  * value: the value to assign; or
626  * property[1]: the property to copy from.
627  */
628 static bool
629 do_property_assign (const SGPropertyNode * arg)
630 {
631   SGPropertyNode * prop = get_prop(arg);
632   const SGPropertyNode * prop2 = get_prop2(arg);
633   const SGPropertyNode * value = arg->getNode("value");
634
635   if (value != 0)
636       return prop->setUnspecifiedValue(value->getStringValue());
637   else if (prop2)
638       return prop->setUnspecifiedValue(prop2->getStringValue());
639   else
640       return false;
641 }
642
643
644 /**
645  * Built-in command: increment or decrement a property value.
646  *
647  * If the 'step' argument is present, it will be used; otherwise,
648  * the command uses 'offset' and 'factor', usually from the mouse.
649  *
650  * property: the name of the property to increment or decrement.
651  * step: the amount of the increment or decrement (default: 0).
652  * offset: offset from the current setting (used for the mouse; multiplied 
653  *         by factor)
654  * factor: scaling amount for the offset (defaults to 1).
655  * min: the minimum allowed value (default: no minimum).
656  * max: the maximum allowed value (default: no maximum).
657  * mask: 'integer' to apply only to the left of the decimal point, 
658  *       'decimal' to apply only to the right of the decimal point,
659  *       or 'all' to apply to the whole number (the default).
660  * wrap: true if the value should be wrapped when it passes min or max;
661  *       both min and max must be present for this to work (default:
662  *       false).
663  */
664 static bool
665 do_property_adjust (const SGPropertyNode * arg)
666 {
667   SGPropertyNode * prop = get_prop(arg);
668
669   double amount = 0;
670   if (arg->hasValue("step"))
671       amount = arg->getDoubleValue("step");
672   else
673       amount = (arg->getDoubleValue("factor", 1)
674                 * arg->getDoubleValue("offset"));
675           
676   double unmodifiable, modifiable;
677   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
678               &unmodifiable, &modifiable);
679   modifiable += amount;
680   limit_value(&modifiable, arg);
681
682   prop->setDoubleValue(unmodifiable + modifiable);
683
684   return true;
685 }
686
687
688 /**
689  * Built-in command: multiply a property value.
690  *
691  * property: the name of the property to multiply.
692  * factor: the amount by which to multiply.
693  * min: the minimum allowed value (default: no minimum).
694  * max: the maximum allowed value (default: no maximum).
695  * mask: 'integer' to apply only to the left of the decimal point, 
696  *       'decimal' to apply only to the right of the decimal point,
697  *       or 'all' to apply to the whole number (the default).
698  * wrap: true if the value should be wrapped when it passes min or max;
699  *       both min and max must be present for this to work (default:
700  *       false).
701  */
702 static bool
703 do_property_multiply (const SGPropertyNode * arg)
704 {
705   SGPropertyNode * prop = get_prop(arg);
706   double factor = arg->getDoubleValue("factor", 1);
707
708   double unmodifiable, modifiable;
709   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
710               &unmodifiable, &modifiable);
711   modifiable *= factor;
712   limit_value(&modifiable, arg);
713
714   prop->setDoubleValue(unmodifiable + modifiable);
715
716   return true;
717 }
718
719
720 /**
721  * Built-in command: swap two property values.
722  *
723  * property[0]: the name of the first property.
724  * property[1]: the name of the second property.
725  */
726 static bool
727 do_property_swap (const SGPropertyNode * arg)
728 {
729   SGPropertyNode * prop1 = get_prop(arg);
730   SGPropertyNode * prop2 = get_prop2(arg);
731
732                                 // FIXME: inefficient
733   const string & tmp = prop1->getStringValue();
734   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
735           prop2->setUnspecifiedValue(tmp.c_str()));
736 }
737
738
739 /**
740  * Built-in command: Set a property to an axis or other moving input.
741  *
742  * property: the name of the property to set.
743  * setting: the current input setting, usually between -1.0 and 1.0.
744  * offset: the offset to shift by, before applying the factor.
745  * factor: the factor to multiply by (use negative to reverse).
746  */
747 static bool
748 do_property_scale (const SGPropertyNode * arg)
749 {
750   SGPropertyNode * prop = get_prop(arg);
751   double setting = arg->getDoubleValue("setting");
752   double offset = arg->getDoubleValue("offset", 0.0);
753   double factor = arg->getDoubleValue("factor", 1.0);
754   bool squared = arg->getBoolValue("squared", false);
755   int power = arg->getIntValue("power", (squared ? 2 : 1));
756
757   int sign = (setting < 0 ? -1 : 1);
758
759   switch (power) {
760   case 1:
761       break;
762   case 2:
763       setting = setting * setting * sign;
764       break;
765   case 3:
766       setting = setting * setting * setting;
767       break;
768   case 4:
769       setting = setting * setting * setting * setting * sign;
770       break;
771   default:
772       setting =  pow(setting, power);
773       if ((power % 2) == 0)
774           setting *= sign;
775       break;
776   }
777
778   return prop->setDoubleValue((setting + offset) * factor);
779 }
780
781
782 /**
783  * Built-in command: cycle a property through a set of values.
784  *
785  * If the current value isn't in the list, the cycle will
786  * (re)start from the beginning.
787  *
788  * property: the name of the property to cycle.
789  * value[*]: the list of values to cycle through.
790  */
791 static bool
792 do_property_cycle (const SGPropertyNode * arg)
793 {
794     SGPropertyNode * prop = get_prop(arg);
795     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
796     int selection = -1;
797     int nSelections = values.size();
798
799     if (nSelections < 1) {
800         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
801         return false;
802     }
803
804                                 // Try to find the current selection
805     for (int i = 0; i < nSelections; i++) {
806         if (compare_values(prop, values[i])) {
807             selection = i + 1;
808             break;
809         }
810     }
811
812                                 // Default or wrap to the first selection
813     if (selection < 0 || selection >= nSelections)
814         selection = 0;
815
816     prop->setUnspecifiedValue(values[selection]->getStringValue());
817     return true;
818 }
819
820
821 /**
822  * Built-in command: randomize a numeric property value.
823  *
824  * property: the name of the property value to randomize.
825  * min: the minimum allowed value.
826  * max: the maximum allowed value.
827  */
828 static bool
829 do_property_randomize (const SGPropertyNode * arg)
830 {
831     SGPropertyNode * prop = get_prop(arg);
832     double min = arg->getDoubleValue("min", DBL_MIN);
833     double max = arg->getDoubleValue("max", DBL_MAX);
834     prop->setDoubleValue(sg_random() * (max - min) + min);
835     return true;
836 }
837
838
839 /**
840  * Built-in command: Show an XML-configured dialog.
841  *
842  * dialog-name: the name of the GUI dialog to display.
843  */
844 static bool
845 do_data_logging_commit (const SGPropertyNode * arg)
846 {
847     FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
848     log->reinit();
849     return true;
850 }
851
852
853 /**
854  * Built-in command: Show an XML-configured dialog.
855  *
856  * dialog-name: the name of the GUI dialog to display.
857  */
858 static bool
859 do_dialog_show (const SGPropertyNode * arg)
860 {
861     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
862     gui->showDialog(arg->getStringValue("dialog-name"));
863     return true;
864 }
865
866
867 /**
868  * Built-in Command: Hide the active XML-configured dialog.
869  */
870 static bool
871 do_dialog_close (const SGPropertyNode * arg)
872 {
873     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
874     return gui->closeActiveDialog();
875 }
876
877
878 /**
879  * Update a value in the active XML-configured dialog.
880  *
881  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
882  */
883 static bool
884 do_dialog_update (const SGPropertyNode * arg)
885 {
886     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
887     FGDialog * dialog = gui->getActiveDialog();
888     if (dialog != 0) {
889         if (arg->hasValue("object-name")) {
890             dialog->updateValue(arg->getStringValue("object-name"));
891         } else {
892             dialog->updateValues();
893         }
894         return true;
895     } else {
896         return false;
897     }
898 }
899
900
901 /**
902  * Apply a value in the active XML-configured dialog.
903  *
904  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
905  */
906 static bool
907 do_dialog_apply (const SGPropertyNode * arg)
908 {
909     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
910     FGDialog * dialog = gui->getActiveDialog();
911     if (dialog != 0) {
912         if (arg->hasValue("object-name")) {
913             const char * name = arg->getStringValue("object-name");
914             dialog->applyValue(name);
915             dialog->updateValue(name);
916         } else {
917             dialog->applyValues();
918             dialog->updateValues();
919         }
920         return true;
921     } else {
922         return false;
923     }
924 }
925
926
927 /**
928  * Built-in command: commit presets (read from in /sim/presets/)
929  */
930 static bool
931 do_presets_commit (const SGPropertyNode * arg)
932 {
933     // unbind the current fdm state so property changes
934     // don't get lost when we subsequently delete this fdm
935     // and create a new one.
936     cur_fdm_state->unbind();
937         
938     // set position from presets
939     fgInitPosition();
940
941     // BusyCursor(0);
942     fgReInitSubsystems();
943
944     globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
945
946 #if 0
947     if ( ! fgGetBool("/sim/presets/onground") ) {
948         fgSetBool( "/sim/freeze/master", true );
949         fgSetBool( "/sim/freeze/clock", true );
950     }
951 #endif
952
953     return true;
954 }
955
956 /**
957  * Built-in command: set log level (0 ... 7)
958  */
959 static bool
960 do_log_level (const SGPropertyNode * arg)
961 {
962    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
963
964    return true;
965 }
966
967 /**
968  * Built-in command: replay the FDR buffer
969  */
970 static bool
971 do_replay (const SGPropertyNode * arg)
972 {
973     // freeze the master fdm
974     fgSetBool( "/sim/freeze/replay", true );
975
976     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
977
978     fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
979     fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
980     double duration = fgGetDouble( "/sim/replay/duration" );
981     if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
982         fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
983     } else {
984         fgSetDouble( "/sim/replay/time", r->get_start_time() );
985     }
986
987     cout << "start = " << r->get_start_time()
988          << "  end = " << r->get_end_time() << endl;
989
990     return true;
991 }
992
993
994
995 static bool
996 do_decrease_visibility (const SGPropertyNode * arg)
997 {
998     double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
999     fgSetDouble("/environment/visibility-m", new_value);
1000     fgDefaultWeatherValue("visibility-m", new_value);
1001     globals->get_subsystem("environment")->reinit();
1002
1003     return true;
1004 }
1005  
1006 static bool
1007 do_increase_visibility (const SGPropertyNode * arg)
1008 {
1009     double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
1010     fgSetDouble("/environment/visibility-m", new_value);
1011     fgDefaultWeatherValue("visibility-m", new_value);
1012     globals->get_subsystem("environment")->reinit();
1013
1014     return true;
1015 }
1016
1017
1018 ////////////////////////////////////////////////////////////////////////
1019 // Command setup.
1020 ////////////////////////////////////////////////////////////////////////
1021
1022
1023 /**
1024  * Table of built-in commands.
1025  *
1026  * New commands do not have to be added here; any module in the application
1027  * can add a new command using globals->get_commands()->addCommand(...).
1028  */
1029 static struct {
1030   const char * name;
1031   SGCommandMgr::command_t command;
1032 } built_ins [] = {
1033     { "null", do_null },
1034 #if defined(HAVE_PLIB_PSL)
1035     { "script", do_script },
1036 #endif // HAVE_PLIB_PSL
1037     { "exit", do_exit },
1038     { "reinit", do_reinit },
1039     { "suspend", do_reinit },
1040     { "resume", do_reinit },
1041     { "load", do_load },
1042     { "save", do_save },
1043     { "panel-load", do_panel_load },
1044     { "panel-mouse-click", do_panel_mouse_click },
1045     { "preferences-load", do_preferences_load },
1046     { "view-cycle", do_view_cycle },
1047     { "screen-capture", do_screen_capture },
1048     { "tile-cache-reload", do_tile_cache_reload },
1049     { "set-outside-air-temp-degc", do_set_oat_degc },
1050     { "timeofday", do_timeofday },
1051     { "property-toggle", do_property_toggle },
1052     { "property-assign", do_property_assign },
1053     { "property-adjust", do_property_adjust },
1054     { "property-multiply", do_property_multiply },
1055     { "property-swap", do_property_swap },
1056     { "property-scale", do_property_scale },
1057     { "property-cycle", do_property_cycle },
1058     { "property-randomize", do_property_randomize },
1059     { "data-logging-commit", do_data_logging_commit },
1060     { "dialog-show", do_dialog_show },
1061     { "dialog-close", do_dialog_close },
1062     { "dialog-show", do_dialog_show },
1063     { "dialog-update", do_dialog_update },
1064     { "dialog-apply", do_dialog_apply },
1065     { "presets-commit", do_presets_commit },
1066     { "log-level", do_log_level },
1067     { "replay", do_replay },
1068     { "decrease-visibility", do_decrease_visibility },
1069     { "increase-visibility", do_increase_visibility },
1070     { 0, 0 }                    // zero-terminated
1071 };
1072
1073
1074 /**
1075  * Initialize the default built-in commands.
1076  *
1077  * Other commands may be added by other parts of the application.
1078  */
1079 void
1080 fgInitCommands ()
1081 {
1082   SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1083   for (int i = 0; built_ins[i].name != 0; i++) {
1084     SG_LOG(SG_GENERAL, SG_INFO, "  " << built_ins[i].name);
1085     globals->get_commands()->addCommand(built_ins[i].name,
1086                                         built_ins[i].command);
1087   }
1088
1089   typedef bool (*dummy)();
1090   fgTie( "/command/view/next", dummy(0), do_view_next );
1091   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1092 }
1093
1094 // end of fg_commands.cxx