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/io/HTTPMemoryRequest.hxx>
28 #include <FDM/flight.hxx>
30 #include <GUI/new_gui.hxx>
31 #include <GUI/dialog.hxx>
32 #include <Aircraft/replay.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scripting/NasalSys.hxx>
35 #include <Sound/sample_queue.hxx>
36 #include <Airports/xmlloader.hxx>
37 #include <Network/HTTPClient.hxx>
38 #include <Viewer/viewmgr.hxx>
39 #include <Viewer/viewer.hxx>
40 #include <Environment/presets.hxx>
42 #include "fg_init.hxx"
45 #include "fg_commands.hxx"
46 #include "fg_props.hxx"
47 #include "globals.hxx"
51 #include "positioninit.hxx"
53 #include <boost/scoped_array.hpp>
55 #if FG_HAVE_GPERFTOOLS
56 # include <google/profiler.h>
64 ////////////////////////////////////////////////////////////////////////
65 // Static helper functions.
66 ////////////////////////////////////////////////////////////////////////
69 static inline SGPropertyNode *
70 get_prop (const SGPropertyNode * arg)
72 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
75 static inline SGPropertyNode *
76 get_prop2 (const SGPropertyNode * arg)
78 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
83 * Get a double value and split it as required.
86 split_value (double full_value, const char * mask,
87 double * unmodifiable, double * modifiable)
89 if (!strcmp("integer", mask)) {
90 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
91 *unmodifiable = full_value - *modifiable;
92 } else if (!strcmp("decimal", mask)) {
93 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
94 *modifiable = full_value - *unmodifiable;
96 if (strcmp("all", mask))
97 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
98 << " assuming 'all'");
100 *modifiable = full_value;
106 * Clamp or wrap a value as specified.
109 limit_value (double * value, const SGPropertyNode * arg)
111 const SGPropertyNode * min_node = arg->getChild("min");
112 const SGPropertyNode * max_node = arg->getChild("max");
114 bool wrap = arg->getBoolValue("wrap");
116 if (min_node == 0 || max_node == 0)
119 if (wrap) { // wrap such that min <= x < max
120 double min_val = min_node->getDoubleValue();
121 double max_val = max_node->getDoubleValue();
122 double resolution = arg->getDoubleValue("resolution");
123 if (resolution > 0.0) {
124 // snap to (min + N*resolution), taking special care to handle imprecision
125 int n = (int)floor((*value - min_val) / resolution + 0.5);
126 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
127 SG_NORMALIZE_RANGE(n, 0, steps);
128 *value = min_val + resolution * n;
130 // plain circular wrapping
131 SG_NORMALIZE_RANGE(*value, min_val, max_val);
133 } else { // clamp such that min <= x <= max
134 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
135 *value = min_node->getDoubleValue();
136 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
137 *value = max_node->getDoubleValue();
142 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
144 switch (value1->getType()) {
145 case simgear::props::BOOL:
146 return (value1->getBoolValue() == value2->getBoolValue());
147 case simgear::props::INT:
148 return (value1->getIntValue() == value2->getIntValue());
149 case simgear::props::LONG:
150 return (value1->getLongValue() == value2->getLongValue());
151 case simgear::props::FLOAT:
152 return (value1->getFloatValue() == value2->getFloatValue());
153 case simgear::props::DOUBLE:
154 return (value1->getDoubleValue() == value2->getDoubleValue());
156 return !strcmp(value1->getStringValue(), value2->getStringValue());
162 ////////////////////////////////////////////////////////////////////////
163 // Command implementations.
164 ////////////////////////////////////////////////////////////////////////
168 * Built-in command: do nothing.
171 do_null (const SGPropertyNode * arg)
177 * Built-in command: run a Nasal script.
180 do_nasal (const SGPropertyNode * arg)
182 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
186 * Built-in command: exit FlightGear.
188 * status: the exit status to return to the operating system (defaults to 0)
191 do_exit (const SGPropertyNode * arg)
193 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
194 fgSetBool("/sim/signals/exit", true);
195 globals->saveUserSettings();
196 fgOSExit(arg->getIntValue("status", 0));
202 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
205 do_reset (const SGPropertyNode * arg)
207 fgReInitSubsystems();
212 * Built-in command: replay the FDR buffer
215 do_replay (const SGPropertyNode * arg)
217 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
222 * Built-in command: pause/unpause the sim
225 do_pause (const SGPropertyNode * arg)
227 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
228 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
234 fgSetBool("/sim/freeze/master",!paused);
235 fgSetBool("/sim/freeze/clock",!paused);
238 SGPropertyNode_ptr args(new SGPropertyNode);
239 args->setStringValue("id", "sim-pause");
240 if (!paused && fgGetBool("/sim/view-name-popup")) {
241 args->setStringValue("label", "Simulation is paused");
242 globals->get_commands()->execute("show-message", args);
244 globals->get_commands()->execute("clear-message", args);
251 * Built-in command: load flight.
253 * file (optional): the name of the file to load (relative to current
254 * directory). Defaults to "fgfs.sav"
257 do_load (const SGPropertyNode * arg)
259 string file = arg->getStringValue("file", "fgfs.sav");
260 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
263 if (!fgValidatePath(file.c_str(), false)) {
264 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
265 "(unauthorized access)");
269 ifstream input(file.c_str());
270 if (input.good() && fgLoadFlight(input)) {
272 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
275 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
282 * Built-in command: save flight.
284 * file (optional): the name of the file to save (relative to the
285 * current directory). Defaults to "fgfs.sav".
288 do_save (const SGPropertyNode * arg)
290 string file = arg->getStringValue("file", "fgfs.sav");
291 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
294 if (!fgValidatePath(file.c_str(), false)) {
295 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
296 "(unauthorized access)");
300 bool write_all = arg->getBoolValue("write-all", false);
301 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
302 ofstream output(file.c_str());
303 if (output.good() && fgSaveFlight(output, write_all)) {
305 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
308 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
314 * Built-in command: save flight recorder tape.
318 do_save_tape (const SGPropertyNode * arg)
320 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
321 replay->saveTape(arg);
326 * Built-in command: load flight recorder tape.
330 do_load_tape (const SGPropertyNode * arg)
332 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
333 replay->loadTape(arg);
339 * Built-in command: (re)load the panel.
341 * path (optional): the file name to load the panel from
342 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
343 * and if that's unspecified, to "Panels/Default/default.xml".
346 do_panel_load (const SGPropertyNode * arg)
348 string panel_path = arg->getStringValue("path");
349 if (!panel_path.empty()) {
350 // write to the standard property, which will force a load
351 fgSetString("/sim/panel/path", panel_path.c_str());
358 * Built-in command: (re)load preferences.
360 * path (optional): the file name to load the panel from (relative
361 * to FG_ROOT). Defaults to "preferences.xml".
364 do_preferences_load (const SGPropertyNode * arg)
367 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
368 globals->get_props());
369 } catch (const sg_exception &e) {
370 guiErrorMessage("Error reading global preferences: ", e);
373 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
378 do_view_next(bool do_it)
380 // Only switch view if really requested to do so (and not for example while
381 // reset/reposition where /command/view/next is set to false)
384 globals->get_current_view()->setHeadingOffset_deg(0.0);
385 globals->get_viewmgr()->next_view();
390 do_view_prev(bool do_it)
394 globals->get_current_view()->setHeadingOffset_deg(0.0);
395 globals->get_viewmgr()->prev_view();
400 * An fgcommand to toggle fullscreen mode.
404 do_toggle_fullscreen(const SGPropertyNode *arg)
411 * Built-in command: cycle view.
414 do_view_cycle (const SGPropertyNode * arg)
416 globals->get_current_view()->setHeadingOffset_deg(0.0);
417 globals->get_viewmgr()->next_view();
422 * Built-in command: capture screen.
425 do_screen_capture (const SGPropertyNode * arg)
427 return fgDumpSnapShot();
431 do_reload_shaders (const SGPropertyNode*)
433 simgear::reload_shaders();
438 do_dump_scene_graph (const SGPropertyNode*)
445 do_dump_terrain_branch (const SGPropertyNode*)
447 fgDumpTerrainBranch();
449 double lon_deg = fgGetDouble("/position/longitude-deg");
450 double lat_deg = fgGetDouble("/position/latitude-deg");
451 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
452 SGVec3d zero = SGVec3d::fromGeod(geodPos);
454 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
455 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
456 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
462 do_print_visible_scene_info(const SGPropertyNode*)
464 fgPrintVisibleSceneInfoCommand();
469 * Built-in command: hires capture screen.
472 do_hires_screen_capture (const SGPropertyNode * arg)
480 * Reload the tile cache.
483 do_tile_cache_reload (const SGPropertyNode * arg)
485 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
486 bool freeze = master_freeze->getBoolValue();
487 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
489 master_freeze->setBoolValue(true);
492 globals->get_subsystem("tile-manager")->reinit();
495 master_freeze->setBoolValue(false);
501 * Reload the materials definition
504 do_materials_reload (const SGPropertyNode * arg)
506 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
507 SGMaterialLib* new_matlib = new SGMaterialLib;
508 SGPath mpath( globals->get_fg_root() );
509 mpath.append( fgGetString("/sim/rendering/materials-file") );
510 bool loaded = new_matlib->load(globals->get_fg_root(),
512 globals->get_props());
515 SG_LOG( SG_GENERAL, SG_ALERT,
516 "Error loading materials file " << mpath.str() );
520 globals->set_matlib(new_matlib);
526 These do_set_(some-environment-parameters) are deprecated and no longer
527 useful/functional - Torsten Dreyer, January 2011
529 * Set the sea level outside air temperature and assigning that to all
530 * boundary and aloft environment layers.
533 do_set_sea_level_degc ( double temp_sea_level_degc)
535 SGPropertyNode *node, *child;
538 node = fgGetNode( "/environment/config/boundary" );
539 if ( node != NULL ) {
541 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
542 child->setDoubleValue( "temperature-sea-level-degc",
543 temp_sea_level_degc );
549 node = fgGetNode( "/environment/config/aloft" );
550 if ( node != NULL ) {
552 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
553 child->setDoubleValue( "temperature-sea-level-degc",
554 temp_sea_level_degc );
563 do_set_sea_level_degc (const SGPropertyNode * arg)
565 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
570 * Set the outside air temperature at the "current" altitude by first
571 * calculating the corresponding sea level temp, and assigning that to
572 * all boundary and aloft environment layers.
575 do_set_oat_degc (const SGPropertyNode * arg)
577 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
578 // check for an altitude specified in the arguments, otherwise use
579 // current aircraft altitude.
580 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
581 if ( altitude_ft == NULL ) {
582 altitude_ft = fgGetNode("/position/altitude-ft");
585 FGEnvironment dummy; // instantiate a dummy so we can leech a method
586 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
587 dummy.set_temperature_degc( oat_degc );
588 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
592 * Set the sea level outside air dewpoint and assigning that to all
593 * boundary and aloft environment layers.
596 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
599 SGPropertyNode *node, *child;
602 node = fgGetNode( "/environment/config/boundary" );
603 if ( node != NULL ) {
605 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
606 child->setDoubleValue( "dewpoint-sea-level-degc",
607 dewpoint_sea_level_degc );
613 node = fgGetNode( "/environment/config/aloft" );
614 if ( node != NULL ) {
616 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
617 child->setDoubleValue( "dewpoint-sea-level-degc",
618 dewpoint_sea_level_degc );
627 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
629 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
633 * Set the outside air dewpoint at the "current" altitude by first
634 * calculating the corresponding sea level dewpoint, and assigning
635 * that to all boundary and aloft environment layers.
638 do_set_dewpoint_degc (const SGPropertyNode * arg)
640 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
642 // check for an altitude specified in the arguments, otherwise use
643 // current aircraft altitude.
644 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
645 if ( altitude_ft == NULL ) {
646 altitude_ft = fgGetNode("/position/altitude-ft");
649 FGEnvironment dummy; // instantiate a dummy so we can leech a method
650 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
651 dummy.set_dewpoint_degc( dewpoint_degc );
652 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
657 * Built-in command: toggle a bool property value.
659 * property: The name of the property to toggle.
662 do_property_toggle (const SGPropertyNode * arg)
664 SGPropertyNode * prop = get_prop(arg);
665 return prop->setBoolValue(!prop->getBoolValue());
670 * Built-in command: assign a value to a property.
672 * property: the name of the property to assign.
673 * value: the value to assign; or
674 * property[1]: the property to copy from.
677 do_property_assign (const SGPropertyNode * arg)
679 SGPropertyNode * prop = get_prop(arg);
680 const SGPropertyNode * value = arg->getNode("value");
683 return prop->setUnspecifiedValue(value->getStringValue());
686 const SGPropertyNode * prop2 = get_prop2(arg);
688 return prop->setUnspecifiedValue(prop2->getStringValue());
696 * Built-in command: increment or decrement a property value.
698 * If the 'step' argument is present, it will be used; otherwise,
699 * the command uses 'offset' and 'factor', usually from the mouse.
701 * property: the name of the property to increment or decrement.
702 * step: the amount of the increment or decrement (default: 0).
703 * offset: offset from the current setting (used for the mouse; multiplied
705 * factor: scaling amount for the offset (defaults to 1).
706 * min: the minimum allowed value (default: no minimum).
707 * max: the maximum allowed value (default: no maximum).
708 * mask: 'integer' to apply only to the left of the decimal point,
709 * 'decimal' to apply only to the right of the decimal point,
710 * or 'all' to apply to the whole number (the default).
711 * wrap: true if the value should be wrapped when it passes min or max;
712 * both min and max must be present for this to work (default:
716 do_property_adjust (const SGPropertyNode * arg)
718 SGPropertyNode * prop = get_prop(arg);
721 if (arg->hasValue("step"))
722 amount = arg->getDoubleValue("step");
724 amount = (arg->getDoubleValue("factor", 1)
725 * arg->getDoubleValue("offset"));
727 double unmodifiable, modifiable;
728 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
729 &unmodifiable, &modifiable);
730 modifiable += amount;
731 limit_value(&modifiable, arg);
733 prop->setDoubleValue(unmodifiable + modifiable);
740 * Built-in command: multiply a property value.
742 * property: the name of the property to multiply.
743 * factor: the amount by which to multiply.
744 * min: the minimum allowed value (default: no minimum).
745 * max: the maximum allowed value (default: no maximum).
746 * mask: 'integer' to apply only to the left of the decimal point,
747 * 'decimal' to apply only to the right of the decimal point,
748 * or 'all' to apply to the whole number (the default).
749 * wrap: true if the value should be wrapped when it passes min or max;
750 * both min and max must be present for this to work (default:
754 do_property_multiply (const SGPropertyNode * arg)
756 SGPropertyNode * prop = get_prop(arg);
757 double factor = arg->getDoubleValue("factor", 1);
759 double unmodifiable, modifiable;
760 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
761 &unmodifiable, &modifiable);
762 modifiable *= factor;
763 limit_value(&modifiable, arg);
765 prop->setDoubleValue(unmodifiable + modifiable);
772 * Built-in command: swap two property values.
774 * property[0]: the name of the first property.
775 * property[1]: the name of the second property.
778 do_property_swap (const SGPropertyNode * arg)
780 SGPropertyNode * prop1 = get_prop(arg);
781 SGPropertyNode * prop2 = get_prop2(arg);
783 // FIXME: inefficient
784 const string & tmp = prop1->getStringValue();
785 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
786 prop2->setUnspecifiedValue(tmp.c_str()));
791 * Built-in command: Set a property to an axis or other moving input.
793 * property: the name of the property to set.
794 * setting: the current input setting, usually between -1.0 and 1.0.
795 * offset: the offset to shift by, before applying the factor.
796 * factor: the factor to multiply by (use negative to reverse).
799 do_property_scale (const SGPropertyNode * arg)
801 SGPropertyNode * prop = get_prop(arg);
802 double setting = arg->getDoubleValue("setting");
803 double offset = arg->getDoubleValue("offset", 0.0);
804 double factor = arg->getDoubleValue("factor", 1.0);
805 bool squared = arg->getBoolValue("squared", false);
806 int power = arg->getIntValue("power", (squared ? 2 : 1));
808 int sign = (setting < 0 ? -1 : 1);
814 setting = setting * setting * sign;
817 setting = setting * setting * setting;
820 setting = setting * setting * setting * setting * sign;
823 setting = pow(setting, power);
824 if ((power % 2) == 0)
829 return prop->setDoubleValue((setting + offset) * factor);
834 * Built-in command: cycle a property through a set of values.
836 * If the current value isn't in the list, the cycle will
837 * (re)start from the beginning.
839 * property: the name of the property to cycle.
840 * value[*]: the list of values to cycle through.
843 do_property_cycle (const SGPropertyNode * arg)
845 SGPropertyNode * prop = get_prop(arg);
846 std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
848 bool wrap = arg->getBoolValue("wrap", true);
849 // compatible with knob/pick animations
850 int offset = arg->getIntValue("offset", 1);
853 int nSelections = values.size();
855 if (nSelections < 1) {
856 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
860 // Try to find the current selection
861 for (int i = 0; i < nSelections; i++) {
862 if (compare_values(prop, values[i])) {
868 if (selection < 0) { // default to first selection
873 selection = (selection + nSelections) % nSelections;
875 SG_CLAMP_RANGE(selection, 0, nSelections - 1);
879 prop->setUnspecifiedValue(values[selection]->getStringValue());
885 * Built-in command: randomize a numeric property value.
887 * property: the name of the property value to randomize.
888 * min: the minimum allowed value.
889 * max: the maximum allowed value.
892 do_property_randomize (const SGPropertyNode * arg)
894 SGPropertyNode * prop = get_prop(arg);
895 double min = arg->getDoubleValue("min", DBL_MIN);
896 double max = arg->getDoubleValue("max", DBL_MAX);
897 prop->setDoubleValue(sg_random() * (max - min) + min);
902 * Built-in command: interpolate a property value over time
904 * property: the name of the property value to interpolate.
905 * type: the interpolation type ("numeric", "color", etc.)
906 * easing: name of easing function (see http://easings.net/)
907 * value[0..n] any number of constant values to interpolate
908 * time/rate[0..n] time between each value, number of time elements must
909 * match those of value elements. Instead of time also rate can
910 * be used which automatically calculates the time to change
911 * the property value at the given speed.
913 * property[1..n+1] any number of target values taken from named properties
914 * time/rate[0..n] time between each value, number of time elements must
915 * match those of value elements. Instead of time also rate can
916 * be used which automatically calculates the time to change
917 * the property value at the given speed.
920 do_property_interpolate (const SGPropertyNode * arg)
922 SGPropertyNode * prop = get_prop(arg);
926 simgear::PropertyList time_nodes = arg->getChildren("time");
927 simgear::PropertyList rate_nodes = arg->getChildren("rate");
929 if( !time_nodes.empty() && !rate_nodes.empty() )
930 // mustn't specify time and rate
933 simgear::PropertyList::size_type num_times = time_nodes.empty()
937 simgear::PropertyList value_nodes = arg->getChildren("value");
938 if( value_nodes.empty() )
940 simgear::PropertyList prop_nodes = arg->getChildren("property");
942 // must have one more property node
943 if( prop_nodes.size() != num_times + 1 )
946 value_nodes.reserve(num_times);
947 for( size_t i = 1; i < prop_nodes.size(); ++i )
948 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
952 if( value_nodes.size() != num_times )
956 deltas.reserve(num_times);
958 if( !time_nodes.empty() )
960 for( size_t i = 0; i < num_times; ++i )
961 deltas.push_back( time_nodes[i]->getDoubleValue() );
965 for( size_t i = 0; i < num_times; ++i )
967 // TODO calculate delta based on property type
968 double delta = value_nodes[i]->getDoubleValue()
970 ? value_nodes[i - 1]->getDoubleValue()
971 : prop->getDoubleValue()
973 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
977 return prop->interpolate
979 arg->getStringValue("type", "numeric"),
982 arg->getStringValue("easing", "linear")
987 * Built-in command: reinit the data logging system based on the
988 * current contents of the /logger tree.
991 do_data_logging_commit (const SGPropertyNode * arg)
993 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
999 * Built-in command: Add a dialog to the GUI system. Does *not*
1000 * display the dialog. The property node should have the same format
1001 * as a dialog XML configuration. It must include:
1003 * name: the name of the GUI dialog for future reference.
1006 do_dialog_new (const SGPropertyNode * arg)
1008 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1013 // Note the casting away of const: this is *real*. Doing a
1014 // "dialog-apply" command later on will mutate this property node.
1015 // I'm not convinced that this isn't the Right Thing though; it
1016 // allows client to create a node, pass it to dialog-new, and get
1017 // the values back from the dialog by reading the same node.
1018 // Perhaps command arguments are not as "const" as they would
1020 gui->newDialog((SGPropertyNode*)arg);
1025 * Built-in command: Show an XML-configured dialog.
1027 * dialog-name: the name of the GUI dialog to display.
1030 do_dialog_show (const SGPropertyNode * arg)
1032 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1033 gui->showDialog(arg->getStringValue("dialog-name"));
1039 * Built-in Command: Hide the active XML-configured dialog.
1042 do_dialog_close (const SGPropertyNode * arg)
1044 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1045 if(arg->hasValue("dialog-name"))
1046 return gui->closeDialog(arg->getStringValue("dialog-name"));
1047 return gui->closeActiveDialog();
1052 * Update a value in the active XML-configured dialog.
1054 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1057 do_dialog_update (const SGPropertyNode * arg)
1059 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1061 if (arg->hasValue("dialog-name"))
1062 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1064 dialog = gui->getActiveDialog();
1067 dialog->updateValues(arg->getStringValue("object-name"));
1075 do_open_browser (const SGPropertyNode * arg)
1078 if (arg->hasValue("path"))
1079 path = arg->getStringValue("path");
1081 if (arg->hasValue("url"))
1082 path = arg->getStringValue("url");
1086 return openBrowser(path);
1090 * Apply a value in the active XML-configured dialog.
1092 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1095 do_dialog_apply (const SGPropertyNode * arg)
1097 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1099 if (arg->hasValue("dialog-name"))
1100 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1102 dialog = gui->getActiveDialog();
1105 dialog->applyValues(arg->getStringValue("object-name"));
1114 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1118 do_gui_redraw (const SGPropertyNode * arg)
1120 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1127 * Adds model to the scenery. The path to the added branch (/models/model[*])
1128 * is returned in property "property".
1131 do_add_model (const SGPropertyNode * arg)
1133 SGPropertyNode * model = fgGetNode("models", true);
1135 for (i = 0; model->hasChild("model",i); i++);
1136 model = model->getChild("model", i, true);
1137 copyProperties(arg, model);
1138 if (model->hasValue("elevation-m"))
1139 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1140 * SG_METER_TO_FEET);
1141 model->getNode("load", true);
1142 model->removeChildren("load");
1143 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1148 * Built-in command: play an audio message (i.e. a wav file) This is
1149 * fire and forget. Call this once per message and it will get dumped
1150 * into a queue. Messages are played sequentially so they do not
1154 do_play_audio_sample (const SGPropertyNode * arg)
1156 SGSoundMgr *smgr = globals->get_soundmgr();
1158 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1162 string path = arg->getStringValue("path");
1163 string file = arg->getStringValue("file");
1164 float volume = arg->getFloatValue("volume");
1165 // cout << "playing " << path << " / " << file << endl;
1167 static FGSampleQueue *queue = 0;
1169 queue = new FGSampleQueue(smgr, "chatter");
1170 queue->tie_to_listener();
1173 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1174 msg->set_volume( volume );
1179 } catch (const sg_io_exception&) {
1180 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1181 "failed to load" << path << '/' << file);
1187 * Built-in command: commit presets (read from in /sim/presets/)
1190 do_presets_commit (const SGPropertyNode * arg)
1192 if (fgGetBool("/sim/initialized", false)) {
1193 fgReInitSubsystems();
1195 // Nasal can trigger this during initial init, which confuses
1196 // the logic in ReInitSubsystems, since initial state has not been
1197 // saved at that time. Short-circuit everything here.
1198 flightgear::initPosition();
1205 * Built-in command: set log level (0 ... 7)
1208 do_log_level (const SGPropertyNode * arg)
1210 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1217 do_decrease_visibility (const SGPropertyNode * arg)
1219 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1224 do_increase_visibility (const SGPropertyNode * arg)
1226 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1231 * An fgcommand to allow loading of xml files via nasal,
1232 * the xml file's structure will be made available within
1233 * a property tree node defined under argument "targetnode",
1234 * or in the given argument tree under "data" otherwise.
1236 * @param filename a string to hold the complete path & filename of an XML file
1237 * @param targetnode a string pointing to a location within the property tree
1238 * where to store the parsed XML file. If <targetnode> is undefined, then the
1239 * file contents are stored under a node <data> in the argument tree.
1243 do_load_xml_to_proptree(const SGPropertyNode * arg)
1245 SGPath file(arg->getStringValue("filename"));
1246 if (file.str().empty())
1249 if (file.extension() != "xml")
1250 file.concat(".xml");
1252 std::string icao = arg->getStringValue("icao");
1254 if (file.isRelative()) {
1255 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1256 if (!absPath.isNull())
1260 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1261 << file.str() << "'.");
1266 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1267 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1268 << file.str() << " at ICAO:" << icao);
1273 if (!fgValidatePath(file.c_str(), false)) {
1274 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1275 "(unauthorized access)");
1279 SGPropertyNode *targetnode;
1280 if (arg->hasValue("targetnode"))
1281 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1283 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1286 readProperties(file.c_str(), targetnode, true);
1287 } catch (const sg_exception &e) {
1288 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1295 class RemoteXMLRequest:
1296 public simgear::HTTP::MemoryRequest
1299 SGPropertyNode_ptr _complete;
1300 SGPropertyNode_ptr _status;
1301 SGPropertyNode_ptr _failed;
1302 SGPropertyNode_ptr _target;
1304 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1305 simgear::HTTP::MemoryRequest(url),
1310 void setCompletionProp(SGPropertyNode_ptr p)
1315 void setStatusProp(SGPropertyNode_ptr p)
1320 void setFailedProp(SGPropertyNode_ptr p)
1327 virtual void onFail()
1329 SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1331 _failed->setBoolValue(true);
1335 virtual void onDone()
1337 int response = responseCode();
1338 bool failed = false;
1339 if (response == 200) {
1341 const char* buffer = responseBody().c_str();
1342 readProperties(buffer, responseBody().size(), _target, true);
1343 } catch (const sg_exception &e) {
1344 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1346 response = 406; // 'not acceptable', anything better?
1351 // now the response data is output, signal Nasal / listeners
1352 if (_complete) _complete->setBoolValue(true);
1353 if (_status) _status->setIntValue(response);
1354 if (_failed && failed) _failed->setBoolValue(true);
1360 do_load_xml_from_url(const SGPropertyNode * arg)
1362 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1364 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1368 std::string url(arg->getStringValue("url"));
1372 SGPropertyNode *targetnode;
1373 if (arg->hasValue("targetnode"))
1374 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1376 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1378 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1380 if (arg->hasChild("body"))
1381 req->setBodyData(arg->getChild("body"));
1383 // connect up optional reporting properties
1384 if (arg->hasValue("complete"))
1385 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1386 if (arg->hasValue("failure"))
1387 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1388 if (arg->hasValue("status"))
1389 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1391 http->makeRequest(req);
1397 * An fgcommand to allow saving of xml files via nasal,
1398 * the file's structure will be determined based on what's
1399 * encountered in the passed (source) property tree node
1401 * @param filename a string to hold the complete path & filename of the (new)
1403 * @param sourcenode a string pointing to a location within the property tree
1404 * where to find the nodes that should be written recursively into an XML file
1405 * @param data if no sourcenode is given, then the file contents are taken from
1406 * the argument tree's "data" node.
1410 do_save_xml_from_proptree(const SGPropertyNode * arg)
1412 SGPath file(arg->getStringValue("filename"));
1413 if (file.str().empty())
1416 if (file.extension() != "xml")
1417 file.concat(".xml");
1419 if (!fgValidatePath(file.c_str(), true)) {
1420 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1421 "(unauthorized access)");
1425 SGPropertyNode *sourcenode;
1426 if (arg->hasValue("sourcenode"))
1427 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1428 else if (arg->getNode("data", false))
1429 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1434 writeProperties (file.c_str(), sourcenode, true);
1435 } catch (const sg_exception &e) {
1436 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1444 do_press_cockpit_button (const SGPropertyNode *arg)
1446 const char *prefix = arg->getStringValue("prefix");
1448 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1451 string prop = string(prefix) + "-button";
1454 if (arg->getBoolValue("latching"))
1455 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1459 fgSetDouble(prop.c_str(), value);
1460 fgSetBool(arg->getStringValue("discrete"), value > 0);
1466 do_release_cockpit_button (const SGPropertyNode *arg)
1468 const char *prefix = arg->getStringValue("prefix");
1470 if (arg->getBoolValue("guarded")) {
1471 string prop = string(prefix) + "-guard";
1472 if (fgGetDouble(prop.c_str()) < 1) {
1473 fgSetDouble(prop.c_str(), 1);
1478 if (! arg->getBoolValue("latching")) {
1479 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1480 fgSetBool(arg->getStringValue("discrete"), false);
1486 // Optional profiling commands using gperftools:
1487 // http://code.google.com/p/gperftools/
1489 #if !FG_HAVE_GPERFTOOLS
1491 no_profiling_support()
1497 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1503 do_profiler_start(const SGPropertyNode *arg)
1505 #if FG_HAVE_GPERFTOOLS
1506 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1507 ProfilerStart(filename);
1510 no_profiling_support();
1516 do_profiler_stop(const SGPropertyNode *arg)
1518 #if FG_HAVE_GPERFTOOLS
1522 no_profiling_support();
1528 ////////////////////////////////////////////////////////////////////////
1530 ////////////////////////////////////////////////////////////////////////
1534 * Table of built-in commands.
1536 * New commands do not have to be added here; any module in the application
1537 * can add a new command using globals->get_commands()->addCommand(...).
1541 SGCommandMgr::command_t command;
1543 { "null", do_null },
1544 { "nasal", do_nasal },
1545 { "exit", do_exit },
1546 { "reset", do_reset },
1547 { "pause", do_pause },
1548 { "load", do_load },
1549 { "save", do_save },
1550 { "save-tape", do_save_tape },
1551 { "load-tape", do_load_tape },
1552 { "panel-load", do_panel_load },
1553 { "preferences-load", do_preferences_load },
1554 { "toggle-fullscreen", do_toggle_fullscreen },
1555 { "view-cycle", do_view_cycle },
1556 { "screen-capture", do_screen_capture },
1557 { "hires-screen-capture", do_hires_screen_capture },
1558 { "tile-cache-reload", do_tile_cache_reload },
1560 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1561 { "set-outside-air-temp-degc", do_set_oat_degc },
1562 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1563 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1565 { "property-toggle", do_property_toggle },
1566 { "property-assign", do_property_assign },
1567 { "property-adjust", do_property_adjust },
1568 { "property-multiply", do_property_multiply },
1569 { "property-swap", do_property_swap },
1570 { "property-scale", do_property_scale },
1571 { "property-cycle", do_property_cycle },
1572 { "property-randomize", do_property_randomize },
1573 { "property-interpolate", do_property_interpolate },
1574 { "data-logging-commit", do_data_logging_commit },
1575 { "dialog-new", do_dialog_new },
1576 { "dialog-show", do_dialog_show },
1577 { "dialog-close", do_dialog_close },
1578 { "dialog-update", do_dialog_update },
1579 { "dialog-apply", do_dialog_apply },
1580 { "open-browser", do_open_browser },
1581 { "gui-redraw", do_gui_redraw },
1582 { "add-model", do_add_model },
1583 { "play-audio-sample", do_play_audio_sample },
1584 { "presets-commit", do_presets_commit },
1585 { "log-level", do_log_level },
1586 { "replay", do_replay },
1588 { "decrease-visibility", do_decrease_visibility },
1589 { "increase-visibility", do_increase_visibility },
1591 { "loadxml", do_load_xml_to_proptree},
1592 { "savexml", do_save_xml_from_proptree },
1593 { "xmlhttprequest", do_load_xml_from_url },
1594 { "press-cockpit-button", do_press_cockpit_button },
1595 { "release-cockpit-button", do_release_cockpit_button },
1596 { "dump-scenegraph", do_dump_scene_graph },
1597 { "dump-terrainbranch", do_dump_terrain_branch },
1598 { "print-visible-scene", do_print_visible_scene_info },
1599 { "reload-shaders", do_reload_shaders },
1600 { "reload-materials", do_materials_reload },
1602 { "profiler-start", do_profiler_start },
1603 { "profiler-stop", do_profiler_stop },
1605 { 0, 0 } // zero-terminated
1610 * Initialize the default built-in commands.
1612 * Other commands may be added by other parts of the application.
1617 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1618 for (int i = 0; built_ins[i].name != 0; i++) {
1619 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1620 globals->get_commands()->addCommand(built_ins[i].name,
1621 built_ins[i].command);
1624 typedef bool (*dummy)();
1625 fgTie( "/command/view/next", dummy(0), do_view_next );
1626 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1628 globals->get_props()->setValueReadOnly( "/sim/debug/profiler-available",
1629 bool(FG_HAVE_GPERFTOOLS) );
1632 // end of fg_commands.cxx