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 <Scenery/tilemgr.hxx>
35 #include <Scripting/NasalSys.hxx>
36 #include <Sound/sample_queue.hxx>
37 #include <Airports/xmlloader.hxx>
38 #include <Network/HTTPClient.hxx>
39 #include <Viewer/viewmgr.hxx>
40 #include <Viewer/viewer.hxx>
41 #include <Environment/presets.hxx>
43 #include "fg_init.hxx"
46 #include "fg_commands.hxx"
47 #include "fg_props.hxx"
48 #include "globals.hxx"
52 #include "positioninit.hxx"
54 #include <boost/scoped_array.hpp>
56 #if FG_HAVE_GPERFTOOLS
57 # include <google/profiler.h>
65 ////////////////////////////////////////////////////////////////////////
66 // Static helper functions.
67 ////////////////////////////////////////////////////////////////////////
70 static inline SGPropertyNode *
71 get_prop (const SGPropertyNode * arg)
73 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
76 static inline SGPropertyNode *
77 get_prop2 (const SGPropertyNode * arg)
79 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
84 * Get a double value and split it as required.
87 split_value (double full_value, const char * mask,
88 double * unmodifiable, double * modifiable)
90 if (!strcmp("integer", mask)) {
91 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
92 *unmodifiable = full_value - *modifiable;
93 } else if (!strcmp("decimal", mask)) {
94 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
95 *modifiable = full_value - *unmodifiable;
97 if (strcmp("all", mask))
98 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
99 << " assuming 'all'");
101 *modifiable = full_value;
107 * Clamp or wrap a value as specified.
110 limit_value (double * value, const SGPropertyNode * arg)
112 const SGPropertyNode * min_node = arg->getChild("min");
113 const SGPropertyNode * max_node = arg->getChild("max");
115 bool wrap = arg->getBoolValue("wrap");
117 if (min_node == 0 || max_node == 0)
120 if (wrap) { // wrap such that min <= x < max
121 double min_val = min_node->getDoubleValue();
122 double max_val = max_node->getDoubleValue();
123 double resolution = arg->getDoubleValue("resolution");
124 if (resolution > 0.0) {
125 // snap to (min + N*resolution), taking special care to handle imprecision
126 int n = (int)floor((*value - min_val) / resolution + 0.5);
127 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
128 SG_NORMALIZE_RANGE(n, 0, steps);
129 *value = min_val + resolution * n;
131 // plain circular wrapping
132 SG_NORMALIZE_RANGE(*value, min_val, max_val);
134 } else { // clamp such that min <= x <= max
135 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
136 *value = min_node->getDoubleValue();
137 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
138 *value = max_node->getDoubleValue();
143 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
145 switch (value1->getType()) {
146 case simgear::props::BOOL:
147 return (value1->getBoolValue() == value2->getBoolValue());
148 case simgear::props::INT:
149 return (value1->getIntValue() == value2->getIntValue());
150 case simgear::props::LONG:
151 return (value1->getLongValue() == value2->getLongValue());
152 case simgear::props::FLOAT:
153 return (value1->getFloatValue() == value2->getFloatValue());
154 case simgear::props::DOUBLE:
155 return (value1->getDoubleValue() == value2->getDoubleValue());
157 return !strcmp(value1->getStringValue(), value2->getStringValue());
163 ////////////////////////////////////////////////////////////////////////
164 // Command implementations.
165 ////////////////////////////////////////////////////////////////////////
169 * Built-in command: do nothing.
172 do_null (const SGPropertyNode * arg)
178 * Built-in command: run a Nasal script.
181 do_nasal (const SGPropertyNode * arg)
183 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
187 * Built-in command: exit FlightGear.
189 * status: the exit status to return to the operating system (defaults to 0)
192 do_exit (const SGPropertyNode * arg)
194 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
195 fgSetBool("/sim/signals/exit", true);
196 globals->saveUserSettings();
197 fgOSExit(arg->getIntValue("status", 0));
203 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
206 do_reset (const SGPropertyNode * arg)
217 do_switch_aircraft (const SGPropertyNode * arg)
219 fgSetString("/sim/aircraft", arg->getStringValue("aircraft"));
228 do_reposition (const SGPropertyNode * arg)
235 * Built-in command: replay the FDR buffer
238 do_replay (const SGPropertyNode * arg)
240 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
245 * Built-in command: pause/unpause the sim
248 do_pause (const SGPropertyNode * arg)
250 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
251 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
257 fgSetBool("/sim/freeze/master",!paused);
258 fgSetBool("/sim/freeze/clock",!paused);
261 SGPropertyNode_ptr args(new SGPropertyNode);
262 args->setStringValue("id", "sim-pause");
263 if (!paused && fgGetBool("/sim/view-name-popup")) {
264 args->setStringValue("label", "Simulation is paused");
265 globals->get_commands()->execute("show-message", args);
267 globals->get_commands()->execute("clear-message", args);
274 * Built-in command: load flight.
276 * file (optional): the name of the file to load (relative to current
277 * directory). Defaults to "fgfs.sav"
280 do_load (const SGPropertyNode * arg)
282 string file = arg->getStringValue("file", "fgfs.sav");
283 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
286 if (!fgValidatePath(file.c_str(), false)) {
287 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
288 "(unauthorized access)");
292 ifstream input(file.c_str());
293 if (input.good() && fgLoadFlight(input)) {
295 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
298 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
305 * Built-in command: save flight.
307 * file (optional): the name of the file to save (relative to the
308 * current directory). Defaults to "fgfs.sav".
311 do_save (const SGPropertyNode * arg)
313 string file = arg->getStringValue("file", "fgfs.sav");
314 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
317 if (!fgValidatePath(file.c_str(), false)) {
318 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
319 "(unauthorized access)");
323 bool write_all = arg->getBoolValue("write-all", false);
324 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
325 ofstream output(file.c_str());
326 if (output.good() && fgSaveFlight(output, write_all)) {
328 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
331 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
337 * Built-in command: save flight recorder tape.
341 do_save_tape (const SGPropertyNode * arg)
343 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
344 replay->saveTape(arg);
349 * Built-in command: load flight recorder tape.
353 do_load_tape (const SGPropertyNode * arg)
355 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
356 replay->loadTape(arg);
362 * Built-in command: (re)load the panel.
364 * path (optional): the file name to load the panel from
365 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
366 * and if that's unspecified, to "Panels/Default/default.xml".
369 do_panel_load (const SGPropertyNode * arg)
371 string panel_path = arg->getStringValue("path");
372 if (!panel_path.empty()) {
373 // write to the standard property, which will force a load
374 fgSetString("/sim/panel/path", panel_path.c_str());
381 * Built-in command: (re)load preferences.
383 * path (optional): the file name to load the panel from (relative
384 * to FG_ROOT). Defaults to "preferences.xml".
387 do_preferences_load (const SGPropertyNode * arg)
390 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
391 globals->get_props());
392 } catch (const sg_exception &e) {
393 guiErrorMessage("Error reading global preferences: ", e);
396 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
401 do_view_next(bool do_it)
403 // Only switch view if really requested to do so (and not for example while
404 // reset/reposition where /command/view/next is set to false)
407 globals->get_current_view()->setHeadingOffset_deg(0.0);
408 globals->get_viewmgr()->next_view();
413 do_view_prev(bool do_it)
417 globals->get_current_view()->setHeadingOffset_deg(0.0);
418 globals->get_viewmgr()->prev_view();
423 * An fgcommand to toggle fullscreen mode.
427 do_toggle_fullscreen(const SGPropertyNode *arg)
434 * Built-in command: cycle view.
437 do_view_cycle (const SGPropertyNode * arg)
439 globals->get_current_view()->setHeadingOffset_deg(0.0);
440 globals->get_viewmgr()->next_view();
445 * Built-in command: capture screen.
448 do_screen_capture (const SGPropertyNode * arg)
450 return fgDumpSnapShot();
454 do_reload_shaders (const SGPropertyNode*)
456 simgear::reload_shaders();
461 do_dump_scene_graph (const SGPropertyNode*)
468 do_dump_terrain_branch (const SGPropertyNode*)
470 fgDumpTerrainBranch();
472 double lon_deg = fgGetDouble("/position/longitude-deg");
473 double lat_deg = fgGetDouble("/position/latitude-deg");
474 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
475 SGVec3d zero = SGVec3d::fromGeod(geodPos);
477 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
478 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
479 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
485 do_print_visible_scene_info(const SGPropertyNode*)
487 fgPrintVisibleSceneInfoCommand();
492 * Built-in command: hires capture screen.
495 do_hires_screen_capture (const SGPropertyNode * arg)
503 * Reload the tile cache.
506 do_tile_cache_reload (const SGPropertyNode * arg)
508 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
509 bool freeze = master_freeze->getBoolValue();
510 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
512 master_freeze->setBoolValue(true);
515 globals->get_subsystem("tile-manager")->reinit();
518 master_freeze->setBoolValue(false);
524 * Reload the materials definition
527 do_materials_reload (const SGPropertyNode * arg)
529 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
530 SGMaterialLib* new_matlib = new SGMaterialLib;
531 SGPath mpath( globals->get_fg_root() );
532 mpath.append( fgGetString("/sim/rendering/materials-file") );
533 bool loaded = new_matlib->load(globals->get_fg_root(),
535 globals->get_props());
538 SG_LOG( SG_GENERAL, SG_ALERT,
539 "Error loading materials file " << mpath.str() );
543 globals->set_matlib(new_matlib);
544 FGTileMgr* tileManager = static_cast<FGTileMgr*>(globals->get_subsystem("tile-manager"));
545 tileManager->materialLibChanged();
551 * Built-in command: toggle a bool property value.
553 * property: The name of the property to toggle.
556 do_property_toggle (const SGPropertyNode * arg)
558 SGPropertyNode * prop = get_prop(arg);
559 return prop->setBoolValue(!prop->getBoolValue());
564 * Built-in command: assign a value to a property.
566 * property: the name of the property to assign.
567 * value: the value to assign; or
568 * property[1]: the property to copy from.
571 do_property_assign (const SGPropertyNode * arg)
573 SGPropertyNode * prop = get_prop(arg);
574 const SGPropertyNode * value = arg->getNode("value");
577 return prop->setUnspecifiedValue(value->getStringValue());
580 const SGPropertyNode * prop2 = get_prop2(arg);
582 return prop->setUnspecifiedValue(prop2->getStringValue());
590 * Built-in command: increment or decrement a property value.
592 * If the 'step' argument is present, it will be used; otherwise,
593 * the command uses 'offset' and 'factor', usually from the mouse.
595 * property: the name of the property to increment or decrement.
596 * step: the amount of the increment or decrement (default: 0).
597 * offset: offset from the current setting (used for the mouse; multiplied
599 * factor: scaling amount for the offset (defaults to 1).
600 * min: the minimum allowed value (default: no minimum).
601 * max: the maximum allowed value (default: no maximum).
602 * mask: 'integer' to apply only to the left of the decimal point,
603 * 'decimal' to apply only to the right of the decimal point,
604 * or 'all' to apply to the whole number (the default).
605 * wrap: true if the value should be wrapped when it passes min or max;
606 * both min and max must be present for this to work (default:
610 do_property_adjust (const SGPropertyNode * arg)
612 SGPropertyNode * prop = get_prop(arg);
615 if (arg->hasValue("step"))
616 amount = arg->getDoubleValue("step");
618 amount = (arg->getDoubleValue("factor", 1)
619 * arg->getDoubleValue("offset"));
621 double unmodifiable, modifiable;
622 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
623 &unmodifiable, &modifiable);
624 modifiable += amount;
625 limit_value(&modifiable, arg);
627 prop->setDoubleValue(unmodifiable + modifiable);
634 * Built-in command: multiply a property value.
636 * property: the name of the property to multiply.
637 * factor: the amount by which to multiply.
638 * min: the minimum allowed value (default: no minimum).
639 * max: the maximum allowed value (default: no maximum).
640 * mask: 'integer' to apply only to the left of the decimal point,
641 * 'decimal' to apply only to the right of the decimal point,
642 * or 'all' to apply to the whole number (the default).
643 * wrap: true if the value should be wrapped when it passes min or max;
644 * both min and max must be present for this to work (default:
648 do_property_multiply (const SGPropertyNode * arg)
650 SGPropertyNode * prop = get_prop(arg);
651 double factor = arg->getDoubleValue("factor", 1);
653 double unmodifiable, modifiable;
654 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
655 &unmodifiable, &modifiable);
656 modifiable *= factor;
657 limit_value(&modifiable, arg);
659 prop->setDoubleValue(unmodifiable + modifiable);
666 * Built-in command: swap two property values.
668 * property[0]: the name of the first property.
669 * property[1]: the name of the second property.
672 do_property_swap (const SGPropertyNode * arg)
674 SGPropertyNode * prop1 = get_prop(arg);
675 SGPropertyNode * prop2 = get_prop2(arg);
677 // FIXME: inefficient
678 const string & tmp = prop1->getStringValue();
679 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
680 prop2->setUnspecifiedValue(tmp.c_str()));
685 * Built-in command: Set a property to an axis or other moving input.
687 * property: the name of the property to set.
688 * setting: the current input setting, usually between -1.0 and 1.0.
689 * offset: the offset to shift by, before applying the factor.
690 * factor: the factor to multiply by (use negative to reverse).
693 do_property_scale (const SGPropertyNode * arg)
695 SGPropertyNode * prop = get_prop(arg);
696 double setting = arg->getDoubleValue("setting");
697 double offset = arg->getDoubleValue("offset", 0.0);
698 double factor = arg->getDoubleValue("factor", 1.0);
699 bool squared = arg->getBoolValue("squared", false);
700 int power = arg->getIntValue("power", (squared ? 2 : 1));
702 int sign = (setting < 0 ? -1 : 1);
708 setting = setting * setting * sign;
711 setting = setting * setting * setting;
714 setting = setting * setting * setting * setting * sign;
717 setting = pow(setting, power);
718 if ((power % 2) == 0)
723 return prop->setDoubleValue((setting + offset) * factor);
728 * Built-in command: cycle a property through a set of values.
730 * If the current value isn't in the list, the cycle will
731 * (re)start from the beginning.
733 * property: the name of the property to cycle.
734 * value[*]: the list of values to cycle through.
737 do_property_cycle (const SGPropertyNode * arg)
739 SGPropertyNode * prop = get_prop(arg);
740 std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
742 bool wrap = arg->getBoolValue("wrap", true);
743 // compatible with knob/pick animations
744 int offset = arg->getIntValue("offset", 1);
747 int nSelections = values.size();
749 if (nSelections < 1) {
750 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
754 // Try to find the current selection
755 for (int i = 0; i < nSelections; i++) {
756 if (compare_values(prop, values[i])) {
762 if (selection < 0) { // default to first selection
767 selection = (selection + nSelections) % nSelections;
769 SG_CLAMP_RANGE(selection, 0, nSelections - 1);
773 prop->setUnspecifiedValue(values[selection]->getStringValue());
779 * Built-in command: randomize a numeric property value.
781 * property: the name of the property value to randomize.
782 * min: the minimum allowed value.
783 * max: the maximum allowed value.
786 do_property_randomize (const SGPropertyNode * arg)
788 SGPropertyNode * prop = get_prop(arg);
789 double min = arg->getDoubleValue("min", DBL_MIN);
790 double max = arg->getDoubleValue("max", DBL_MAX);
791 prop->setDoubleValue(sg_random() * (max - min) + min);
796 * Built-in command: interpolate a property value over time
798 * property: the name of the property value to interpolate.
799 * type: the interpolation type ("numeric", "color", etc.)
800 * easing: name of easing function (see http://easings.net/)
801 * value[0..n] any number of constant values to interpolate
802 * time/rate[0..n] time between each value, number of time elements must
803 * match those of value elements. Instead of time also rate can
804 * be used which automatically calculates the time to change
805 * the property value at the given speed.
807 * property[1..n+1] any number of target values taken from named properties
808 * time/rate[0..n] time between each value, number of time elements must
809 * match those of value elements. Instead of time also rate can
810 * be used which automatically calculates the time to change
811 * the property value at the given speed.
814 do_property_interpolate (const SGPropertyNode * arg)
816 SGPropertyNode * prop = get_prop(arg);
820 simgear::PropertyList time_nodes = arg->getChildren("time");
821 simgear::PropertyList rate_nodes = arg->getChildren("rate");
823 if( !time_nodes.empty() && !rate_nodes.empty() )
824 // mustn't specify time and rate
827 simgear::PropertyList::size_type num_times = time_nodes.empty()
831 simgear::PropertyList value_nodes = arg->getChildren("value");
832 if( value_nodes.empty() )
834 simgear::PropertyList prop_nodes = arg->getChildren("property");
836 // must have one more property node
837 if( prop_nodes.size() != num_times + 1 )
840 value_nodes.reserve(num_times);
841 for( size_t i = 1; i < prop_nodes.size(); ++i )
842 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
846 if( value_nodes.size() != num_times )
850 deltas.reserve(num_times);
852 if( !time_nodes.empty() )
854 for( size_t i = 0; i < num_times; ++i )
855 deltas.push_back( time_nodes[i]->getDoubleValue() );
859 for( size_t i = 0; i < num_times; ++i )
861 // TODO calculate delta based on property type
862 double delta = value_nodes[i]->getDoubleValue()
864 ? value_nodes[i - 1]->getDoubleValue()
865 : prop->getDoubleValue()
867 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
871 return prop->interpolate
873 arg->getStringValue("type", "numeric"),
876 arg->getStringValue("easing", "linear")
881 * Built-in command: reinit the data logging system based on the
882 * current contents of the /logger tree.
885 do_data_logging_commit (const SGPropertyNode * arg)
887 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
893 * Built-in command: Add a dialog to the GUI system. Does *not*
894 * display the dialog. The property node should have the same format
895 * as a dialog XML configuration. It must include:
897 * name: the name of the GUI dialog for future reference.
900 do_dialog_new (const SGPropertyNode * arg)
902 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
907 // Note the casting away of const: this is *real*. Doing a
908 // "dialog-apply" command later on will mutate this property node.
909 // I'm not convinced that this isn't the Right Thing though; it
910 // allows client to create a node, pass it to dialog-new, and get
911 // the values back from the dialog by reading the same node.
912 // Perhaps command arguments are not as "const" as they would
914 gui->newDialog((SGPropertyNode*)arg);
919 * Built-in command: Show an XML-configured dialog.
921 * dialog-name: the name of the GUI dialog to display.
924 do_dialog_show (const SGPropertyNode * arg)
926 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
927 gui->showDialog(arg->getStringValue("dialog-name"));
933 * Built-in Command: Hide the active XML-configured dialog.
936 do_dialog_close (const SGPropertyNode * arg)
938 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
939 if(arg->hasValue("dialog-name"))
940 return gui->closeDialog(arg->getStringValue("dialog-name"));
941 return gui->closeActiveDialog();
946 * Update a value in the active XML-configured dialog.
948 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
951 do_dialog_update (const SGPropertyNode * arg)
953 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
955 if (arg->hasValue("dialog-name"))
956 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
958 dialog = gui->getActiveDialog();
961 dialog->updateValues(arg->getStringValue("object-name"));
969 do_open_browser (const SGPropertyNode * arg)
972 if (arg->hasValue("path"))
973 path = arg->getStringValue("path");
975 if (arg->hasValue("url"))
976 path = arg->getStringValue("url");
980 return openBrowser(path);
984 * Apply a value in the active XML-configured dialog.
986 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
989 do_dialog_apply (const SGPropertyNode * arg)
991 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
993 if (arg->hasValue("dialog-name"))
994 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
996 dialog = gui->getActiveDialog();
999 dialog->applyValues(arg->getStringValue("object-name"));
1008 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1012 do_gui_redraw (const SGPropertyNode * arg)
1014 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1021 * Adds model to the scenery. The path to the added branch (/models/model[*])
1022 * is returned in property "property".
1025 do_add_model (const SGPropertyNode * arg)
1027 SGPropertyNode * model = fgGetNode("models", true);
1029 for (i = 0; model->hasChild("model",i); i++);
1030 model = model->getChild("model", i, true);
1031 copyProperties(arg, model);
1032 if (model->hasValue("elevation-m"))
1033 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1034 * SG_METER_TO_FEET);
1035 model->getNode("load", true);
1036 model->removeChildren("load");
1037 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1042 * Built-in command: play an audio message (i.e. a wav file) This is
1043 * fire and forget. Call this once per message and it will get dumped
1044 * into a queue. Messages are played sequentially so they do not
1048 do_play_audio_sample (const SGPropertyNode * arg)
1050 SGSoundMgr *smgr = globals->get_soundmgr();
1052 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1056 string path = arg->getStringValue("path");
1057 string file = arg->getStringValue("file");
1058 float volume = arg->getFloatValue("volume");
1059 // cout << "playing " << path << " / " << file << endl;
1061 FGSampleQueue *queue = globals->get_chatter_queue();
1063 queue = new FGSampleQueue(smgr, "chatter");
1064 queue->tie_to_listener();
1065 globals->set_chatter_queue(queue);
1068 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1069 msg->set_volume( volume );
1074 } catch (const sg_io_exception&) {
1075 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1076 "failed to load" << path << '/' << file);
1082 * Built-in command: commit presets (read from in /sim/presets/)
1085 do_presets_commit (const SGPropertyNode * arg)
1087 if (fgGetBool("/sim/initialized", false)) {
1090 // Nasal can trigger this during initial init, which confuses
1091 // the logic in ReInitSubsystems, since initial state has not been
1092 // saved at that time. Short-circuit everything here.
1093 flightgear::initPosition();
1100 * Built-in command: set log level (0 ... 7)
1103 do_log_level (const SGPropertyNode * arg)
1105 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1112 do_decrease_visibility (const SGPropertyNode * arg)
1114 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1119 do_increase_visibility (const SGPropertyNode * arg)
1121 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1126 * An fgcommand to allow loading of xml files via nasal,
1127 * the xml file's structure will be made available within
1128 * a property tree node defined under argument "targetnode",
1129 * or in the given argument tree under "data" otherwise.
1131 * @param filename a string to hold the complete path & filename of an XML file
1132 * @param targetnode a string pointing to a location within the property tree
1133 * where to store the parsed XML file. If <targetnode> is undefined, then the
1134 * file contents are stored under a node <data> in the argument tree.
1138 do_load_xml_to_proptree(const SGPropertyNode * arg)
1140 SGPath file(arg->getStringValue("filename"));
1141 if (file.str().empty())
1144 if (file.extension() != "xml")
1145 file.concat(".xml");
1147 std::string icao = arg->getStringValue("icao");
1149 if (file.isRelative()) {
1150 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1151 if (!absPath.isNull())
1155 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1156 << file.str() << "'.");
1161 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1162 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1163 << file.str() << " at ICAO:" << icao);
1168 if (!fgValidatePath(file.c_str(), false)) {
1169 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1170 "(unauthorized access)");
1174 SGPropertyNode *targetnode;
1175 if (arg->hasValue("targetnode"))
1176 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1178 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1181 readProperties(file.c_str(), targetnode, true);
1182 } catch (const sg_exception &e) {
1183 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1190 class RemoteXMLRequest:
1191 public simgear::HTTP::MemoryRequest
1194 SGPropertyNode_ptr _complete;
1195 SGPropertyNode_ptr _status;
1196 SGPropertyNode_ptr _failed;
1197 SGPropertyNode_ptr _target;
1199 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1200 simgear::HTTP::MemoryRequest(url),
1205 void setCompletionProp(SGPropertyNode_ptr p)
1210 void setStatusProp(SGPropertyNode_ptr p)
1215 void setFailedProp(SGPropertyNode_ptr p)
1222 virtual void onFail()
1224 SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1226 _failed->setBoolValue(true);
1230 virtual void onDone()
1232 int response = responseCode();
1233 bool failed = false;
1234 if (response == 200) {
1236 const char* buffer = responseBody().c_str();
1237 readProperties(buffer, responseBody().size(), _target, true);
1238 } catch (const sg_exception &e) {
1239 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1241 response = 406; // 'not acceptable', anything better?
1246 // now the response data is output, signal Nasal / listeners
1247 if (_complete) _complete->setBoolValue(true);
1248 if (_status) _status->setIntValue(response);
1249 if (_failed && failed) _failed->setBoolValue(true);
1255 do_load_xml_from_url(const SGPropertyNode * arg)
1257 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1259 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1263 std::string url(arg->getStringValue("url"));
1267 SGPropertyNode *targetnode;
1268 if (arg->hasValue("targetnode"))
1269 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1271 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1273 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1275 if (arg->hasChild("body"))
1276 req->setBodyData(arg->getChild("body"));
1278 // connect up optional reporting properties
1279 if (arg->hasValue("complete"))
1280 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1281 if (arg->hasValue("failure"))
1282 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1283 if (arg->hasValue("status"))
1284 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1286 http->makeRequest(req);
1292 * An fgcommand to allow saving of xml files via nasal,
1293 * the file's structure will be determined based on what's
1294 * encountered in the passed (source) property tree node
1296 * @param filename a string to hold the complete path & filename of the (new)
1298 * @param sourcenode a string pointing to a location within the property tree
1299 * where to find the nodes that should be written recursively into an XML file
1300 * @param data if no sourcenode is given, then the file contents are taken from
1301 * the argument tree's "data" node.
1305 do_save_xml_from_proptree(const SGPropertyNode * arg)
1307 SGPath file(arg->getStringValue("filename"));
1308 if (file.str().empty())
1311 if (file.extension() != "xml")
1312 file.concat(".xml");
1314 if (!fgValidatePath(file.c_str(), true)) {
1315 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1316 "(unauthorized access)");
1320 SGPropertyNode *sourcenode;
1321 if (arg->hasValue("sourcenode"))
1322 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1323 else if (arg->getNode("data", false))
1324 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1329 writeProperties (file.c_str(), sourcenode, true);
1330 } catch (const sg_exception &e) {
1331 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1339 do_press_cockpit_button (const SGPropertyNode *arg)
1341 const char *prefix = arg->getStringValue("prefix");
1343 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1346 string prop = string(prefix) + "-button";
1349 if (arg->getBoolValue("latching"))
1350 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1354 fgSetDouble(prop.c_str(), value);
1355 fgSetBool(arg->getStringValue("discrete"), value > 0);
1361 do_release_cockpit_button (const SGPropertyNode *arg)
1363 const char *prefix = arg->getStringValue("prefix");
1365 if (arg->getBoolValue("guarded")) {
1366 string prop = string(prefix) + "-guard";
1367 if (fgGetDouble(prop.c_str()) < 1) {
1368 fgSetDouble(prop.c_str(), 1);
1373 if (! arg->getBoolValue("latching")) {
1374 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1375 fgSetBool(arg->getStringValue("discrete"), false);
1381 // Optional profiling commands using gperftools:
1382 // http://code.google.com/p/gperftools/
1384 #if !FG_HAVE_GPERFTOOLS
1386 no_profiling_support()
1392 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1398 do_profiler_start(const SGPropertyNode *arg)
1400 #if FG_HAVE_GPERFTOOLS
1401 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1402 ProfilerStart(filename);
1405 no_profiling_support();
1411 do_profiler_stop(const SGPropertyNode *arg)
1413 #if FG_HAVE_GPERFTOOLS
1417 no_profiling_support();
1424 do_set_scenery_paths(const SGPropertyNode* arg)
1426 SGPropertyNode* sim = fgGetNode("/sim", true);
1427 sim->removeChildren("fg-scenery");
1429 globals->clear_fg_scenery();
1431 std::string terrasyncPath(fgGetString("/sim/terrasync/scenery-dir"));
1432 bool seenTerrasyncPath = false;
1434 simgear::PropertyList paths = arg->getChildren("path");
1435 for (size_t i = 0; i < paths.size(); ++i) {
1436 std::string s = paths[i]->getStringValue();
1437 if (s == terrasyncPath) {
1438 seenTerrasyncPath = true;
1441 globals->append_fg_scenery(s);
1444 if (fgGetBool("/sim/terrasync/enabled") && !seenTerrasyncPath) {
1445 globals->append_fg_scenery(terrasyncPath);
1448 if (paths.empty()) {
1449 // no scenery paths set *at all*, use the data in FG_ROOT
1450 SGPath root(globals->get_fg_root());
1451 root.append("Scenery");
1452 globals->append_fg_scenery(root.str());
1458 ////////////////////////////////////////////////////////////////////////
1460 ////////////////////////////////////////////////////////////////////////
1464 * Table of built-in commands.
1466 * New commands do not have to be added here; any module in the application
1467 * can add a new command using globals->get_commands()->addCommand(...).
1471 SGCommandMgr::command_t command;
1473 { "null", do_null },
1474 { "nasal", do_nasal },
1475 { "exit", do_exit },
1476 { "reset", do_reset },
1477 { "reposition", do_reposition },
1478 { "switch-aircraft", do_switch_aircraft },
1479 { "pause", do_pause },
1480 { "load", do_load },
1481 { "save", do_save },
1482 { "save-tape", do_save_tape },
1483 { "load-tape", do_load_tape },
1484 { "panel-load", do_panel_load },
1485 { "preferences-load", do_preferences_load },
1486 { "toggle-fullscreen", do_toggle_fullscreen },
1487 { "view-cycle", do_view_cycle },
1488 { "screen-capture", do_screen_capture },
1489 { "hires-screen-capture", do_hires_screen_capture },
1490 { "tile-cache-reload", do_tile_cache_reload },
1492 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1493 { "set-outside-air-temp-degc", do_set_oat_degc },
1494 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1495 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1497 { "property-toggle", do_property_toggle },
1498 { "property-assign", do_property_assign },
1499 { "property-adjust", do_property_adjust },
1500 { "property-multiply", do_property_multiply },
1501 { "property-swap", do_property_swap },
1502 { "property-scale", do_property_scale },
1503 { "property-cycle", do_property_cycle },
1504 { "property-randomize", do_property_randomize },
1505 { "property-interpolate", do_property_interpolate },
1506 { "data-logging-commit", do_data_logging_commit },
1507 { "dialog-new", do_dialog_new },
1508 { "dialog-show", do_dialog_show },
1509 { "dialog-close", do_dialog_close },
1510 { "dialog-update", do_dialog_update },
1511 { "dialog-apply", do_dialog_apply },
1512 { "open-browser", do_open_browser },
1513 { "gui-redraw", do_gui_redraw },
1514 { "add-model", do_add_model },
1515 { "play-audio-sample", do_play_audio_sample },
1516 { "presets-commit", do_presets_commit },
1517 { "log-level", do_log_level },
1518 { "replay", do_replay },
1520 { "decrease-visibility", do_decrease_visibility },
1521 { "increase-visibility", do_increase_visibility },
1523 { "loadxml", do_load_xml_to_proptree},
1524 { "savexml", do_save_xml_from_proptree },
1525 { "xmlhttprequest", do_load_xml_from_url },
1526 { "press-cockpit-button", do_press_cockpit_button },
1527 { "release-cockpit-button", do_release_cockpit_button },
1528 { "dump-scenegraph", do_dump_scene_graph },
1529 { "dump-terrainbranch", do_dump_terrain_branch },
1530 { "print-visible-scene", do_print_visible_scene_info },
1531 { "reload-shaders", do_reload_shaders },
1532 { "reload-materials", do_materials_reload },
1533 { "set-scenery-paths", do_set_scenery_paths },
1535 { "profiler-start", do_profiler_start },
1536 { "profiler-stop", do_profiler_stop },
1538 { 0, 0 } // zero-terminated
1543 * Initialize the default built-in commands.
1545 * Other commands may be added by other parts of the application.
1550 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1551 for (int i = 0; built_ins[i].name != 0; i++) {
1552 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1553 globals->get_commands()->addCommand(built_ins[i].name,
1554 built_ins[i].command);
1557 typedef bool (*dummy)();
1558 fgTie( "/command/view/next", dummy(0), do_view_next );
1559 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1561 globals->get_props()->setValueReadOnly( "/sim/debug/profiler-available",
1562 bool(FG_HAVE_GPERFTOOLS) );
1565 // end of fg_commands.cxx