]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
79d6708cc488abe4b04de2aac04576306af80c3b
[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/debug/logstream.hxx>
12 #include <simgear/misc/commands.hxx>
13 #include <simgear/misc/props.hxx>
14 #include <simgear/sg_inlines.h>
15
16 #include <Cockpit/panel.hxx>
17 #include <Cockpit/panel_io.hxx>
18 #include <FDM/flight.hxx>
19 #include <GUI/gui.h>
20 #include <GUI/new_gui.hxx>
21 #include <GUI/dialog.hxx>
22 #include <Scenery/tilemgr.hxx>
23 #if defined(HAVE_PLIB_PSL)
24 #include <Scripting/scriptmgr.hxx>
25 #endif
26 #include <Time/tmp.hxx>
27
28 #include "fg_init.hxx"
29 #include "fg_commands.hxx"
30
31 SG_USING_STD(string);
32 SG_USING_STD(ifstream);
33 SG_USING_STD(ofstream);
34
35 #include "fg_props.hxx"
36 #include "fg_io.hxx"
37 #include "globals.hxx"
38 #include "viewmgr.hxx"
39
40
41 \f
42 ////////////////////////////////////////////////////////////////////////
43 // Static helper functions.
44 ////////////////////////////////////////////////////////////////////////
45
46
47 static inline SGPropertyNode *
48 get_prop (const SGPropertyNode * arg)
49 {
50     return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
51 }
52
53 static inline SGPropertyNode *
54 get_prop2 (const SGPropertyNode * arg)
55 {
56     return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
57 }
58
59
60 /**
61  * Get a double value and split it as required.
62  */
63 static void
64 split_value (double full_value, const char * mask,
65              double * unmodifiable, double * modifiable)
66 {
67     if (!strcmp("integer", mask)) {
68         *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
69         *unmodifiable = full_value - *modifiable;
70     } else if (!strcmp("decimal", mask)) {
71         *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
72         *modifiable = full_value - *unmodifiable;
73     } else {
74         if (strcmp("all", mask))
75             SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
76                    << " assuming 'all'");
77         *unmodifiable = 0;
78         *modifiable = full_value;
79     }
80 }
81
82
83 /**
84  * Clamp or wrap a value as specified.
85  */
86 static void
87 limit_value (double * value, const SGPropertyNode * arg)
88 {
89     const SGPropertyNode * min_node = arg->getChild("min");
90     const SGPropertyNode * max_node = arg->getChild("max");
91
92     bool wrap = arg->getBoolValue("wrap");
93
94     if (min_node == 0 || max_node == 0)
95         wrap = false;
96   
97     if (wrap) {                 // wrap such that min <= x < max
98         double min_val = min_node->getDoubleValue();
99         double max_val = max_node->getDoubleValue();
100         double resolution = arg->getDoubleValue("resolution");
101         if (resolution > 0.0) {
102             // snap to (min + N*resolution), taking special care to handle imprecision
103             int n = (int)floor((*value - min_val) / resolution + 0.5);
104             int steps = (int)floor((max_val - min_val) / resolution + 0.5);
105             SG_NORMALIZE_RANGE(n, 0, steps);
106             *value = min_val + resolution * n;
107         } else {
108             // plain circular wrapping
109             SG_NORMALIZE_RANGE(*value, min_val, max_val);
110         }
111     } else {                    // clamp such that min <= x <= max
112         if ((min_node != 0) && (*value < min_node->getDoubleValue()))
113             *value = min_node->getDoubleValue();
114         else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
115             *value = max_node->getDoubleValue();
116     }
117 }
118
119 static bool
120 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
121 {
122     switch (value1->getType()) {
123     case SGPropertyNode::BOOL:
124         return (value1->getBoolValue() == value2->getBoolValue());
125     case SGPropertyNode::INT:
126         return (value1->getIntValue() == value2->getIntValue());
127     case SGPropertyNode::LONG:
128         return (value1->getLongValue() == value2->getLongValue());
129     case SGPropertyNode::FLOAT:
130         return (value1->getFloatValue() == value2->getFloatValue());
131     case SGPropertyNode::DOUBLE:
132         return (value1->getDoubleValue() == value2->getDoubleValue());
133     default:
134         return !strcmp(value1->getStringValue(), value2->getStringValue());
135     }
136 }
137
138
139 \f
140 ////////////////////////////////////////////////////////////////////////
141 // Command implementations.
142 ////////////////////////////////////////////////////////////////////////
143
144
145 /**
146  * Built-in command: do nothing.
147  */
148 static bool
149 do_null (const SGPropertyNode * arg)
150 {
151   return true;
152 }
153
154 #if defined(HAVE_PLIB_PSL)
155 /**
156  * Built-in command: run a PSL script.
157  */
158 static bool
159 do_script (const SGPropertyNode * arg)
160 {
161     FGScriptMgr * mgr = (FGScriptMgr *)globals->get_subsystem("scripting");
162     return mgr->run(arg->getStringValue("script"));
163 }
164 #endif // HAVE_PLIB_PSL
165
166
167 /**
168  * Built-in command: exit FlightGear.
169  *
170  * TODO: show a confirm dialog.
171  */
172 static bool
173 do_exit (const SGPropertyNode * arg)
174 {
175   SG_LOG(SG_INPUT, SG_ALERT, "Program exit requested.");
176   ConfirmExitDialog();
177   return true;
178 }
179
180
181 /**
182  * Built-in command: load flight.
183  *
184  * file (optional): the name of the file to load (relative to current
185  * directory).  Defaults to "fgfs.sav".
186  */
187 static bool
188 do_load (const SGPropertyNode * arg)
189 {
190   const string &file = arg->getStringValue("file", "fgfs.sav");
191   ifstream input(file.c_str());
192   if (input.good() && fgLoadFlight(input)) {
193     input.close();
194     SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
195     return true;
196   } else {
197     SG_LOG(SG_INPUT, SG_ALERT, "Cannot load flight from " << file);
198     return false;
199   }
200 }
201
202
203 /**
204  * Built-in command: save flight.
205  *
206  * file (optional): the name of the file to save (relative to the
207  * current directory).  Defaults to "fgfs.sav".
208  */
209 static bool
210 do_save (const SGPropertyNode * arg)
211 {
212   const string &file = arg->getStringValue("file", "fgfs.sav");
213   bool write_all = arg->getBoolValue("write-all", false);
214   SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
215   ofstream output(file.c_str());
216   if (output.good() && fgSaveFlight(output, write_all)) {
217     output.close();
218     SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
219     return true;
220   } else {
221     SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
222     return false;
223   }
224 }
225
226
227 /**
228  * Built-in command: (re)load the panel.
229  *
230  * path (optional): the file name to load the panel from 
231  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
232  * and if that's unspecified, to "Panels/Default/default.xml".
233  */
234 static bool
235 do_panel_load (const SGPropertyNode * arg)
236 {
237   string panel_path =
238     arg->getStringValue("path",
239                         fgGetString("/sim/panel/path",
240                                     "Panels/Default/default.xml"));
241   FGPanel * new_panel = fgReadPanel(panel_path);
242   if (new_panel == 0) {
243     SG_LOG(SG_INPUT, SG_ALERT,
244            "Error reading new panel from " << panel_path);
245     return false;
246   }
247   SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
248   current_panel->unbind();
249   delete current_panel;
250   current_panel = new_panel;
251   current_panel->bind();
252   return true;
253 }
254
255
256 /**
257  * Built-in command: pass a mouse click to the panel.
258  *
259  * button: the mouse button number, zero-based.
260  * is-down: true if the button is down, false if it is up.
261  * x-pos: the x position of the mouse click.
262  * y-pos: the y position of the mouse click.
263  */
264 static bool
265 do_panel_mouse_click (const SGPropertyNode * arg)
266 {
267   if (current_panel != 0)
268     return current_panel
269       ->doMouseAction(arg->getIntValue("button"),
270                       arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
271                       arg->getIntValue("x-pos"),
272                       arg->getIntValue("y-pos"));
273   else
274     return false;
275 }
276
277
278 /**
279  * Built-in command: (re)load preferences.
280  *
281  * path (optional): the file name to load the panel from (relative
282  * to FG_ROOT). Defaults to "preferences.xml".
283  */
284 static bool
285 do_preferences_load (const SGPropertyNode * arg)
286 {
287   try {
288     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
289                 globals->get_props());
290   } catch (const sg_exception &e) {
291     guiErrorMessage("Error reading global preferences: ", e);
292     return false;
293   }
294   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
295   return true;
296 }
297
298
299 static void
300 fix_hud_visibility()
301 {
302   if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
303       globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
304       if ( globals->get_viewmgr()->get_current() == 1 ) {
305           globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
306       }
307   }
308 }
309
310 static void
311 do_view_next( bool )
312 {
313     globals->get_current_view()->setHeadingOffset_deg(0.0);
314     globals->get_viewmgr()->next_view();
315     fix_hud_visibility();
316     globals->get_tile_mgr()->refresh_view_timestamps();
317 }
318
319 static void
320 do_view_prev( bool )
321 {
322     globals->get_current_view()->setHeadingOffset_deg(0.0);
323     globals->get_viewmgr()->prev_view();
324     fix_hud_visibility();
325     globals->get_tile_mgr()->refresh_view_timestamps();
326 }
327
328 /**
329  * Built-in command: cycle view.
330  */
331 static bool
332 do_view_cycle (const SGPropertyNode * arg)
333 {
334   globals->get_current_view()->setHeadingOffset_deg(0.0);
335   globals->get_viewmgr()->next_view();
336   fix_hud_visibility();
337   globals->get_tile_mgr()->refresh_view_timestamps();
338 //   fgReshape(fgGetInt("/sim/startup/xsize"), fgGetInt("/sim/startup/ysize"));
339   return true;
340 }
341
342 /**
343  * Built-in command: capture screen.
344  */
345 static bool
346 do_screen_capture (const SGPropertyNode * arg)
347 {
348   fgDumpSnapShot();
349   return true;
350 }
351
352
353 /**
354  * Reload the tile cache.
355  */
356 static bool
357 do_tile_cache_reload (const SGPropertyNode * arg)
358 {
359     static const SGPropertyNode *master_freeze
360         = fgGetNode("/sim/freeze/master");
361     bool freeze = master_freeze->getBoolValue();
362     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
363     if ( !freeze ) {
364         fgSetBool("/sim/freeze/master", true);
365     }
366     // BusyCursor(0);
367     if ( globals->get_tile_mgr()->init() ) {
368         // Load the local scenery data
369         double visibility_meters = fgGetDouble("/environment/visibility-m");
370         globals->get_tile_mgr()->update( visibility_meters );
371     } else {
372         SG_LOG( SG_GENERAL, SG_ALERT, 
373                 "Error in Tile Manager initialization!" );
374         exit(-1);
375     }
376     // BusyCursor(1);
377     if ( !freeze ) {
378         fgSetBool("/sim/freeze/master", false);
379     }
380     return true;
381 }
382
383
384 /**
385  * Update the lighting manually.
386  */
387 static bool
388 do_lighting_update (const SGPropertyNode * arg)
389 {
390   fgUpdateSkyAndLightingParams();
391   return true;
392 }
393
394
395 /**
396  * Built-in command: toggle a bool property value.
397  *
398  * property: The name of the property to toggle.
399  */
400 static bool
401 do_property_toggle (const SGPropertyNode * arg)
402 {
403   SGPropertyNode * prop = get_prop(arg);
404   return prop->setBoolValue(!prop->getBoolValue());
405 }
406
407
408 /**
409  * Built-in command: assign a value to a property.
410  *
411  * property: the name of the property to assign.
412  * value: the value to assign; or
413  * property[1]: the property to copy from.
414  */
415 static bool
416 do_property_assign (const SGPropertyNode * arg)
417 {
418   SGPropertyNode * prop = get_prop(arg);
419   const SGPropertyNode * prop2 = get_prop2(arg);
420   const SGPropertyNode * value = arg->getNode("value");
421
422   if (value != 0)
423       return prop->setUnspecifiedValue(value->getStringValue());
424   else if (prop2)
425       return prop->setUnspecifiedValue(prop2->getStringValue());
426   else
427       return false;
428 }
429
430
431 /**
432  * Built-in command: increment or decrement a property value.
433  *
434  * If the 'step' argument is present, it will be used; otherwise,
435  * the command uses 'offset' and 'factor', usually from the mouse.
436  *
437  * property: the name of the property to increment or decrement.
438  * step: the amount of the increment or decrement (default: 0).
439  * offset: offset from the current setting (used for the mouse; multiplied 
440  *         by factor)
441  * factor: scaling amount for the offset (defaults to 1).
442  * min: the minimum allowed value (default: no minimum).
443  * max: the maximum allowed value (default: no maximum).
444  * mask: 'integer' to apply only to the left of the decimal point, 
445  *       'decimal' to apply only to the right of the decimal point,
446  *       or 'all' to apply to the whole number (the default).
447  * wrap: true if the value should be wrapped when it passes min or max;
448  *       both min and max must be present for this to work (default:
449  *       false).
450  */
451 static bool
452 do_property_adjust (const SGPropertyNode * arg)
453 {
454   SGPropertyNode * prop = get_prop(arg);
455
456   double amount = 0;
457   if (arg->hasValue("step"))
458       amount = arg->getDoubleValue("step");
459   else
460       amount = (arg->getDoubleValue("factor", 1)
461                 * arg->getDoubleValue("offset"));
462           
463   double unmodifiable, modifiable;
464   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
465               &unmodifiable, &modifiable);
466   modifiable += amount;
467   limit_value(&modifiable, arg);
468
469   prop->setDoubleValue(unmodifiable + modifiable);
470
471   return true;
472 }
473
474
475 /**
476  * Built-in command: multiply a property value.
477  *
478  * property: the name of the property to multiply.
479  * factor: the amount by which to multiply.
480  * min: the minimum allowed value (default: no minimum).
481  * max: the maximum allowed value (default: no maximum).
482  * mask: 'integer' to apply only to the left of the decimal point, 
483  *       'decimal' to apply only to the right of the decimal point,
484  *       or 'all' to apply to the whole number (the default).
485  * wrap: true if the value should be wrapped when it passes min or max;
486  *       both min and max must be present for this to work (default:
487  *       false).
488  */
489 static bool
490 do_property_multiply (const SGPropertyNode * arg)
491 {
492   SGPropertyNode * prop = get_prop(arg);
493   double factor = arg->getDoubleValue("factor", 1);
494
495   double unmodifiable, modifiable;
496   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
497               &unmodifiable, &modifiable);
498   modifiable *= factor;
499   limit_value(&modifiable, arg);
500
501   prop->setDoubleValue(unmodifiable + modifiable);
502
503   return true;
504 }
505
506
507 /**
508  * Built-in command: swap two property values.
509  *
510  * property[0]: the name of the first property.
511  * property[1]: the name of the second property.
512  */
513 static bool
514 do_property_swap (const SGPropertyNode * arg)
515 {
516   SGPropertyNode * prop1 = get_prop(arg);
517   SGPropertyNode * prop2 = get_prop2(arg);
518
519                                 // FIXME: inefficient
520   const string & tmp = prop1->getStringValue();
521   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
522           prop2->setUnspecifiedValue(tmp.c_str()));
523 }
524
525
526 /**
527  * Built-in command: Set a property to an axis or other moving input.
528  *
529  * property: the name of the property to set.
530  * setting: the current input setting, usually between -1.0 and 1.0.
531  * offset: the offset to shift by, before applying the factor.
532  * factor: the factor to multiply by (use negative to reverse).
533  */
534 static bool
535 do_property_scale (const SGPropertyNode * arg)
536 {
537   SGPropertyNode * prop = get_prop(arg);
538   double setting = arg->getDoubleValue("setting");
539   double offset = arg->getDoubleValue("offset", 0.0);
540   double factor = arg->getDoubleValue("factor", 1.0);
541   bool squared = arg->getBoolValue("squared", false);
542
543   if (squared)
544     setting = (setting < 0 ? -1 : 1) * setting * setting;
545
546   return prop->setDoubleValue((setting + offset) * factor);
547 }
548
549
550 /**
551  * Built-in command: cycle a property through a set of values.
552  *
553  * If the current value isn't in the list, the cycle will
554  * (re)start from the beginning.
555  *
556  * property: the name of the property to cycle.
557  * value[*]: the list of values to cycle through.
558  */
559 static bool
560 do_property_cycle (const SGPropertyNode * arg)
561 {
562     SGPropertyNode * prop = get_prop(arg);
563     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
564     int selection = -1;
565     int nSelections = values.size();
566
567     if (nSelections < 1) {
568         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
569         return false;
570     }
571
572                                 // Try to find the current selection
573     for (int i = 0; i < nSelections; i++) {
574         if (compare_values(prop, values[i])) {
575             selection = i + 1;
576             break;
577         }
578     }
579
580                                 // Default or wrap to the first selection
581     if (selection < 0 || selection >= nSelections)
582         selection = 0;
583
584     prop->setUnspecifiedValue(values[selection]->getStringValue());
585     return true;
586 }
587
588
589 /**
590  * Built-in command: Show an XML-configured dialog.
591  *
592  * dialog-name: the name of the GUI dialog to display.
593  */
594 static bool
595 do_dialog_show (const SGPropertyNode * arg)
596 {
597     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
598     gui->showDialog(arg->getStringValue("dialog-name"));
599     return true;
600 }
601
602
603 /**
604  * Built-in Command: Hide the active XML-configured dialog.
605  */
606 static bool
607 do_dialog_close (const SGPropertyNode * arg)
608 {
609     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
610     gui->closeActiveDialog();
611 }
612
613
614 /**
615  * Update a value in the active XML-configured dialog.
616  *
617  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
618  */
619 static bool
620 do_dialog_update (const SGPropertyNode * arg)
621 {
622     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
623     FGDialog * dialog = gui->getActiveDialog();
624     if (dialog != 0) {
625         if (arg->hasValue("object-name")) {
626             dialog->updateValue(arg->getStringValue("object-name"));
627         } else {
628             dialog->updateValues();
629         }
630         return true;
631     } else {
632         return false;
633     }
634 }
635
636
637 /**
638  * Apply a value in the active XML-configured dialog.
639  *
640  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
641  */
642 static bool
643 do_dialog_apply (const SGPropertyNode * arg)
644 {
645     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
646     FGDialog * dialog = gui->getActiveDialog();
647     if (dialog != 0) {
648         if (arg->hasValue("object-name")) {
649             const char * name = arg->getStringValue("object-name");
650             dialog->applyValue(name);
651             dialog->updateValue(name);
652         } else {
653             dialog->applyValues();
654             dialog->updateValues();
655         }
656         return true;
657     } else {
658         return false;
659     }
660 }
661
662
663 /**
664  * Built-in command: commit presets (read from in /sim/presets/)
665  */
666 static bool
667 do_presets_commit (const SGPropertyNode * arg)
668 {
669     // unbind the current fdm state so property changes
670     // don't get lost when we subsequently delete this fdm
671     // and create a new one.
672     cur_fdm_state->unbind();
673         
674     // set position from presets
675     fgInitPosition();
676
677     // BusyCursor(0);
678     fgReInitSubsystems();
679
680     globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
681
682     if ( ! fgGetBool("/sim/presets/onground") ) {
683         fgSetBool( "/sim/freeze/master", true );
684         fgSetBool( "/sim/freeze/clock", true );
685     }
686
687     return true;
688 }
689
690
691 \f
692 ////////////////////////////////////////////////////////////////////////
693 // Command setup.
694 ////////////////////////////////////////////////////////////////////////
695
696
697 /**
698  * Table of built-in commands.
699  *
700  * New commands do not have to be added here; any module in the application
701  * can add a new command using globals->get_commands()->addCommand(...).
702  */
703 static struct {
704   const char * name;
705   SGCommandMgr::command_t command;
706 } built_ins [] = {
707     { "null", do_null },
708 #if defined(HAVE_PLIB_PSL)
709     { "script", do_script },
710 #endif // HAVE_PLIB_PSL
711     { "exit", do_exit },
712     { "load", do_load },
713     { "save", do_save },
714     { "panel-load", do_panel_load },
715     { "panel-mouse-click", do_panel_mouse_click },
716     { "preferences-load", do_preferences_load },
717     { "view-cycle", do_view_cycle },
718     { "screen-capture", do_screen_capture },
719     { "tile-cache-reload", do_tile_cache_reload },
720     { "lighting-update", do_lighting_update },
721     { "property-toggle", do_property_toggle },
722     { "property-assign", do_property_assign },
723     { "property-adjust", do_property_adjust },
724     { "property-multiply", do_property_multiply },
725     { "property-swap", do_property_swap },
726     { "property-scale", do_property_scale },
727     { "property-cycle", do_property_cycle },
728     { "dialog-show", do_dialog_show },
729     { "dialog-close", do_dialog_close },
730     { "dialog-show", do_dialog_show },
731     { "dialog-update", do_dialog_update },
732     { "dialog-apply", do_dialog_apply },
733     { "presets-commit", do_presets_commit },
734     { 0, 0 }                    // zero-terminated
735 };
736
737
738 /**
739  * Initialize the default built-in commands.
740  *
741  * Other commands may be added by other parts of the application.
742  */
743 void
744 fgInitCommands ()
745 {
746   SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
747   for (int i = 0; built_ins[i].name != 0; i++) {
748     SG_LOG(SG_GENERAL, SG_INFO, "  " << built_ins[i].name);
749     globals->get_commands()->addCommand(built_ins[i].name,
750                                         built_ins[i].command);
751   }
752
753   typedef bool (*dummy)();
754   fgTie( "/command/view/next", dummy(0), do_view_next );
755   fgTie( "/command/view/prev", dummy(0), do_view_prev );
756 }
757
758 // end of fg_commands.cxx