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);
536 These do_set_(some-environment-parameters) are deprecated and no longer
537 useful/functional - Torsten Dreyer, January 2011
539 * Set the sea level outside air temperature and assigning that to all
540 * boundary and aloft environment layers.
543 do_set_sea_level_degc ( double temp_sea_level_degc)
545 SGPropertyNode *node, *child;
548 node = fgGetNode( "/environment/config/boundary" );
549 if ( node != NULL ) {
551 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
552 child->setDoubleValue( "temperature-sea-level-degc",
553 temp_sea_level_degc );
559 node = fgGetNode( "/environment/config/aloft" );
560 if ( node != NULL ) {
562 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
563 child->setDoubleValue( "temperature-sea-level-degc",
564 temp_sea_level_degc );
573 do_set_sea_level_degc (const SGPropertyNode * arg)
575 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
580 * Set the outside air temperature at the "current" altitude by first
581 * calculating the corresponding sea level temp, and assigning that to
582 * all boundary and aloft environment layers.
585 do_set_oat_degc (const SGPropertyNode * arg)
587 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
588 // check for an altitude specified in the arguments, otherwise use
589 // current aircraft altitude.
590 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
591 if ( altitude_ft == NULL ) {
592 altitude_ft = fgGetNode("/position/altitude-ft");
595 FGEnvironment dummy; // instantiate a dummy so we can leech a method
596 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
597 dummy.set_temperature_degc( oat_degc );
598 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
602 * Set the sea level outside air dewpoint and assigning that to all
603 * boundary and aloft environment layers.
606 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
609 SGPropertyNode *node, *child;
612 node = fgGetNode( "/environment/config/boundary" );
613 if ( node != NULL ) {
615 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
616 child->setDoubleValue( "dewpoint-sea-level-degc",
617 dewpoint_sea_level_degc );
623 node = fgGetNode( "/environment/config/aloft" );
624 if ( node != NULL ) {
626 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
627 child->setDoubleValue( "dewpoint-sea-level-degc",
628 dewpoint_sea_level_degc );
637 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
639 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
643 * Set the outside air dewpoint at the "current" altitude by first
644 * calculating the corresponding sea level dewpoint, and assigning
645 * that to all boundary and aloft environment layers.
648 do_set_dewpoint_degc (const SGPropertyNode * arg)
650 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
652 // check for an altitude specified in the arguments, otherwise use
653 // current aircraft altitude.
654 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
655 if ( altitude_ft == NULL ) {
656 altitude_ft = fgGetNode("/position/altitude-ft");
659 FGEnvironment dummy; // instantiate a dummy so we can leech a method
660 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
661 dummy.set_dewpoint_degc( dewpoint_degc );
662 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
667 * Built-in command: toggle a bool property value.
669 * property: The name of the property to toggle.
672 do_property_toggle (const SGPropertyNode * arg)
674 SGPropertyNode * prop = get_prop(arg);
675 return prop->setBoolValue(!prop->getBoolValue());
680 * Built-in command: assign a value to a property.
682 * property: the name of the property to assign.
683 * value: the value to assign; or
684 * property[1]: the property to copy from.
687 do_property_assign (const SGPropertyNode * arg)
689 SGPropertyNode * prop = get_prop(arg);
690 const SGPropertyNode * value = arg->getNode("value");
693 return prop->setUnspecifiedValue(value->getStringValue());
696 const SGPropertyNode * prop2 = get_prop2(arg);
698 return prop->setUnspecifiedValue(prop2->getStringValue());
706 * Built-in command: increment or decrement a property value.
708 * If the 'step' argument is present, it will be used; otherwise,
709 * the command uses 'offset' and 'factor', usually from the mouse.
711 * property: the name of the property to increment or decrement.
712 * step: the amount of the increment or decrement (default: 0).
713 * offset: offset from the current setting (used for the mouse; multiplied
715 * factor: scaling amount for the offset (defaults to 1).
716 * min: the minimum allowed value (default: no minimum).
717 * max: the maximum allowed value (default: no maximum).
718 * mask: 'integer' to apply only to the left of the decimal point,
719 * 'decimal' to apply only to the right of the decimal point,
720 * or 'all' to apply to the whole number (the default).
721 * wrap: true if the value should be wrapped when it passes min or max;
722 * both min and max must be present for this to work (default:
726 do_property_adjust (const SGPropertyNode * arg)
728 SGPropertyNode * prop = get_prop(arg);
731 if (arg->hasValue("step"))
732 amount = arg->getDoubleValue("step");
734 amount = (arg->getDoubleValue("factor", 1)
735 * arg->getDoubleValue("offset"));
737 double unmodifiable, modifiable;
738 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
739 &unmodifiable, &modifiable);
740 modifiable += amount;
741 limit_value(&modifiable, arg);
743 prop->setDoubleValue(unmodifiable + modifiable);
750 * Built-in command: multiply a property value.
752 * property: the name of the property to multiply.
753 * factor: the amount by which to multiply.
754 * min: the minimum allowed value (default: no minimum).
755 * max: the maximum allowed value (default: no maximum).
756 * mask: 'integer' to apply only to the left of the decimal point,
757 * 'decimal' to apply only to the right of the decimal point,
758 * or 'all' to apply to the whole number (the default).
759 * wrap: true if the value should be wrapped when it passes min or max;
760 * both min and max must be present for this to work (default:
764 do_property_multiply (const SGPropertyNode * arg)
766 SGPropertyNode * prop = get_prop(arg);
767 double factor = arg->getDoubleValue("factor", 1);
769 double unmodifiable, modifiable;
770 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
771 &unmodifiable, &modifiable);
772 modifiable *= factor;
773 limit_value(&modifiable, arg);
775 prop->setDoubleValue(unmodifiable + modifiable);
782 * Built-in command: swap two property values.
784 * property[0]: the name of the first property.
785 * property[1]: the name of the second property.
788 do_property_swap (const SGPropertyNode * arg)
790 SGPropertyNode * prop1 = get_prop(arg);
791 SGPropertyNode * prop2 = get_prop2(arg);
793 // FIXME: inefficient
794 const string & tmp = prop1->getStringValue();
795 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
796 prop2->setUnspecifiedValue(tmp.c_str()));
801 * Built-in command: Set a property to an axis or other moving input.
803 * property: the name of the property to set.
804 * setting: the current input setting, usually between -1.0 and 1.0.
805 * offset: the offset to shift by, before applying the factor.
806 * factor: the factor to multiply by (use negative to reverse).
809 do_property_scale (const SGPropertyNode * arg)
811 SGPropertyNode * prop = get_prop(arg);
812 double setting = arg->getDoubleValue("setting");
813 double offset = arg->getDoubleValue("offset", 0.0);
814 double factor = arg->getDoubleValue("factor", 1.0);
815 bool squared = arg->getBoolValue("squared", false);
816 int power = arg->getIntValue("power", (squared ? 2 : 1));
818 int sign = (setting < 0 ? -1 : 1);
824 setting = setting * setting * sign;
827 setting = setting * setting * setting;
830 setting = setting * setting * setting * setting * sign;
833 setting = pow(setting, power);
834 if ((power % 2) == 0)
839 return prop->setDoubleValue((setting + offset) * factor);
844 * Built-in command: cycle a property through a set of values.
846 * If the current value isn't in the list, the cycle will
847 * (re)start from the beginning.
849 * property: the name of the property to cycle.
850 * value[*]: the list of values to cycle through.
853 do_property_cycle (const SGPropertyNode * arg)
855 SGPropertyNode * prop = get_prop(arg);
856 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
858 int nSelections = values.size();
860 if (nSelections < 1) {
861 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
865 // Try to find the current selection
866 for (int i = 0; i < nSelections; i++) {
867 if (compare_values(prop, values[i])) {
873 // Default or wrap to the first selection
874 if (selection < 0 || selection >= nSelections)
877 prop->setUnspecifiedValue(values[selection]->getStringValue());
883 * Built-in command: randomize a numeric property value.
885 * property: the name of the property value to randomize.
886 * min: the minimum allowed value.
887 * max: the maximum allowed value.
890 do_property_randomize (const SGPropertyNode * arg)
892 SGPropertyNode * prop = get_prop(arg);
893 double min = arg->getDoubleValue("min", DBL_MIN);
894 double max = arg->getDoubleValue("max", DBL_MAX);
895 prop->setDoubleValue(sg_random() * (max - min) + min);
900 * Built-in command: interpolate a property value over time
902 * property: the name of the property value to interpolate.
903 * value[0..n] any number of constant values to interpolate
904 * time[0..n] time between each value, number of time elements must
905 * match those of value elements
907 * property[1..n] any number of target values taken from named properties
908 * time[0..n] time between each value, number of time elements must
909 * match those of property elements minus one
912 do_property_interpolate (const SGPropertyNode * arg)
914 SGPropertyNode * prop = get_prop(arg);
916 simgear::PropertyList valueNodes = arg->getChildren( "value" );
917 simgear::PropertyList timeNodes = arg->getChildren( "time" );
919 boost::scoped_array<double> value;
920 boost::scoped_array<double> time;
922 if( valueNodes.size() > 0 ) {
924 if( timeNodes.size() != valueNodes.size() )
927 value.reset( new double[valueNodes.size()] );
928 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
929 value[n] = valueNodes[n]->getDoubleValue();
932 valueNodes = arg->getChildren("property");
933 // must have one more property node
934 if( valueNodes.size() - 1 != timeNodes.size() )
937 value.reset( new double[valueNodes.size()-1] );
938 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
939 value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
944 time.reset( new double[timeNodes.size()] );
945 for( simgear::PropertyList::size_type n = 0; n < timeNodes.size(); n++ ) {
946 time[n] = timeNodes[n]->getDoubleValue();
949 ((SGInterpolator*)globals->get_subsystem_mgr()
950 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
951 ->interpolate(prop, timeNodes.size(), value.get(), time.get() );
957 * Built-in command: reinit the data logging system based on the
958 * current contents of the /logger tree.
961 do_data_logging_commit (const SGPropertyNode * arg)
963 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
969 * Built-in command: Add a dialog to the GUI system. Does *not*
970 * display the dialog. The property node should have the same format
971 * as a dialog XML configuration. It must include:
973 * name: the name of the GUI dialog for future reference.
976 do_dialog_new (const SGPropertyNode * arg)
978 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
980 // Note the casting away of const: this is *real*. Doing a
981 // "dialog-apply" command later on will mutate this property node.
982 // I'm not convinced that this isn't the Right Thing though; it
983 // allows client to create a node, pass it to dialog-new, and get
984 // the values back from the dialog by reading the same node.
985 // Perhaps command arguments are not as "const" as they would
987 gui->newDialog((SGPropertyNode*)arg);
992 * Built-in command: Show an XML-configured dialog.
994 * dialog-name: the name of the GUI dialog to display.
997 do_dialog_show (const SGPropertyNode * arg)
999 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1000 gui->showDialog(arg->getStringValue("dialog-name"));
1006 * Built-in Command: Hide the active XML-configured dialog.
1009 do_dialog_close (const SGPropertyNode * arg)
1011 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1012 if(arg->hasValue("dialog-name"))
1013 return gui->closeDialog(arg->getStringValue("dialog-name"));
1014 return gui->closeActiveDialog();
1019 * Update a value in the active XML-configured dialog.
1021 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1024 do_dialog_update (const SGPropertyNode * arg)
1026 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1028 if (arg->hasValue("dialog-name"))
1029 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1031 dialog = gui->getActiveDialog();
1034 dialog->updateValues(arg->getStringValue("object-name"));
1042 do_open_browser (const SGPropertyNode * arg)
1045 if (arg->hasValue("path"))
1046 path = arg->getStringValue("path");
1048 if (arg->hasValue("url"))
1049 path = arg->getStringValue("url");
1053 return openBrowser(path);
1057 * Apply a value in the active XML-configured dialog.
1059 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1062 do_dialog_apply (const SGPropertyNode * arg)
1064 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1066 if (arg->hasValue("dialog-name"))
1067 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1069 dialog = gui->getActiveDialog();
1072 dialog->applyValues(arg->getStringValue("object-name"));
1081 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1085 do_gui_redraw (const SGPropertyNode * arg)
1087 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1094 * Adds model to the scenery. The path to the added branch (/models/model[*])
1095 * is returned in property "property".
1098 do_add_model (const SGPropertyNode * arg)
1100 SGPropertyNode * model = fgGetNode("models", true);
1102 for (i = 0; model->hasChild("model",i); i++);
1103 model = model->getChild("model", i, true);
1104 copyProperties(arg, model);
1105 if (model->hasValue("elevation-m"))
1106 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1107 * SG_METER_TO_FEET);
1108 model->getNode("load", true);
1109 model->removeChildren("load");
1110 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1116 * Set mouse cursor coordinates and cursor shape.
1119 do_set_cursor (const SGPropertyNode * arg)
1121 if (arg->hasValue("x") || arg->hasValue("y")) {
1122 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1123 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1124 int x = arg->getIntValue("x", mx->getIntValue());
1125 int y = arg->getIntValue("y", my->getIntValue());
1131 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1132 if (cursor->getType() != simgear::props::NONE)
1133 fgSetMouseCursor(cursor->getIntValue());
1135 cursor->setIntValue(fgGetMouseCursor());
1141 * Built-in command: play an audio message (i.e. a wav file) This is
1142 * fire and forget. Call this once per message and it will get dumped
1143 * into a queue. Messages are played sequentially so they do not
1147 do_play_audio_sample (const SGPropertyNode * arg)
1149 string path = arg->getStringValue("path");
1150 string file = arg->getStringValue("file");
1151 float volume = arg->getFloatValue("volume");
1152 // cout << "playing " << path << " / " << file << endl;
1154 static FGSampleQueue *queue = 0;
1156 SGSoundMgr *smgr = globals->get_soundmgr();
1157 queue = new FGSampleQueue(smgr, "chatter");
1158 queue->tie_to_listener();
1161 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1162 msg->set_volume( volume );
1167 } catch (const sg_io_exception&) {
1168 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1169 "failed to load" << path << '/' << file);
1175 * Built-in command: commit presets (read from in /sim/presets/)
1178 do_presets_commit (const SGPropertyNode * arg)
1180 if (fgGetBool("/sim/initialized", false)) {
1181 fgReInitSubsystems();
1183 // Nasal can trigger this during initial init, which confuses
1184 // the logic in ReInitSubsystems, since initial state has not been
1185 // saved at that time. Short-circuit everything here.
1193 * Built-in command: set log level (0 ... 7)
1196 do_log_level (const SGPropertyNode * arg)
1198 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1205 do_decrease_visibility (const SGPropertyNode * arg)
1207 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1212 do_increase_visibility (const SGPropertyNode * arg)
1214 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1219 * An fgcommand to allow loading of xml files via nasal,
1220 * the xml file's structure will be made available within
1221 * a property tree node defined under argument "targetnode",
1222 * or in the given argument tree under "data" otherwise.
1224 * @param filename a string to hold the complete path & filename of an XML file
1225 * @param targetnode a string pointing to a location within the property tree
1226 * where to store the parsed XML file. If <targetnode> is undefined, then the
1227 * file contents are stored under a node <data> in the argument tree.
1231 do_load_xml_to_proptree(const SGPropertyNode * arg)
1233 SGPath file(arg->getStringValue("filename"));
1234 if (file.str().empty())
1237 if (file.extension() != "xml")
1238 file.concat(".xml");
1240 std::string icao = arg->getStringValue("icao");
1242 if (file.isRelative()) {
1243 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1244 if (!absPath.isNull())
1248 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1249 << file.str() << "'.");
1254 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1255 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1256 << file.str() << " at ICAO:" << icao);
1261 if (!fgValidatePath(file.c_str(), false)) {
1262 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1263 "(unauthorized access)");
1267 SGPropertyNode *targetnode;
1268 if (arg->hasValue("targetnode"))
1269 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1271 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1274 readProperties(file.c_str(), targetnode, true);
1275 } catch (const sg_exception &e) {
1276 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1283 class RemoteXMLRequest : public simgear::HTTP::Request
1286 SGPropertyNode_ptr _complete;
1287 SGPropertyNode_ptr _status;
1288 SGPropertyNode_ptr _failed;
1289 SGPropertyNode_ptr _target;
1292 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1293 simgear::HTTP::Request(url),
1298 void setCompletionProp(SGPropertyNode_ptr p)
1303 void setStatusProp(SGPropertyNode_ptr p)
1308 void setFailedProp(SGPropertyNode_ptr p)
1313 virtual void gotBodyData(const char* s, int n)
1315 propsData += string(s, n);
1318 virtual void responseComplete()
1320 int response = responseCode();
1321 bool failed = false;
1322 if (response == 200) {
1324 const char* buffer = propsData.c_str();
1325 readProperties(buffer, propsData.size(), _target, true);
1326 } catch (const sg_exception &e) {
1327 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1329 response = 406; // 'not acceptable', anything better?
1334 // now the response data is output, signal Nasal / listeners
1335 if (_complete) _complete->setBoolValue(true);
1336 if (_status) _status->setIntValue(response);
1337 if (_failed) _failed->setBoolValue(failed);
1343 do_load_xml_from_url(const SGPropertyNode * arg)
1345 std::string url(arg->getStringValue("url"));
1349 SGPropertyNode *targetnode;
1350 if (arg->hasValue("targetnode"))
1351 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1353 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1355 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1357 // connect up optional reporting properties
1358 if (arg->hasValue("complete"))
1359 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1360 if (arg->hasValue("failure"))
1361 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1362 if (arg->hasValue("status"))
1363 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1365 FGHTTPClient::instance()->makeRequest(req);
1372 * An fgcommand to allow saving of xml files via nasal,
1373 * the file's structure will be determined based on what's
1374 * encountered in the passed (source) property tree node
1376 * @param filename a string to hold the complete path & filename of the (new)
1378 * @param sourcenode a string pointing to a location within the property tree
1379 * where to find the nodes that should be written recursively into an XML file
1380 * @param data if no sourcenode is given, then the file contents are taken from
1381 * the argument tree's "data" node.
1385 do_save_xml_from_proptree(const SGPropertyNode * arg)
1387 SGPath file(arg->getStringValue("filename"));
1388 if (file.str().empty())
1391 if (file.extension() != "xml")
1392 file.concat(".xml");
1394 if (!fgValidatePath(file.c_str(), true)) {
1395 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1396 "(unauthorized access)");
1400 SGPropertyNode *sourcenode;
1401 if (arg->hasValue("sourcenode"))
1402 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1403 else if (arg->getNode("data", false))
1404 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1409 writeProperties (file.c_str(), sourcenode, true);
1410 } catch (const sg_exception &e) {
1411 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1419 do_press_cockpit_button (const SGPropertyNode *arg)
1421 const char *prefix = arg->getStringValue("prefix");
1423 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1426 string prop = string(prefix) + "-button";
1429 if (arg->getBoolValue("latching"))
1430 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1434 fgSetDouble(prop.c_str(), value);
1435 fgSetBool(arg->getStringValue("discrete"), value > 0);
1441 do_release_cockpit_button (const SGPropertyNode *arg)
1443 const char *prefix = arg->getStringValue("prefix");
1445 if (arg->getBoolValue("guarded")) {
1446 string prop = string(prefix) + "-guard";
1447 if (fgGetDouble(prop.c_str()) < 1) {
1448 fgSetDouble(prop.c_str(), 1);
1453 if (! arg->getBoolValue("latching")) {
1454 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1455 fgSetBool(arg->getStringValue("discrete"), false);
1461 ////////////////////////////////////////////////////////////////////////
1463 ////////////////////////////////////////////////////////////////////////
1467 * Table of built-in commands.
1469 * New commands do not have to be added here; any module in the application
1470 * can add a new command using globals->get_commands()->addCommand(...).
1474 SGCommandMgr::command_t command;
1476 { "null", do_null },
1477 { "nasal", do_nasal },
1478 { "exit", do_exit },
1479 { "reset", do_reset },
1480 { "reinit", do_reinit },
1481 { "suspend", do_reinit },
1482 { "resume", do_reinit },
1483 { "pause", do_pause },
1484 { "load", do_load },
1485 { "save", do_save },
1486 { "panel-load", do_panel_load },
1487 { "preferences-load", do_preferences_load },
1488 { "view-cycle", do_view_cycle },
1489 { "screen-capture", do_screen_capture },
1490 { "hires-screen-capture", do_hires_screen_capture },
1491 { "tile-cache-reload", do_tile_cache_reload },
1493 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1494 { "set-outside-air-temp-degc", do_set_oat_degc },
1495 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1496 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1498 { "property-toggle", do_property_toggle },
1499 { "property-assign", do_property_assign },
1500 { "property-adjust", do_property_adjust },
1501 { "property-multiply", do_property_multiply },
1502 { "property-swap", do_property_swap },
1503 { "property-scale", do_property_scale },
1504 { "property-cycle", do_property_cycle },
1505 { "property-randomize", do_property_randomize },
1506 { "property-interpolate", do_property_interpolate },
1507 { "data-logging-commit", do_data_logging_commit },
1508 { "dialog-new", do_dialog_new },
1509 { "dialog-show", do_dialog_show },
1510 { "dialog-close", do_dialog_close },
1511 { "dialog-update", do_dialog_update },
1512 { "dialog-apply", do_dialog_apply },
1513 { "open-browser", do_open_browser },
1514 { "gui-redraw", do_gui_redraw },
1515 { "add-model", do_add_model },
1516 { "set-cursor", do_set_cursor },
1517 { "play-audio-sample", do_play_audio_sample },
1518 { "presets-commit", do_presets_commit },
1519 { "log-level", do_log_level },
1520 { "replay", do_replay },
1522 { "decrease-visibility", do_decrease_visibility },
1523 { "increase-visibility", do_increase_visibility },
1525 { "loadxml", do_load_xml_to_proptree},
1526 { "savexml", do_save_xml_from_proptree },
1527 { "xmlhttprequest", do_load_xml_from_url },
1528 { "press-cockpit-button", do_press_cockpit_button },
1529 { "release-cockpit-button", do_release_cockpit_button },
1530 { "dump-scenegraph", do_dump_scene_graph },
1531 { "dump-terrainbranch", do_dump_terrain_branch },
1532 { "print-visible-scene", do_print_visible_scene_info },
1533 { "reload-shaders", do_reload_shaders },
1535 { 0, 0 } // zero-terminated
1540 * Initialize the default built-in commands.
1542 * Other commands may be added by other parts of the application.
1547 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1548 for (int i = 0; built_ins[i].name != 0; i++) {
1549 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1550 globals->get_commands()->addCommand(built_ins[i].name,
1551 built_ins[i].command);
1554 typedef bool (*dummy)();
1555 fgTie( "/command/view/next", dummy(0), do_view_next );
1556 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1559 // end of fg_commands.cxx