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"
53 #include <boost/scoped_array.hpp>
61 ////////////////////////////////////////////////////////////////////////
62 // Static helper functions.
63 ////////////////////////////////////////////////////////////////////////
66 static inline SGPropertyNode *
67 get_prop (const SGPropertyNode * arg)
69 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
72 static inline SGPropertyNode *
73 get_prop2 (const SGPropertyNode * arg)
75 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
80 * Get a double value and split it as required.
83 split_value (double full_value, const char * mask,
84 double * unmodifiable, double * modifiable)
86 if (!strcmp("integer", mask)) {
87 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
88 *unmodifiable = full_value - *modifiable;
89 } else if (!strcmp("decimal", mask)) {
90 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
91 *modifiable = full_value - *unmodifiable;
93 if (strcmp("all", mask))
94 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
95 << " assuming 'all'");
97 *modifiable = full_value;
103 * Clamp or wrap a value as specified.
106 limit_value (double * value, const SGPropertyNode * arg)
108 const SGPropertyNode * min_node = arg->getChild("min");
109 const SGPropertyNode * max_node = arg->getChild("max");
111 bool wrap = arg->getBoolValue("wrap");
113 if (min_node == 0 || max_node == 0)
116 if (wrap) { // wrap such that min <= x < max
117 double min_val = min_node->getDoubleValue();
118 double max_val = max_node->getDoubleValue();
119 double resolution = arg->getDoubleValue("resolution");
120 if (resolution > 0.0) {
121 // snap to (min + N*resolution), taking special care to handle imprecision
122 int n = (int)floor((*value - min_val) / resolution + 0.5);
123 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
124 SG_NORMALIZE_RANGE(n, 0, steps);
125 *value = min_val + resolution * n;
127 // plain circular wrapping
128 SG_NORMALIZE_RANGE(*value, min_val, max_val);
130 } else { // clamp such that min <= x <= max
131 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
132 *value = min_node->getDoubleValue();
133 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
134 *value = max_node->getDoubleValue();
139 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
141 switch (value1->getType()) {
142 case simgear::props::BOOL:
143 return (value1->getBoolValue() == value2->getBoolValue());
144 case simgear::props::INT:
145 return (value1->getIntValue() == value2->getIntValue());
146 case simgear::props::LONG:
147 return (value1->getLongValue() == value2->getLongValue());
148 case simgear::props::FLOAT:
149 return (value1->getFloatValue() == value2->getFloatValue());
150 case simgear::props::DOUBLE:
151 return (value1->getDoubleValue() == value2->getDoubleValue());
153 return !strcmp(value1->getStringValue(), value2->getStringValue());
159 ////////////////////////////////////////////////////////////////////////
160 // Command implementations.
161 ////////////////////////////////////////////////////////////////////////
165 * Built-in command: do nothing.
168 do_null (const SGPropertyNode * arg)
174 * Built-in command: run a Nasal script.
177 do_nasal (const SGPropertyNode * arg)
179 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
183 * Built-in command: exit FlightGear.
185 * status: the exit status to return to the operating system (defaults to 0)
188 do_exit (const SGPropertyNode * arg)
190 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
191 fgSetBool("/sim/signals/exit", true);
192 globals->saveUserSettings();
193 fgOSExit(arg->getIntValue("status", 0));
199 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
202 do_reset (const SGPropertyNode * arg)
204 fgReInitSubsystems();
210 * Built-in command: reinitialize one or more subsystems.
212 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
213 * none is specified, reinitialize all of them.
216 do_reinit (const SGPropertyNode * arg)
220 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
221 if (subsystems.size() == 0) {
222 globals->get_subsystem_mgr()->reinit();
224 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
225 const char * name = subsystems[i]->getStringValue();
226 SGSubsystem * subsystem = globals->get_subsystem(name);
227 if (subsystem == 0) {
229 SG_LOG( SG_GENERAL, SG_ALERT,
230 "Subsystem " << name << " not found" );
237 globals->get_event_mgr()->reinit();
244 // these routines look useful ??? but are never used in the code ???
248 * Built-in command: suspend one or more subsystems.
250 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
253 do_suspend (const SGPropertyNode * arg)
257 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
258 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
259 const char * name = subsystems[i]->getStringValue();
260 SGSubsystem * subsystem = globals->get_subsystem(name);
261 if (subsystem == 0) {
263 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
265 subsystem->suspend();
272 * Built-in command: suspend one or more subsystems.
274 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
277 do_resume (const SGPropertyNode * arg)
281 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
282 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
283 const char * name = subsystems[i]->getStringValue();
284 SGSubsystem * subsystem = globals->get_subsystem(name);
285 if (subsystem == 0) {
287 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
298 * Built-in command: replay the FDR buffer
301 do_replay (const SGPropertyNode * arg)
303 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
308 * Built-in command: pause/unpause the sim
311 do_pause (const SGPropertyNode * arg)
313 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
314 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
320 fgSetBool("/sim/freeze/master",!paused);
321 fgSetBool("/sim/freeze/clock",!paused);
327 * Built-in command: load flight.
329 * file (optional): the name of the file to load (relative to current
330 * directory). Defaults to "fgfs.sav"
333 do_load (const SGPropertyNode * arg)
335 string file = arg->getStringValue("file", "fgfs.sav");
336 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
339 if (!fgValidatePath(file.c_str(), false)) {
340 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
341 "(unauthorized access)");
345 ifstream input(file.c_str());
346 if (input.good() && fgLoadFlight(input)) {
348 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
351 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
358 * Built-in command: save flight.
360 * file (optional): the name of the file to save (relative to the
361 * current directory). Defaults to "fgfs.sav".
364 do_save (const SGPropertyNode * arg)
366 string file = arg->getStringValue("file", "fgfs.sav");
367 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
370 if (!fgValidatePath(file.c_str(), false)) {
371 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
372 "(unauthorized access)");
376 bool write_all = arg->getBoolValue("write-all", false);
377 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
378 ofstream output(file.c_str());
379 if (output.good() && fgSaveFlight(output, write_all)) {
381 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
384 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
391 * Built-in command: (re)load the panel.
393 * path (optional): the file name to load the panel from
394 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
395 * and if that's unspecified, to "Panels/Default/default.xml".
398 do_panel_load (const SGPropertyNode * arg)
400 string panel_path = arg->getStringValue("path");
401 if (!panel_path.empty()) {
402 // write to the standard property, which will force a load
403 fgSetString("/sim/panel/path", panel_path.c_str());
410 * Built-in command: (re)load preferences.
412 * path (optional): the file name to load the panel from (relative
413 * to FG_ROOT). Defaults to "preferences.xml".
416 do_preferences_load (const SGPropertyNode * arg)
419 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
420 globals->get_props());
421 } catch (const sg_exception &e) {
422 guiErrorMessage("Error reading global preferences: ", e);
425 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
432 globals->get_current_view()->setHeadingOffset_deg(0.0);
433 globals->get_viewmgr()->next_view();
439 globals->get_current_view()->setHeadingOffset_deg(0.0);
440 globals->get_viewmgr()->prev_view();
444 * Built-in command: cycle view.
447 do_view_cycle (const SGPropertyNode * arg)
449 globals->get_current_view()->setHeadingOffset_deg(0.0);
450 globals->get_viewmgr()->next_view();
455 * Built-in command: capture screen.
458 do_screen_capture (const SGPropertyNode * arg)
460 return fgDumpSnapShot();
464 do_reload_shaders (const SGPropertyNode*)
466 simgear::reload_shaders();
471 do_dump_scene_graph (const SGPropertyNode*)
478 do_dump_terrain_branch (const SGPropertyNode*)
480 fgDumpTerrainBranch();
482 double lon_deg = fgGetDouble("/position/longitude-deg");
483 double lat_deg = fgGetDouble("/position/latitude-deg");
484 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
485 SGVec3d zero = SGVec3d::fromGeod(geodPos);
487 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
488 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
489 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
495 do_print_visible_scene_info(const SGPropertyNode*)
497 fgPrintVisibleSceneInfoCommand();
502 * Built-in command: hires capture screen.
505 do_hires_screen_capture (const SGPropertyNode * arg)
513 * Reload the tile cache.
516 do_tile_cache_reload (const SGPropertyNode * arg)
518 static const SGPropertyNode *master_freeze
519 = fgGetNode("/sim/freeze/master");
520 bool freeze = master_freeze->getBoolValue();
521 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
523 fgSetBool("/sim/freeze/master", true);
526 globals->get_subsystem("tile-manager")->reinit();
529 fgSetBool("/sim/freeze/master", false);
535 * Reload the materials definition
538 do_materials_reload (const SGPropertyNode * arg)
540 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
541 SGMaterialLib* new_matlib = new SGMaterialLib;
542 SGPath mpath( globals->get_fg_root() );
543 mpath.append( fgGetString("/sim/rendering/materials-file") );
544 bool loaded = new_matlib->load(globals->get_fg_root(),
546 globals->get_props());
549 SG_LOG( SG_GENERAL, SG_ALERT,
550 "Error loading materials file " << mpath.str() );
554 globals->set_matlib(new_matlib);
560 These do_set_(some-environment-parameters) are deprecated and no longer
561 useful/functional - Torsten Dreyer, January 2011
563 * Set the sea level outside air temperature and assigning that to all
564 * boundary and aloft environment layers.
567 do_set_sea_level_degc ( double temp_sea_level_degc)
569 SGPropertyNode *node, *child;
572 node = fgGetNode( "/environment/config/boundary" );
573 if ( node != NULL ) {
575 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
576 child->setDoubleValue( "temperature-sea-level-degc",
577 temp_sea_level_degc );
583 node = fgGetNode( "/environment/config/aloft" );
584 if ( node != NULL ) {
586 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
587 child->setDoubleValue( "temperature-sea-level-degc",
588 temp_sea_level_degc );
597 do_set_sea_level_degc (const SGPropertyNode * arg)
599 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
604 * Set the outside air temperature at the "current" altitude by first
605 * calculating the corresponding sea level temp, and assigning that to
606 * all boundary and aloft environment layers.
609 do_set_oat_degc (const SGPropertyNode * arg)
611 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
612 // check for an altitude specified in the arguments, otherwise use
613 // current aircraft altitude.
614 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
615 if ( altitude_ft == NULL ) {
616 altitude_ft = fgGetNode("/position/altitude-ft");
619 FGEnvironment dummy; // instantiate a dummy so we can leech a method
620 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
621 dummy.set_temperature_degc( oat_degc );
622 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
626 * Set the sea level outside air dewpoint and assigning that to all
627 * boundary and aloft environment layers.
630 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
633 SGPropertyNode *node, *child;
636 node = fgGetNode( "/environment/config/boundary" );
637 if ( node != NULL ) {
639 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
640 child->setDoubleValue( "dewpoint-sea-level-degc",
641 dewpoint_sea_level_degc );
647 node = fgGetNode( "/environment/config/aloft" );
648 if ( node != NULL ) {
650 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
651 child->setDoubleValue( "dewpoint-sea-level-degc",
652 dewpoint_sea_level_degc );
661 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
663 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
667 * Set the outside air dewpoint at the "current" altitude by first
668 * calculating the corresponding sea level dewpoint, and assigning
669 * that to all boundary and aloft environment layers.
672 do_set_dewpoint_degc (const SGPropertyNode * arg)
674 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
676 // check for an altitude specified in the arguments, otherwise use
677 // current aircraft altitude.
678 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
679 if ( altitude_ft == NULL ) {
680 altitude_ft = fgGetNode("/position/altitude-ft");
683 FGEnvironment dummy; // instantiate a dummy so we can leech a method
684 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
685 dummy.set_dewpoint_degc( dewpoint_degc );
686 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
691 * Built-in command: toggle a bool property value.
693 * property: The name of the property to toggle.
696 do_property_toggle (const SGPropertyNode * arg)
698 SGPropertyNode * prop = get_prop(arg);
699 return prop->setBoolValue(!prop->getBoolValue());
704 * Built-in command: assign a value to a property.
706 * property: the name of the property to assign.
707 * value: the value to assign; or
708 * property[1]: the property to copy from.
711 do_property_assign (const SGPropertyNode * arg)
713 SGPropertyNode * prop = get_prop(arg);
714 const SGPropertyNode * value = arg->getNode("value");
717 return prop->setUnspecifiedValue(value->getStringValue());
720 const SGPropertyNode * prop2 = get_prop2(arg);
722 return prop->setUnspecifiedValue(prop2->getStringValue());
730 * Built-in command: increment or decrement a property value.
732 * If the 'step' argument is present, it will be used; otherwise,
733 * the command uses 'offset' and 'factor', usually from the mouse.
735 * property: the name of the property to increment or decrement.
736 * step: the amount of the increment or decrement (default: 0).
737 * offset: offset from the current setting (used for the mouse; multiplied
739 * factor: scaling amount for the offset (defaults to 1).
740 * min: the minimum allowed value (default: no minimum).
741 * max: the maximum allowed value (default: no maximum).
742 * mask: 'integer' to apply only to the left of the decimal point,
743 * 'decimal' to apply only to the right of the decimal point,
744 * or 'all' to apply to the whole number (the default).
745 * wrap: true if the value should be wrapped when it passes min or max;
746 * both min and max must be present for this to work (default:
750 do_property_adjust (const SGPropertyNode * arg)
752 SGPropertyNode * prop = get_prop(arg);
755 if (arg->hasValue("step"))
756 amount = arg->getDoubleValue("step");
758 amount = (arg->getDoubleValue("factor", 1)
759 * arg->getDoubleValue("offset"));
761 double unmodifiable, modifiable;
762 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
763 &unmodifiable, &modifiable);
764 modifiable += amount;
765 limit_value(&modifiable, arg);
767 prop->setDoubleValue(unmodifiable + modifiable);
774 * Built-in command: multiply a property value.
776 * property: the name of the property to multiply.
777 * factor: the amount by which to multiply.
778 * min: the minimum allowed value (default: no minimum).
779 * max: the maximum allowed value (default: no maximum).
780 * mask: 'integer' to apply only to the left of the decimal point,
781 * 'decimal' to apply only to the right of the decimal point,
782 * or 'all' to apply to the whole number (the default).
783 * wrap: true if the value should be wrapped when it passes min or max;
784 * both min and max must be present for this to work (default:
788 do_property_multiply (const SGPropertyNode * arg)
790 SGPropertyNode * prop = get_prop(arg);
791 double factor = arg->getDoubleValue("factor", 1);
793 double unmodifiable, modifiable;
794 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
795 &unmodifiable, &modifiable);
796 modifiable *= factor;
797 limit_value(&modifiable, arg);
799 prop->setDoubleValue(unmodifiable + modifiable);
806 * Built-in command: swap two property values.
808 * property[0]: the name of the first property.
809 * property[1]: the name of the second property.
812 do_property_swap (const SGPropertyNode * arg)
814 SGPropertyNode * prop1 = get_prop(arg);
815 SGPropertyNode * prop2 = get_prop2(arg);
817 // FIXME: inefficient
818 const string & tmp = prop1->getStringValue();
819 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
820 prop2->setUnspecifiedValue(tmp.c_str()));
825 * Built-in command: Set a property to an axis or other moving input.
827 * property: the name of the property to set.
828 * setting: the current input setting, usually between -1.0 and 1.0.
829 * offset: the offset to shift by, before applying the factor.
830 * factor: the factor to multiply by (use negative to reverse).
833 do_property_scale (const SGPropertyNode * arg)
835 SGPropertyNode * prop = get_prop(arg);
836 double setting = arg->getDoubleValue("setting");
837 double offset = arg->getDoubleValue("offset", 0.0);
838 double factor = arg->getDoubleValue("factor", 1.0);
839 bool squared = arg->getBoolValue("squared", false);
840 int power = arg->getIntValue("power", (squared ? 2 : 1));
842 int sign = (setting < 0 ? -1 : 1);
848 setting = setting * setting * sign;
851 setting = setting * setting * setting;
854 setting = setting * setting * setting * setting * sign;
857 setting = pow(setting, power);
858 if ((power % 2) == 0)
863 return prop->setDoubleValue((setting + offset) * factor);
868 * Built-in command: cycle a property through a set of values.
870 * If the current value isn't in the list, the cycle will
871 * (re)start from the beginning.
873 * property: the name of the property to cycle.
874 * value[*]: the list of values to cycle through.
877 do_property_cycle (const SGPropertyNode * arg)
879 SGPropertyNode * prop = get_prop(arg);
880 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
882 int nSelections = values.size();
884 if (nSelections < 1) {
885 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
889 // Try to find the current selection
890 for (int i = 0; i < nSelections; i++) {
891 if (compare_values(prop, values[i])) {
897 // Default or wrap to the first selection
898 if (selection < 0 || selection >= nSelections)
901 prop->setUnspecifiedValue(values[selection]->getStringValue());
907 * Built-in command: randomize a numeric property value.
909 * property: the name of the property value to randomize.
910 * min: the minimum allowed value.
911 * max: the maximum allowed value.
914 do_property_randomize (const SGPropertyNode * arg)
916 SGPropertyNode * prop = get_prop(arg);
917 double min = arg->getDoubleValue("min", DBL_MIN);
918 double max = arg->getDoubleValue("max", DBL_MAX);
919 prop->setDoubleValue(sg_random() * (max - min) + min);
924 * Built-in command: interpolate a property value over time
926 * property: the name of the property value to interpolate.
927 * value[0..n] any number of constant values to interpolate
928 * time[0..n] time between each value, number of time elements must
929 * match those of value elements
931 * property[1..n] any number of target values taken from named properties
932 * time[0..n] time between each value, number of time elements must
933 * match those of property elements minus one
936 do_property_interpolate (const SGPropertyNode * arg)
938 SGPropertyNode * prop = get_prop(arg);
940 simgear::PropertyList valueNodes = arg->getChildren( "value" );
941 simgear::PropertyList timeNodes = arg->getChildren( "time" );
943 boost::scoped_array<double> value;
944 boost::scoped_array<double> time;
946 if( valueNodes.size() > 0 ) {
948 if( timeNodes.size() != valueNodes.size() )
951 value.reset( new double[valueNodes.size()] );
952 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
953 value[n] = valueNodes[n]->getDoubleValue();
956 valueNodes = arg->getChildren("property");
957 // must have one more property node
958 if( valueNodes.size() - 1 != timeNodes.size() )
961 value.reset( new double[valueNodes.size()-1] );
962 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
963 value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
968 time.reset( new double[timeNodes.size()] );
969 for( simgear::PropertyList::size_type n = 0; n < timeNodes.size(); n++ ) {
970 time[n] = timeNodes[n]->getDoubleValue();
973 ((SGInterpolator*)globals->get_subsystem_mgr()
974 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
975 ->interpolate(prop, timeNodes.size(), value.get(), time.get() );
981 * Built-in command: reinit the data logging system based on the
982 * current contents of the /logger tree.
985 do_data_logging_commit (const SGPropertyNode * arg)
987 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
993 * Built-in command: Add a dialog to the GUI system. Does *not*
994 * display the dialog. The property node should have the same format
995 * as a dialog XML configuration. It must include:
997 * name: the name of the GUI dialog for future reference.
1000 do_dialog_new (const SGPropertyNode * arg)
1002 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1004 // Note the casting away of const: this is *real*. Doing a
1005 // "dialog-apply" command later on will mutate this property node.
1006 // I'm not convinced that this isn't the Right Thing though; it
1007 // allows client to create a node, pass it to dialog-new, and get
1008 // the values back from the dialog by reading the same node.
1009 // Perhaps command arguments are not as "const" as they would
1011 gui->newDialog((SGPropertyNode*)arg);
1016 * Built-in command: Show an XML-configured dialog.
1018 * dialog-name: the name of the GUI dialog to display.
1021 do_dialog_show (const SGPropertyNode * arg)
1023 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1024 gui->showDialog(arg->getStringValue("dialog-name"));
1030 * Built-in Command: Hide the active XML-configured dialog.
1033 do_dialog_close (const SGPropertyNode * arg)
1035 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1036 if(arg->hasValue("dialog-name"))
1037 return gui->closeDialog(arg->getStringValue("dialog-name"));
1038 return gui->closeActiveDialog();
1043 * Update a value in the active XML-configured dialog.
1045 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1048 do_dialog_update (const SGPropertyNode * arg)
1050 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1052 if (arg->hasValue("dialog-name"))
1053 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1055 dialog = gui->getActiveDialog();
1058 dialog->updateValues(arg->getStringValue("object-name"));
1066 do_open_browser (const SGPropertyNode * arg)
1069 if (arg->hasValue("path"))
1070 path = arg->getStringValue("path");
1072 if (arg->hasValue("url"))
1073 path = arg->getStringValue("url");
1077 return openBrowser(path);
1081 * Apply a value in the active XML-configured dialog.
1083 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1086 do_dialog_apply (const SGPropertyNode * arg)
1088 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1090 if (arg->hasValue("dialog-name"))
1091 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1093 dialog = gui->getActiveDialog();
1096 dialog->applyValues(arg->getStringValue("object-name"));
1105 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1109 do_gui_redraw (const SGPropertyNode * arg)
1111 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1118 * Adds model to the scenery. The path to the added branch (/models/model[*])
1119 * is returned in property "property".
1122 do_add_model (const SGPropertyNode * arg)
1124 SGPropertyNode * model = fgGetNode("models", true);
1126 for (i = 0; model->hasChild("model",i); i++);
1127 model = model->getChild("model", i, true);
1128 copyProperties(arg, model);
1129 if (model->hasValue("elevation-m"))
1130 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1131 * SG_METER_TO_FEET);
1132 model->getNode("load", true);
1133 model->removeChildren("load");
1134 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1140 * Set mouse cursor coordinates and cursor shape.
1143 do_set_cursor (const SGPropertyNode * arg)
1145 if (arg->hasValue("x") || arg->hasValue("y")) {
1146 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1147 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1148 int x = arg->getIntValue("x", mx->getIntValue());
1149 int y = arg->getIntValue("y", my->getIntValue());
1155 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1156 if (cursor->getType() != simgear::props::NONE)
1157 fgSetMouseCursor(cursor->getIntValue());
1159 cursor->setIntValue(fgGetMouseCursor());
1165 * Built-in command: play an audio message (i.e. a wav file) This is
1166 * fire and forget. Call this once per message and it will get dumped
1167 * into a queue. Messages are played sequentially so they do not
1171 do_play_audio_sample (const SGPropertyNode * arg)
1173 string path = arg->getStringValue("path");
1174 string file = arg->getStringValue("file");
1175 float volume = arg->getFloatValue("volume");
1176 // cout << "playing " << path << " / " << file << endl;
1178 static FGSampleQueue *queue = 0;
1180 SGSoundMgr *smgr = globals->get_soundmgr();
1181 queue = new FGSampleQueue(smgr, "chatter");
1182 queue->tie_to_listener();
1185 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1186 msg->set_volume( volume );
1191 } catch (const sg_io_exception&) {
1192 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1193 "failed to load" << path << '/' << file);
1199 * Built-in command: commit presets (read from in /sim/presets/)
1202 do_presets_commit (const SGPropertyNode * arg)
1204 if (fgGetBool("/sim/initialized", false)) {
1205 fgReInitSubsystems();
1207 // Nasal can trigger this during initial init, which confuses
1208 // the logic in ReInitSubsystems, since initial state has not been
1209 // saved at that time. Short-circuit everything here.
1217 * Built-in command: set log level (0 ... 7)
1220 do_log_level (const SGPropertyNode * arg)
1222 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1229 do_decrease_visibility (const SGPropertyNode * arg)
1231 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1236 do_increase_visibility (const SGPropertyNode * arg)
1238 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1243 * An fgcommand to allow loading of xml files via nasal,
1244 * the xml file's structure will be made available within
1245 * a property tree node defined under argument "targetnode",
1246 * or in the given argument tree under "data" otherwise.
1248 * @param filename a string to hold the complete path & filename of an XML file
1249 * @param targetnode a string pointing to a location within the property tree
1250 * where to store the parsed XML file. If <targetnode> is undefined, then the
1251 * file contents are stored under a node <data> in the argument tree.
1255 do_load_xml_to_proptree(const SGPropertyNode * arg)
1257 SGPath file(arg->getStringValue("filename"));
1258 if (file.str().empty())
1261 if (file.extension() != "xml")
1262 file.concat(".xml");
1264 std::string icao = arg->getStringValue("icao");
1266 if (file.isRelative()) {
1267 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1268 if (!absPath.isNull())
1272 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1273 << file.str() << "'.");
1278 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1279 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1280 << file.str() << " at ICAO:" << icao);
1285 if (!fgValidatePath(file.c_str(), false)) {
1286 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1287 "(unauthorized access)");
1291 SGPropertyNode *targetnode;
1292 if (arg->hasValue("targetnode"))
1293 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1295 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1298 readProperties(file.c_str(), targetnode, true);
1299 } catch (const sg_exception &e) {
1300 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1307 class RemoteXMLRequest : public simgear::HTTP::Request
1310 SGPropertyNode_ptr _complete;
1311 SGPropertyNode_ptr _status;
1312 SGPropertyNode_ptr _failed;
1313 SGPropertyNode_ptr _target;
1316 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1317 simgear::HTTP::Request(url),
1322 void setCompletionProp(SGPropertyNode_ptr p)
1327 void setStatusProp(SGPropertyNode_ptr p)
1332 void setFailedProp(SGPropertyNode_ptr p)
1337 virtual void gotBodyData(const char* s, int n)
1339 propsData += string(s, n);
1342 virtual void responseComplete()
1344 int response = responseCode();
1345 bool failed = false;
1346 if (response == 200) {
1348 const char* buffer = propsData.c_str();
1349 readProperties(buffer, propsData.size(), _target, true);
1350 } catch (const sg_exception &e) {
1351 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1353 response = 406; // 'not acceptable', anything better?
1358 // now the response data is output, signal Nasal / listeners
1359 if (_complete) _complete->setBoolValue(true);
1360 if (_status) _status->setIntValue(response);
1361 if (_failed) _failed->setBoolValue(failed);
1367 do_load_xml_from_url(const SGPropertyNode * arg)
1369 std::string url(arg->getStringValue("url"));
1373 SGPropertyNode *targetnode;
1374 if (arg->hasValue("targetnode"))
1375 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1377 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1379 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1381 // connect up optional reporting properties
1382 if (arg->hasValue("complete"))
1383 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1384 if (arg->hasValue("failure"))
1385 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1386 if (arg->hasValue("status"))
1387 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1389 FGHTTPClient::instance()->makeRequest(req);
1396 * An fgcommand to allow saving of xml files via nasal,
1397 * the file's structure will be determined based on what's
1398 * encountered in the passed (source) property tree node
1400 * @param filename a string to hold the complete path & filename of the (new)
1402 * @param sourcenode a string pointing to a location within the property tree
1403 * where to find the nodes that should be written recursively into an XML file
1404 * @param data if no sourcenode is given, then the file contents are taken from
1405 * the argument tree's "data" node.
1409 do_save_xml_from_proptree(const SGPropertyNode * arg)
1411 SGPath file(arg->getStringValue("filename"));
1412 if (file.str().empty())
1415 if (file.extension() != "xml")
1416 file.concat(".xml");
1418 if (!fgValidatePath(file.c_str(), true)) {
1419 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1420 "(unauthorized access)");
1424 SGPropertyNode *sourcenode;
1425 if (arg->hasValue("sourcenode"))
1426 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1427 else if (arg->getNode("data", false))
1428 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1433 writeProperties (file.c_str(), sourcenode, true);
1434 } catch (const sg_exception &e) {
1435 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1443 do_press_cockpit_button (const SGPropertyNode *arg)
1445 const char *prefix = arg->getStringValue("prefix");
1447 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1450 string prop = string(prefix) + "-button";
1453 if (arg->getBoolValue("latching"))
1454 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1458 fgSetDouble(prop.c_str(), value);
1459 fgSetBool(arg->getStringValue("discrete"), value > 0);
1465 do_release_cockpit_button (const SGPropertyNode *arg)
1467 const char *prefix = arg->getStringValue("prefix");
1469 if (arg->getBoolValue("guarded")) {
1470 string prop = string(prefix) + "-guard";
1471 if (fgGetDouble(prop.c_str()) < 1) {
1472 fgSetDouble(prop.c_str(), 1);
1477 if (! arg->getBoolValue("latching")) {
1478 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1479 fgSetBool(arg->getStringValue("discrete"), false);
1485 ////////////////////////////////////////////////////////////////////////
1487 ////////////////////////////////////////////////////////////////////////
1491 * Table of built-in commands.
1493 * New commands do not have to be added here; any module in the application
1494 * can add a new command using globals->get_commands()->addCommand(...).
1498 SGCommandMgr::command_t command;
1500 { "null", do_null },
1501 { "nasal", do_nasal },
1502 { "exit", do_exit },
1503 { "reset", do_reset },
1504 { "reinit", do_reinit },
1505 { "suspend", do_reinit },
1506 { "resume", do_reinit },
1507 { "pause", do_pause },
1508 { "load", do_load },
1509 { "save", do_save },
1510 { "panel-load", do_panel_load },
1511 { "preferences-load", do_preferences_load },
1512 { "view-cycle", do_view_cycle },
1513 { "screen-capture", do_screen_capture },
1514 { "hires-screen-capture", do_hires_screen_capture },
1515 { "tile-cache-reload", do_tile_cache_reload },
1517 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1518 { "set-outside-air-temp-degc", do_set_oat_degc },
1519 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1520 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1522 { "property-toggle", do_property_toggle },
1523 { "property-assign", do_property_assign },
1524 { "property-adjust", do_property_adjust },
1525 { "property-multiply", do_property_multiply },
1526 { "property-swap", do_property_swap },
1527 { "property-scale", do_property_scale },
1528 { "property-cycle", do_property_cycle },
1529 { "property-randomize", do_property_randomize },
1530 { "property-interpolate", do_property_interpolate },
1531 { "data-logging-commit", do_data_logging_commit },
1532 { "dialog-new", do_dialog_new },
1533 { "dialog-show", do_dialog_show },
1534 { "dialog-close", do_dialog_close },
1535 { "dialog-update", do_dialog_update },
1536 { "dialog-apply", do_dialog_apply },
1537 { "open-browser", do_open_browser },
1538 { "gui-redraw", do_gui_redraw },
1539 { "add-model", do_add_model },
1540 { "set-cursor", do_set_cursor },
1541 { "play-audio-sample", do_play_audio_sample },
1542 { "presets-commit", do_presets_commit },
1543 { "log-level", do_log_level },
1544 { "replay", do_replay },
1546 { "decrease-visibility", do_decrease_visibility },
1547 { "increase-visibility", do_increase_visibility },
1549 { "loadxml", do_load_xml_to_proptree},
1550 { "savexml", do_save_xml_from_proptree },
1551 { "xmlhttprequest", do_load_xml_from_url },
1552 { "press-cockpit-button", do_press_cockpit_button },
1553 { "release-cockpit-button", do_release_cockpit_button },
1554 { "dump-scenegraph", do_dump_scene_graph },
1555 { "dump-terrainbranch", do_dump_terrain_branch },
1556 { "print-visible-scene", do_print_visible_scene_info },
1557 { "reload-shaders", do_reload_shaders },
1558 { "reload-materials", do_materials_reload },
1560 { 0, 0 } // zero-terminated
1565 * Initialize the default built-in commands.
1567 * Other commands may be added by other parts of the application.
1572 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1573 for (int i = 0; built_ins[i].name != 0; i++) {
1574 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1575 globals->get_commands()->addCommand(built_ins[i].name,
1576 built_ins[i].command);
1579 typedef bool (*dummy)();
1580 fgTie( "/command/view/next", dummy(0), do_view_next );
1581 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1584 // end of fg_commands.cxx