1 // fg_commands.cxx - internal FGFS commands.
7 #include <string.h> // strcmp()
9 #include <simgear/compiler.h>
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/scene/material/mat.hxx>
18 #include <simgear/scene/material/matlib.hxx>
19 #include <simgear/structure/exception.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/props/props.hxx>
22 #include <simgear/props/props_io.hxx>
23 #include <simgear/structure/event_mgr.hxx>
24 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <simgear/timing/sg_time.hxx>
26 #include <simgear/misc/interpolator.hxx>
27 #include <simgear/io/HTTPRequest.hxx>
29 #include <FDM/flight.hxx>
31 #include <GUI/new_gui.hxx>
32 #include <GUI/dialog.hxx>
33 #include <Aircraft/replay.hxx>
34 #include <Scenery/scenery.hxx>
35 #include <Scripting/NasalSys.hxx>
36 #include <Sound/sample_queue.hxx>
37 #include <Airports/xmlloader.hxx>
38 #include <Network/HTTPClient.hxx>
39 #include <Viewer/viewmgr.hxx>
40 #include <Viewer/viewer.hxx>
41 #include <Environment/presets.hxx>
43 #include "fg_init.hxx"
46 #include "fg_commands.hxx"
47 #include "fg_props.hxx"
48 #include "globals.hxx"
52 #include "positioninit.hxx"
54 #include <boost/scoped_array.hpp>
56 #ifdef FG_HAVE_GPERFTOOLS
57 # include <google/profiler.h>
65 ////////////////////////////////////////////////////////////////////////
66 // Static helper functions.
67 ////////////////////////////////////////////////////////////////////////
70 static inline SGPropertyNode *
71 get_prop (const SGPropertyNode * arg)
73 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
76 static inline SGPropertyNode *
77 get_prop2 (const SGPropertyNode * arg)
79 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
84 * Get a double value and split it as required.
87 split_value (double full_value, const char * mask,
88 double * unmodifiable, double * modifiable)
90 if (!strcmp("integer", mask)) {
91 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
92 *unmodifiable = full_value - *modifiable;
93 } else if (!strcmp("decimal", mask)) {
94 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
95 *modifiable = full_value - *unmodifiable;
97 if (strcmp("all", mask))
98 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
99 << " assuming 'all'");
101 *modifiable = full_value;
107 * Clamp or wrap a value as specified.
110 limit_value (double * value, const SGPropertyNode * arg)
112 const SGPropertyNode * min_node = arg->getChild("min");
113 const SGPropertyNode * max_node = arg->getChild("max");
115 bool wrap = arg->getBoolValue("wrap");
117 if (min_node == 0 || max_node == 0)
120 if (wrap) { // wrap such that min <= x < max
121 double min_val = min_node->getDoubleValue();
122 double max_val = max_node->getDoubleValue();
123 double resolution = arg->getDoubleValue("resolution");
124 if (resolution > 0.0) {
125 // snap to (min + N*resolution), taking special care to handle imprecision
126 int n = (int)floor((*value - min_val) / resolution + 0.5);
127 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
128 SG_NORMALIZE_RANGE(n, 0, steps);
129 *value = min_val + resolution * n;
131 // plain circular wrapping
132 SG_NORMALIZE_RANGE(*value, min_val, max_val);
134 } else { // clamp such that min <= x <= max
135 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
136 *value = min_node->getDoubleValue();
137 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
138 *value = max_node->getDoubleValue();
143 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
145 switch (value1->getType()) {
146 case simgear::props::BOOL:
147 return (value1->getBoolValue() == value2->getBoolValue());
148 case simgear::props::INT:
149 return (value1->getIntValue() == value2->getIntValue());
150 case simgear::props::LONG:
151 return (value1->getLongValue() == value2->getLongValue());
152 case simgear::props::FLOAT:
153 return (value1->getFloatValue() == value2->getFloatValue());
154 case simgear::props::DOUBLE:
155 return (value1->getDoubleValue() == value2->getDoubleValue());
157 return !strcmp(value1->getStringValue(), value2->getStringValue());
163 ////////////////////////////////////////////////////////////////////////
164 // Command implementations.
165 ////////////////////////////////////////////////////////////////////////
169 * Built-in command: do nothing.
172 do_null (const SGPropertyNode * arg)
178 * Built-in command: run a Nasal script.
181 do_nasal (const SGPropertyNode * arg)
183 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
187 * Built-in command: exit FlightGear.
189 * status: the exit status to return to the operating system (defaults to 0)
192 do_exit (const SGPropertyNode * arg)
194 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
195 fgSetBool("/sim/signals/exit", true);
196 globals->saveUserSettings();
197 fgOSExit(arg->getIntValue("status", 0));
203 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
206 do_reset (const SGPropertyNode * arg)
208 fgReInitSubsystems();
213 * Built-in command: replay the FDR buffer
216 do_replay (const SGPropertyNode * arg)
218 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
223 * Built-in command: pause/unpause the sim
226 do_pause (const SGPropertyNode * arg)
228 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
229 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
235 fgSetBool("/sim/freeze/master",!paused);
236 fgSetBool("/sim/freeze/clock",!paused);
242 * Built-in command: load flight.
244 * file (optional): the name of the file to load (relative to current
245 * directory). Defaults to "fgfs.sav"
248 do_load (const SGPropertyNode * arg)
250 string file = arg->getStringValue("file", "fgfs.sav");
251 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
254 if (!fgValidatePath(file.c_str(), false)) {
255 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
256 "(unauthorized access)");
260 ifstream input(file.c_str());
261 if (input.good() && fgLoadFlight(input)) {
263 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
266 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
273 * Built-in command: save flight.
275 * file (optional): the name of the file to save (relative to the
276 * current directory). Defaults to "fgfs.sav".
279 do_save (const SGPropertyNode * arg)
281 string file = arg->getStringValue("file", "fgfs.sav");
282 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
285 if (!fgValidatePath(file.c_str(), false)) {
286 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
287 "(unauthorized access)");
291 bool write_all = arg->getBoolValue("write-all", false);
292 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
293 ofstream output(file.c_str());
294 if (output.good() && fgSaveFlight(output, write_all)) {
296 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
299 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
305 * Built-in command: save flight recorder tape.
309 do_save_tape (const SGPropertyNode * arg)
311 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
312 replay->saveTape(arg);
317 * Built-in command: load flight recorder tape.
321 do_load_tape (const SGPropertyNode * arg)
323 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
324 replay->loadTape(arg);
330 * Built-in command: (re)load the panel.
332 * path (optional): the file name to load the panel from
333 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
334 * and if that's unspecified, to "Panels/Default/default.xml".
337 do_panel_load (const SGPropertyNode * arg)
339 string panel_path = arg->getStringValue("path");
340 if (!panel_path.empty()) {
341 // write to the standard property, which will force a load
342 fgSetString("/sim/panel/path", panel_path.c_str());
349 * Built-in command: (re)load preferences.
351 * path (optional): the file name to load the panel from (relative
352 * to FG_ROOT). Defaults to "preferences.xml".
355 do_preferences_load (const SGPropertyNode * arg)
358 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
359 globals->get_props());
360 } catch (const sg_exception &e) {
361 guiErrorMessage("Error reading global preferences: ", e);
364 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
371 globals->get_current_view()->setHeadingOffset_deg(0.0);
372 globals->get_viewmgr()->next_view();
378 globals->get_current_view()->setHeadingOffset_deg(0.0);
379 globals->get_viewmgr()->prev_view();
383 * Built-in command: cycle view.
386 do_view_cycle (const SGPropertyNode * arg)
388 globals->get_current_view()->setHeadingOffset_deg(0.0);
389 globals->get_viewmgr()->next_view();
394 * Built-in command: capture screen.
397 do_screen_capture (const SGPropertyNode * arg)
399 return fgDumpSnapShot();
403 do_reload_shaders (const SGPropertyNode*)
405 simgear::reload_shaders();
410 do_dump_scene_graph (const SGPropertyNode*)
417 do_dump_terrain_branch (const SGPropertyNode*)
419 fgDumpTerrainBranch();
421 double lon_deg = fgGetDouble("/position/longitude-deg");
422 double lat_deg = fgGetDouble("/position/latitude-deg");
423 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
424 SGVec3d zero = SGVec3d::fromGeod(geodPos);
426 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
427 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
428 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
434 do_print_visible_scene_info(const SGPropertyNode*)
436 fgPrintVisibleSceneInfoCommand();
441 * Built-in command: hires capture screen.
444 do_hires_screen_capture (const SGPropertyNode * arg)
452 * Reload the tile cache.
455 do_tile_cache_reload (const SGPropertyNode * arg)
457 static const SGPropertyNode *master_freeze
458 = fgGetNode("/sim/freeze/master");
459 bool freeze = master_freeze->getBoolValue();
460 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
462 fgSetBool("/sim/freeze/master", true);
465 globals->get_subsystem("tile-manager")->reinit();
468 fgSetBool("/sim/freeze/master", false);
474 * Reload the materials definition
477 do_materials_reload (const SGPropertyNode * arg)
479 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
480 SGMaterialLib* new_matlib = new SGMaterialLib;
481 SGPath mpath( globals->get_fg_root() );
482 mpath.append( fgGetString("/sim/rendering/materials-file") );
483 bool loaded = new_matlib->load(globals->get_fg_root(),
485 globals->get_props());
488 SG_LOG( SG_GENERAL, SG_ALERT,
489 "Error loading materials file " << mpath.str() );
493 globals->set_matlib(new_matlib);
499 These do_set_(some-environment-parameters) are deprecated and no longer
500 useful/functional - Torsten Dreyer, January 2011
502 * Set the sea level outside air temperature and assigning that to all
503 * boundary and aloft environment layers.
506 do_set_sea_level_degc ( double temp_sea_level_degc)
508 SGPropertyNode *node, *child;
511 node = fgGetNode( "/environment/config/boundary" );
512 if ( node != NULL ) {
514 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
515 child->setDoubleValue( "temperature-sea-level-degc",
516 temp_sea_level_degc );
522 node = fgGetNode( "/environment/config/aloft" );
523 if ( node != NULL ) {
525 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
526 child->setDoubleValue( "temperature-sea-level-degc",
527 temp_sea_level_degc );
536 do_set_sea_level_degc (const SGPropertyNode * arg)
538 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
543 * Set the outside air temperature at the "current" altitude by first
544 * calculating the corresponding sea level temp, and assigning that to
545 * all boundary and aloft environment layers.
548 do_set_oat_degc (const SGPropertyNode * arg)
550 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
551 // check for an altitude specified in the arguments, otherwise use
552 // current aircraft altitude.
553 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
554 if ( altitude_ft == NULL ) {
555 altitude_ft = fgGetNode("/position/altitude-ft");
558 FGEnvironment dummy; // instantiate a dummy so we can leech a method
559 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
560 dummy.set_temperature_degc( oat_degc );
561 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
565 * Set the sea level outside air dewpoint and assigning that to all
566 * boundary and aloft environment layers.
569 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
572 SGPropertyNode *node, *child;
575 node = fgGetNode( "/environment/config/boundary" );
576 if ( node != NULL ) {
578 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
579 child->setDoubleValue( "dewpoint-sea-level-degc",
580 dewpoint_sea_level_degc );
586 node = fgGetNode( "/environment/config/aloft" );
587 if ( node != NULL ) {
589 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
590 child->setDoubleValue( "dewpoint-sea-level-degc",
591 dewpoint_sea_level_degc );
600 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
602 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
606 * Set the outside air dewpoint at the "current" altitude by first
607 * calculating the corresponding sea level dewpoint, and assigning
608 * that to all boundary and aloft environment layers.
611 do_set_dewpoint_degc (const SGPropertyNode * arg)
613 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
615 // check for an altitude specified in the arguments, otherwise use
616 // current aircraft altitude.
617 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
618 if ( altitude_ft == NULL ) {
619 altitude_ft = fgGetNode("/position/altitude-ft");
622 FGEnvironment dummy; // instantiate a dummy so we can leech a method
623 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
624 dummy.set_dewpoint_degc( dewpoint_degc );
625 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
630 * Built-in command: toggle a bool property value.
632 * property: The name of the property to toggle.
635 do_property_toggle (const SGPropertyNode * arg)
637 SGPropertyNode * prop = get_prop(arg);
638 return prop->setBoolValue(!prop->getBoolValue());
643 * Built-in command: assign a value to a property.
645 * property: the name of the property to assign.
646 * value: the value to assign; or
647 * property[1]: the property to copy from.
650 do_property_assign (const SGPropertyNode * arg)
652 SGPropertyNode * prop = get_prop(arg);
653 const SGPropertyNode * value = arg->getNode("value");
656 return prop->setUnspecifiedValue(value->getStringValue());
659 const SGPropertyNode * prop2 = get_prop2(arg);
661 return prop->setUnspecifiedValue(prop2->getStringValue());
669 * Built-in command: increment or decrement a property value.
671 * If the 'step' argument is present, it will be used; otherwise,
672 * the command uses 'offset' and 'factor', usually from the mouse.
674 * property: the name of the property to increment or decrement.
675 * step: the amount of the increment or decrement (default: 0).
676 * offset: offset from the current setting (used for the mouse; multiplied
678 * factor: scaling amount for the offset (defaults to 1).
679 * min: the minimum allowed value (default: no minimum).
680 * max: the maximum allowed value (default: no maximum).
681 * mask: 'integer' to apply only to the left of the decimal point,
682 * 'decimal' to apply only to the right of the decimal point,
683 * or 'all' to apply to the whole number (the default).
684 * wrap: true if the value should be wrapped when it passes min or max;
685 * both min and max must be present for this to work (default:
689 do_property_adjust (const SGPropertyNode * arg)
691 SGPropertyNode * prop = get_prop(arg);
694 if (arg->hasValue("step"))
695 amount = arg->getDoubleValue("step");
697 amount = (arg->getDoubleValue("factor", 1)
698 * arg->getDoubleValue("offset"));
700 double unmodifiable, modifiable;
701 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
702 &unmodifiable, &modifiable);
703 modifiable += amount;
704 limit_value(&modifiable, arg);
706 prop->setDoubleValue(unmodifiable + modifiable);
713 * Built-in command: multiply a property value.
715 * property: the name of the property to multiply.
716 * factor: the amount by which to multiply.
717 * min: the minimum allowed value (default: no minimum).
718 * max: the maximum allowed value (default: no maximum).
719 * mask: 'integer' to apply only to the left of the decimal point,
720 * 'decimal' to apply only to the right of the decimal point,
721 * or 'all' to apply to the whole number (the default).
722 * wrap: true if the value should be wrapped when it passes min or max;
723 * both min and max must be present for this to work (default:
727 do_property_multiply (const SGPropertyNode * arg)
729 SGPropertyNode * prop = get_prop(arg);
730 double factor = arg->getDoubleValue("factor", 1);
732 double unmodifiable, modifiable;
733 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
734 &unmodifiable, &modifiable);
735 modifiable *= factor;
736 limit_value(&modifiable, arg);
738 prop->setDoubleValue(unmodifiable + modifiable);
745 * Built-in command: swap two property values.
747 * property[0]: the name of the first property.
748 * property[1]: the name of the second property.
751 do_property_swap (const SGPropertyNode * arg)
753 SGPropertyNode * prop1 = get_prop(arg);
754 SGPropertyNode * prop2 = get_prop2(arg);
756 // FIXME: inefficient
757 const string & tmp = prop1->getStringValue();
758 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
759 prop2->setUnspecifiedValue(tmp.c_str()));
764 * Built-in command: Set a property to an axis or other moving input.
766 * property: the name of the property to set.
767 * setting: the current input setting, usually between -1.0 and 1.0.
768 * offset: the offset to shift by, before applying the factor.
769 * factor: the factor to multiply by (use negative to reverse).
772 do_property_scale (const SGPropertyNode * arg)
774 SGPropertyNode * prop = get_prop(arg);
775 double setting = arg->getDoubleValue("setting");
776 double offset = arg->getDoubleValue("offset", 0.0);
777 double factor = arg->getDoubleValue("factor", 1.0);
778 bool squared = arg->getBoolValue("squared", false);
779 int power = arg->getIntValue("power", (squared ? 2 : 1));
781 int sign = (setting < 0 ? -1 : 1);
787 setting = setting * setting * sign;
790 setting = setting * setting * setting;
793 setting = setting * setting * setting * setting * sign;
796 setting = pow(setting, power);
797 if ((power % 2) == 0)
802 return prop->setDoubleValue((setting + offset) * factor);
807 * Built-in command: cycle a property through a set of values.
809 * If the current value isn't in the list, the cycle will
810 * (re)start from the beginning.
812 * property: the name of the property to cycle.
813 * value[*]: the list of values to cycle through.
816 do_property_cycle (const SGPropertyNode * arg)
818 SGPropertyNode * prop = get_prop(arg);
819 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
821 int nSelections = values.size();
823 if (nSelections < 1) {
824 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
828 // Try to find the current selection
829 for (int i = 0; i < nSelections; i++) {
830 if (compare_values(prop, values[i])) {
836 // Default or wrap to the first selection
837 if (selection < 0 || selection >= nSelections)
840 prop->setUnspecifiedValue(values[selection]->getStringValue());
846 * Built-in command: randomize a numeric property value.
848 * property: the name of the property value to randomize.
849 * min: the minimum allowed value.
850 * max: the maximum allowed value.
853 do_property_randomize (const SGPropertyNode * arg)
855 SGPropertyNode * prop = get_prop(arg);
856 double min = arg->getDoubleValue("min", DBL_MIN);
857 double max = arg->getDoubleValue("max", DBL_MAX);
858 prop->setDoubleValue(sg_random() * (max - min) + min);
863 * Built-in command: interpolate a property value over time
865 * property: the name of the property value to interpolate.
866 * value[0..n] any number of constant values to interpolate
867 * time/rate[0..n] time between each value, number of time elements must
868 * match those of value elements. Instead of time also rate can
869 * be used which automatically calculates the time to change
870 * the property value at the given speed.
872 * property[1..n] any number of target values taken from named properties
873 * time/rate[0..n] time between each value, number of time elements must
874 * match those of value elements. Instead of time also rate can
875 * be used which automatically calculates the time to change
876 * the property value at the given speed.
879 do_property_interpolate (const SGPropertyNode * arg)
881 SGPropertyNode * prop = get_prop(arg);
883 simgear::PropertyList valueNodes = arg->getChildren( "value" );
884 simgear::PropertyList timeNodes = arg->getChildren( "time" );
885 simgear::PropertyList rateNodes = arg->getChildren( "rate" );
887 if( !timeNodes.empty() && !rateNodes.empty() )
888 // mustn't specify time and rate
891 simgear::PropertyList::size_type num_times = timeNodes.empty()
895 boost::scoped_array<double> value;
896 boost::scoped_array<double> time;
898 if( valueNodes.size() > 0 ) {
900 if( num_times != valueNodes.size() )
903 value.reset( new double[valueNodes.size()] );
904 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
905 value[n] = valueNodes[n]->getDoubleValue();
908 valueNodes = arg->getChildren("property");
909 // must have one more property node
910 if( valueNodes.size() - 1 != num_times )
913 value.reset( new double[valueNodes.size()-1] );
914 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
915 value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
920 time.reset( new double[num_times] );
921 if( !timeNodes.empty() ) {
922 for( simgear::PropertyList::size_type n = 0; n < num_times; n++ ) {
923 time[n] = timeNodes[n]->getDoubleValue();
926 for( simgear::PropertyList::size_type n = 0; n < num_times; n++ ) {
927 double delta = value[n]
928 - (n > 0 ? value[n - 1] : prop->getDoubleValue());
929 time[n] = fabs(delta / rateNodes[n]->getDoubleValue());
933 ((SGInterpolator*)globals->get_subsystem_mgr()
934 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
935 ->interpolate(prop, num_times, value.get(), time.get() );
941 * Built-in command: reinit the data logging system based on the
942 * current contents of the /logger tree.
945 do_data_logging_commit (const SGPropertyNode * arg)
947 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
953 * Built-in command: Add a dialog to the GUI system. Does *not*
954 * display the dialog. The property node should have the same format
955 * as a dialog XML configuration. It must include:
957 * name: the name of the GUI dialog for future reference.
960 do_dialog_new (const SGPropertyNode * arg)
962 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
967 // Note the casting away of const: this is *real*. Doing a
968 // "dialog-apply" command later on will mutate this property node.
969 // I'm not convinced that this isn't the Right Thing though; it
970 // allows client to create a node, pass it to dialog-new, and get
971 // the values back from the dialog by reading the same node.
972 // Perhaps command arguments are not as "const" as they would
974 gui->newDialog((SGPropertyNode*)arg);
979 * Built-in command: Show an XML-configured dialog.
981 * dialog-name: the name of the GUI dialog to display.
984 do_dialog_show (const SGPropertyNode * arg)
986 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
987 gui->showDialog(arg->getStringValue("dialog-name"));
993 * Built-in Command: Hide the active XML-configured dialog.
996 do_dialog_close (const SGPropertyNode * arg)
998 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
999 if(arg->hasValue("dialog-name"))
1000 return gui->closeDialog(arg->getStringValue("dialog-name"));
1001 return gui->closeActiveDialog();
1006 * Update a value in the active XML-configured dialog.
1008 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1011 do_dialog_update (const SGPropertyNode * arg)
1013 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1015 if (arg->hasValue("dialog-name"))
1016 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1018 dialog = gui->getActiveDialog();
1021 dialog->updateValues(arg->getStringValue("object-name"));
1029 do_open_browser (const SGPropertyNode * arg)
1032 if (arg->hasValue("path"))
1033 path = arg->getStringValue("path");
1035 if (arg->hasValue("url"))
1036 path = arg->getStringValue("url");
1040 return openBrowser(path);
1044 * Apply a value in the active XML-configured dialog.
1046 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1049 do_dialog_apply (const SGPropertyNode * arg)
1051 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1053 if (arg->hasValue("dialog-name"))
1054 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1056 dialog = gui->getActiveDialog();
1059 dialog->applyValues(arg->getStringValue("object-name"));
1068 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1072 do_gui_redraw (const SGPropertyNode * arg)
1074 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1081 * Adds model to the scenery. The path to the added branch (/models/model[*])
1082 * is returned in property "property".
1085 do_add_model (const SGPropertyNode * arg)
1087 SGPropertyNode * model = fgGetNode("models", true);
1089 for (i = 0; model->hasChild("model",i); i++);
1090 model = model->getChild("model", i, true);
1091 copyProperties(arg, model);
1092 if (model->hasValue("elevation-m"))
1093 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1094 * SG_METER_TO_FEET);
1095 model->getNode("load", true);
1096 model->removeChildren("load");
1097 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1103 * Set mouse cursor coordinates and cursor shape.
1106 do_set_cursor (const SGPropertyNode * arg)
1108 if (arg->hasValue("x") || arg->hasValue("y")) {
1109 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1110 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1111 int x = arg->getIntValue("x", mx->getIntValue());
1112 int y = arg->getIntValue("y", my->getIntValue());
1118 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1119 if (cursor->getType() != simgear::props::NONE)
1120 fgSetMouseCursor(cursor->getIntValue());
1122 cursor->setIntValue(fgGetMouseCursor());
1128 * Built-in command: play an audio message (i.e. a wav file) This is
1129 * fire and forget. Call this once per message and it will get dumped
1130 * into a queue. Messages are played sequentially so they do not
1134 do_play_audio_sample (const SGPropertyNode * arg)
1136 SGSoundMgr *smgr = globals->get_soundmgr();
1138 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1142 string path = arg->getStringValue("path");
1143 string file = arg->getStringValue("file");
1144 float volume = arg->getFloatValue("volume");
1145 // cout << "playing " << path << " / " << file << endl;
1147 static FGSampleQueue *queue = 0;
1149 queue = new FGSampleQueue(smgr, "chatter");
1150 queue->tie_to_listener();
1153 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1154 msg->set_volume( volume );
1159 } catch (const sg_io_exception&) {
1160 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1161 "failed to load" << path << '/' << file);
1167 * Built-in command: commit presets (read from in /sim/presets/)
1170 do_presets_commit (const SGPropertyNode * arg)
1172 if (fgGetBool("/sim/initialized", false)) {
1173 fgReInitSubsystems();
1175 // Nasal can trigger this during initial init, which confuses
1176 // the logic in ReInitSubsystems, since initial state has not been
1177 // saved at that time. Short-circuit everything here.
1178 flightgear::initPosition();
1185 * Built-in command: set log level (0 ... 7)
1188 do_log_level (const SGPropertyNode * arg)
1190 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1197 do_decrease_visibility (const SGPropertyNode * arg)
1199 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1204 do_increase_visibility (const SGPropertyNode * arg)
1206 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1211 * An fgcommand to allow loading of xml files via nasal,
1212 * the xml file's structure will be made available within
1213 * a property tree node defined under argument "targetnode",
1214 * or in the given argument tree under "data" otherwise.
1216 * @param filename a string to hold the complete path & filename of an XML file
1217 * @param targetnode a string pointing to a location within the property tree
1218 * where to store the parsed XML file. If <targetnode> is undefined, then the
1219 * file contents are stored under a node <data> in the argument tree.
1223 do_load_xml_to_proptree(const SGPropertyNode * arg)
1225 SGPath file(arg->getStringValue("filename"));
1226 if (file.str().empty())
1229 if (file.extension() != "xml")
1230 file.concat(".xml");
1232 std::string icao = arg->getStringValue("icao");
1234 if (file.isRelative()) {
1235 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1236 if (!absPath.isNull())
1240 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1241 << file.str() << "'.");
1246 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1247 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1248 << file.str() << " at ICAO:" << icao);
1253 if (!fgValidatePath(file.c_str(), false)) {
1254 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1255 "(unauthorized access)");
1259 SGPropertyNode *targetnode;
1260 if (arg->hasValue("targetnode"))
1261 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1263 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1266 readProperties(file.c_str(), targetnode, true);
1267 } catch (const sg_exception &e) {
1268 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1275 class RemoteXMLRequest : public simgear::HTTP::Request
1278 SGPropertyNode_ptr _complete;
1279 SGPropertyNode_ptr _status;
1280 SGPropertyNode_ptr _failed;
1281 SGPropertyNode_ptr _target;
1284 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1285 simgear::HTTP::Request(url),
1290 void setCompletionProp(SGPropertyNode_ptr p)
1295 void setStatusProp(SGPropertyNode_ptr p)
1300 void setFailedProp(SGPropertyNode_ptr p)
1305 virtual void gotBodyData(const char* s, int n)
1307 propsData += string(s, n);
1310 virtual void responseComplete()
1312 int response = responseCode();
1313 bool failed = false;
1314 if (response == 200) {
1316 const char* buffer = propsData.c_str();
1317 readProperties(buffer, propsData.size(), _target, true);
1318 } catch (const sg_exception &e) {
1319 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1321 response = 406; // 'not acceptable', anything better?
1326 // now the response data is output, signal Nasal / listeners
1327 if (_complete) _complete->setBoolValue(true);
1328 if (_status) _status->setIntValue(response);
1329 if (_failed) _failed->setBoolValue(failed);
1335 do_load_xml_from_url(const SGPropertyNode * arg)
1337 std::string url(arg->getStringValue("url"));
1341 SGPropertyNode *targetnode;
1342 if (arg->hasValue("targetnode"))
1343 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1345 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1347 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1349 // connect up optional reporting properties
1350 if (arg->hasValue("complete"))
1351 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1352 if (arg->hasValue("failure"))
1353 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1354 if (arg->hasValue("status"))
1355 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1357 FGHTTPClient::instance()->makeRequest(req);
1364 * An fgcommand to allow saving of xml files via nasal,
1365 * the file's structure will be determined based on what's
1366 * encountered in the passed (source) property tree node
1368 * @param filename a string to hold the complete path & filename of the (new)
1370 * @param sourcenode a string pointing to a location within the property tree
1371 * where to find the nodes that should be written recursively into an XML file
1372 * @param data if no sourcenode is given, then the file contents are taken from
1373 * the argument tree's "data" node.
1377 do_save_xml_from_proptree(const SGPropertyNode * arg)
1379 SGPath file(arg->getStringValue("filename"));
1380 if (file.str().empty())
1383 if (file.extension() != "xml")
1384 file.concat(".xml");
1386 if (!fgValidatePath(file.c_str(), true)) {
1387 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1388 "(unauthorized access)");
1392 SGPropertyNode *sourcenode;
1393 if (arg->hasValue("sourcenode"))
1394 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1395 else if (arg->getNode("data", false))
1396 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1401 writeProperties (file.c_str(), sourcenode, true);
1402 } catch (const sg_exception &e) {
1403 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1411 do_press_cockpit_button (const SGPropertyNode *arg)
1413 const char *prefix = arg->getStringValue("prefix");
1415 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1418 string prop = string(prefix) + "-button";
1421 if (arg->getBoolValue("latching"))
1422 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1426 fgSetDouble(prop.c_str(), value);
1427 fgSetBool(arg->getStringValue("discrete"), value > 0);
1433 do_release_cockpit_button (const SGPropertyNode *arg)
1435 const char *prefix = arg->getStringValue("prefix");
1437 if (arg->getBoolValue("guarded")) {
1438 string prop = string(prefix) + "-guard";
1439 if (fgGetDouble(prop.c_str()) < 1) {
1440 fgSetDouble(prop.c_str(), 1);
1445 if (! arg->getBoolValue("latching")) {
1446 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1447 fgSetBool(arg->getStringValue("discrete"), false);
1453 // Optional profiling commands using gperftools:
1454 // http://code.google.com/p/gperftools/
1456 #ifndef FG_HAVE_GPERFTOOLS
1458 no_profiling_support()
1464 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1470 do_profiler_start(const SGPropertyNode *arg)
1472 #ifdef FG_HAVE_GPERFTOOLS
1473 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1474 ProfilerStart(filename);
1477 no_profiling_support();
1483 do_profiler_stop(const SGPropertyNode *arg)
1485 #ifdef FG_HAVE_GPERFTOOLS
1489 no_profiling_support();
1494 ////////////////////////////////////////////////////////////////////////
1496 ////////////////////////////////////////////////////////////////////////
1500 * Table of built-in commands.
1502 * New commands do not have to be added here; any module in the application
1503 * can add a new command using globals->get_commands()->addCommand(...).
1507 SGCommandMgr::command_t command;
1509 { "null", do_null },
1510 { "nasal", do_nasal },
1511 { "exit", do_exit },
1512 { "reset", do_reset },
1513 { "pause", do_pause },
1514 { "load", do_load },
1515 { "save", do_save },
1516 { "save-tape", do_save_tape },
1517 { "load-tape", do_load_tape },
1518 { "panel-load", do_panel_load },
1519 { "preferences-load", do_preferences_load },
1520 { "view-cycle", do_view_cycle },
1521 { "screen-capture", do_screen_capture },
1522 { "hires-screen-capture", do_hires_screen_capture },
1523 { "tile-cache-reload", do_tile_cache_reload },
1525 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1526 { "set-outside-air-temp-degc", do_set_oat_degc },
1527 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1528 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1530 { "property-toggle", do_property_toggle },
1531 { "property-assign", do_property_assign },
1532 { "property-adjust", do_property_adjust },
1533 { "property-multiply", do_property_multiply },
1534 { "property-swap", do_property_swap },
1535 { "property-scale", do_property_scale },
1536 { "property-cycle", do_property_cycle },
1537 { "property-randomize", do_property_randomize },
1538 { "property-interpolate", do_property_interpolate },
1539 { "data-logging-commit", do_data_logging_commit },
1540 { "dialog-new", do_dialog_new },
1541 { "dialog-show", do_dialog_show },
1542 { "dialog-close", do_dialog_close },
1543 { "dialog-update", do_dialog_update },
1544 { "dialog-apply", do_dialog_apply },
1545 { "open-browser", do_open_browser },
1546 { "gui-redraw", do_gui_redraw },
1547 { "add-model", do_add_model },
1548 { "set-cursor", do_set_cursor },
1549 { "play-audio-sample", do_play_audio_sample },
1550 { "presets-commit", do_presets_commit },
1551 { "log-level", do_log_level },
1552 { "replay", do_replay },
1554 { "decrease-visibility", do_decrease_visibility },
1555 { "increase-visibility", do_increase_visibility },
1557 { "loadxml", do_load_xml_to_proptree},
1558 { "savexml", do_save_xml_from_proptree },
1559 { "xmlhttprequest", do_load_xml_from_url },
1560 { "press-cockpit-button", do_press_cockpit_button },
1561 { "release-cockpit-button", do_release_cockpit_button },
1562 { "dump-scenegraph", do_dump_scene_graph },
1563 { "dump-terrainbranch", do_dump_terrain_branch },
1564 { "print-visible-scene", do_print_visible_scene_info },
1565 { "reload-shaders", do_reload_shaders },
1566 { "reload-materials", do_materials_reload },
1568 { "profiler-start", do_profiler_start },
1569 { "profiler-stop", do_profiler_stop },
1571 { 0, 0 } // zero-terminated
1576 * Initialize the default built-in commands.
1578 * Other commands may be added by other parts of the application.
1583 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1584 for (int i = 0; built_ins[i].name != 0; i++) {
1585 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1586 globals->get_commands()->addCommand(built_ins[i].name,
1587 built_ins[i].command);
1590 typedef bool (*dummy)();
1591 fgTie( "/command/view/next", dummy(0), do_view_next );
1592 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1595 // end of fg_commands.cxx