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 <Network/RemoteXMLRequest.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>
42 #include <Navaids/NavDataCache.hxx>
44 #include "fg_init.hxx"
47 #include "fg_commands.hxx"
48 #include "fg_props.hxx"
49 #include "globals.hxx"
53 #include "positioninit.hxx"
55 #include <boost/scoped_array.hpp>
57 #if FG_HAVE_GPERFTOOLS
58 # include <google/profiler.h>
66 ////////////////////////////////////////////////////////////////////////
67 // Static helper functions.
68 ////////////////////////////////////////////////////////////////////////
71 static inline SGPropertyNode *
72 get_prop (const SGPropertyNode * arg)
74 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
77 static inline SGPropertyNode *
78 get_prop2 (const SGPropertyNode * arg)
80 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
85 * Get a double value and split it as required.
88 split_value (double full_value, const char * mask,
89 double * unmodifiable, double * modifiable)
91 if (!strcmp("integer", mask)) {
92 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
93 *unmodifiable = full_value - *modifiable;
94 } else if (!strcmp("decimal", mask)) {
95 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
96 *modifiable = full_value - *unmodifiable;
98 if (strcmp("all", mask))
99 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
100 << " assuming 'all'");
102 *modifiable = full_value;
108 * Clamp or wrap a value as specified.
111 limit_value (double * value, const SGPropertyNode * arg)
113 const SGPropertyNode * min_node = arg->getChild("min");
114 const SGPropertyNode * max_node = arg->getChild("max");
116 bool wrap = arg->getBoolValue("wrap");
118 if (min_node == 0 || max_node == 0)
121 if (wrap) { // wrap such that min <= x < max
122 double min_val = min_node->getDoubleValue();
123 double max_val = max_node->getDoubleValue();
124 double resolution = arg->getDoubleValue("resolution");
125 if (resolution > 0.0) {
126 // snap to (min + N*resolution), taking special care to handle imprecision
127 int n = (int)floor((*value - min_val) / resolution + 0.5);
128 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
129 SG_NORMALIZE_RANGE(n, 0, steps);
130 *value = min_val + resolution * n;
132 // plain circular wrapping
133 SG_NORMALIZE_RANGE(*value, min_val, max_val);
135 } else { // clamp such that min <= x <= max
136 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
137 *value = min_node->getDoubleValue();
138 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
139 *value = max_node->getDoubleValue();
144 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
146 switch (value1->getType()) {
147 case simgear::props::BOOL:
148 return (value1->getBoolValue() == value2->getBoolValue());
149 case simgear::props::INT:
150 return (value1->getIntValue() == value2->getIntValue());
151 case simgear::props::LONG:
152 return (value1->getLongValue() == value2->getLongValue());
153 case simgear::props::FLOAT:
154 return (value1->getFloatValue() == value2->getFloatValue());
155 case simgear::props::DOUBLE:
156 return (value1->getDoubleValue() == value2->getDoubleValue());
158 return !strcmp(value1->getStringValue(), value2->getStringValue());
164 ////////////////////////////////////////////////////////////////////////
165 // Command implementations.
166 ////////////////////////////////////////////////////////////////////////
170 * Built-in command: do nothing.
173 do_null (const SGPropertyNode * arg)
179 * Built-in command: run a Nasal script.
182 do_nasal (const SGPropertyNode * arg)
184 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
188 * Built-in command: exit FlightGear.
190 * status: the exit status to return to the operating system (defaults to 0)
193 do_exit (const SGPropertyNode * arg)
195 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
196 fgSetBool("/sim/signals/exit", true);
197 globals->saveUserSettings();
198 fgOSExit(arg->getIntValue("status", 0));
204 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
207 do_reset (const SGPropertyNode * arg)
218 do_switch_aircraft (const SGPropertyNode * arg)
220 fgSetString("/sim/aircraft", arg->getStringValue("aircraft"));
229 do_reposition (const SGPropertyNode * arg)
236 * Built-in command: replay the FDR buffer
239 do_replay (const SGPropertyNode * arg)
241 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
246 * Built-in command: pause/unpause the sim
249 do_pause (const SGPropertyNode * arg)
251 bool forcePause = arg->getBoolValue("force-pause", false );
252 bool forcePlay = arg->getBoolValue("force-play", false );
254 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
256 if(forcePause) paused = false;
257 if(forcePlay) paused = true;
259 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
265 fgSetBool("/sim/freeze/master",!paused);
266 fgSetBool("/sim/freeze/clock",!paused);
269 SGPropertyNode_ptr args(new SGPropertyNode);
270 args->setStringValue("id", "sim-pause");
271 if (!paused && fgGetBool("/sim/view-name-popup")) {
272 args->setStringValue("label", "Simulation is paused");
273 globals->get_commands()->execute("show-message", args);
275 globals->get_commands()->execute("clear-message", args);
282 * Built-in command: load flight.
284 * file (optional): the name of the file to load (relative to current
285 * directory). Defaults to "fgfs.sav"
288 do_load (const SGPropertyNode * arg)
290 string file = arg->getStringValue("file", "fgfs.sav");
291 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
294 if (fgValidatePath(file, false).empty()) {
295 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
296 "(unauthorized access)");
300 ifstream input(file.c_str());
301 if (input.good() && fgLoadFlight(input)) {
303 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
306 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
313 * Built-in command: save flight.
315 * file (optional): the name of the file to save (relative to the
316 * current directory). Defaults to "fgfs.sav".
319 do_save (const SGPropertyNode * arg)
321 string file = arg->getStringValue("file", "fgfs.sav");
322 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
325 if (fgValidatePath(file, false).empty()) {
326 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
327 "(unauthorized access)");
331 bool write_all = arg->getBoolValue("write-all", false);
332 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
333 ofstream output(file.c_str());
334 if (output.good() && fgSaveFlight(output, write_all)) {
336 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
339 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
345 * Built-in command: save flight recorder tape.
349 do_save_tape (const SGPropertyNode * arg)
351 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
352 replay->saveTape(arg);
357 * Built-in command: load flight recorder tape.
361 do_load_tape (const SGPropertyNode * arg)
363 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
364 replay->loadTape(arg);
370 * Built-in command: (re)load the panel.
372 * path (optional): the file name to load the panel from
373 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
374 * and if that's unspecified, to "Panels/Default/default.xml".
377 do_panel_load (const SGPropertyNode * arg)
379 string panel_path = arg->getStringValue("path");
380 if (!panel_path.empty()) {
381 // write to the standard property, which will force a load
382 fgSetString("/sim/panel/path", panel_path.c_str());
389 * Built-in command: (re)load preferences.
391 * path (optional): the file name to load the panel from (relative
392 * to FG_ROOT). Defaults to "preferences.xml".
395 do_preferences_load (const SGPropertyNode * arg)
398 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
399 globals->get_props());
400 } catch (const sg_exception &e) {
401 guiErrorMessage("Error reading global preferences: ", e);
404 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
409 do_view_next(bool do_it)
411 // Only switch view if really requested to do so (and not for example while
412 // reset/reposition where /command/view/next is set to false)
415 globals->get_current_view()->setHeadingOffset_deg(0.0);
416 globals->get_viewmgr()->next_view();
421 do_view_prev(bool do_it)
425 globals->get_current_view()->setHeadingOffset_deg(0.0);
426 globals->get_viewmgr()->prev_view();
431 * An fgcommand to toggle fullscreen mode.
435 do_toggle_fullscreen(const SGPropertyNode *arg)
442 * Built-in command: cycle view.
445 do_view_cycle (const SGPropertyNode * arg)
447 globals->get_current_view()->setHeadingOffset_deg(0.0);
448 globals->get_viewmgr()->next_view();
453 * Built-in command: capture screen.
456 do_screen_capture (const SGPropertyNode * arg)
458 return fgDumpSnapShot();
462 do_reload_shaders (const SGPropertyNode*)
464 simgear::reload_shaders();
469 do_dump_scene_graph (const SGPropertyNode*)
476 do_dump_terrain_branch (const SGPropertyNode*)
478 fgDumpTerrainBranch();
480 double lon_deg = fgGetDouble("/position/longitude-deg");
481 double lat_deg = fgGetDouble("/position/latitude-deg");
482 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
483 SGVec3d zero = SGVec3d::fromGeod(geodPos);
485 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
486 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
487 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
493 do_print_visible_scene_info(const SGPropertyNode*)
495 fgPrintVisibleSceneInfoCommand();
500 * Built-in command: hires capture screen.
503 do_hires_screen_capture (const SGPropertyNode * arg)
511 * Reload the tile cache.
514 do_tile_cache_reload (const SGPropertyNode * arg)
516 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
517 bool freeze = master_freeze->getBoolValue();
518 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
520 master_freeze->setBoolValue(true);
523 globals->get_subsystem("tile-manager")->reinit();
526 master_freeze->setBoolValue(false);
532 * Reload the materials definition
535 do_materials_reload (const SGPropertyNode * arg)
537 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
538 SGMaterialLib* new_matlib = new SGMaterialLib;
539 SGPath mpath( globals->get_fg_root() );
540 mpath.append( fgGetString("/sim/rendering/materials-file") );
541 bool loaded = new_matlib->load(globals->get_fg_root(),
543 globals->get_props());
546 SG_LOG( SG_GENERAL, SG_ALERT,
547 "Error loading materials file " << mpath.str() );
551 globals->set_matlib(new_matlib);
552 FGTileMgr* tileManager = static_cast<FGTileMgr*>(globals->get_subsystem("tile-manager"));
553 tileManager->materialLibChanged();
559 * Built-in command: toggle a bool property value.
561 * property: The name of the property to toggle.
564 do_property_toggle (const SGPropertyNode * arg)
566 SGPropertyNode * prop = get_prop(arg);
567 return prop->setBoolValue(!prop->getBoolValue());
572 * Built-in command: assign a value to a property.
574 * property: the name of the property to assign.
575 * value: the value to assign; or
576 * property[1]: the property to copy from.
579 do_property_assign (const SGPropertyNode * arg)
581 SGPropertyNode * prop = get_prop(arg);
582 const SGPropertyNode * value = arg->getNode("value");
585 return prop->setUnspecifiedValue(value->getStringValue());
588 const SGPropertyNode * prop2 = get_prop2(arg);
590 return prop->setUnspecifiedValue(prop2->getStringValue());
598 * Built-in command: increment or decrement a property value.
600 * If the 'step' argument is present, it will be used; otherwise,
601 * the command uses 'offset' and 'factor', usually from the mouse.
603 * property: the name of the property to increment or decrement.
604 * step: the amount of the increment or decrement (default: 0).
605 * offset: offset from the current setting (used for the mouse; multiplied
607 * factor: scaling amount for the offset (defaults to 1).
608 * min: the minimum allowed value (default: no minimum).
609 * max: the maximum allowed value (default: no maximum).
610 * mask: 'integer' to apply only to the left of the decimal point,
611 * 'decimal' to apply only to the right of the decimal point,
612 * or 'all' to apply to the whole number (the default).
613 * wrap: true if the value should be wrapped when it passes min or max;
614 * both min and max must be present for this to work (default:
618 do_property_adjust (const SGPropertyNode * arg)
620 SGPropertyNode * prop = get_prop(arg);
623 if (arg->hasValue("step"))
624 amount = arg->getDoubleValue("step");
626 amount = (arg->getDoubleValue("factor", 1)
627 * arg->getDoubleValue("offset"));
629 double unmodifiable, modifiable;
630 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
631 &unmodifiable, &modifiable);
632 modifiable += amount;
633 limit_value(&modifiable, arg);
635 prop->setDoubleValue(unmodifiable + modifiable);
642 * Built-in command: multiply a property value.
644 * property: the name of the property to multiply.
645 * factor: the amount by which to multiply.
646 * min: the minimum allowed value (default: no minimum).
647 * max: the maximum allowed value (default: no maximum).
648 * mask: 'integer' to apply only to the left of the decimal point,
649 * 'decimal' to apply only to the right of the decimal point,
650 * or 'all' to apply to the whole number (the default).
651 * wrap: true if the value should be wrapped when it passes min or max;
652 * both min and max must be present for this to work (default:
656 do_property_multiply (const SGPropertyNode * arg)
658 SGPropertyNode * prop = get_prop(arg);
659 double factor = arg->getDoubleValue("factor", 1);
661 double unmodifiable, modifiable;
662 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
663 &unmodifiable, &modifiable);
664 modifiable *= factor;
665 limit_value(&modifiable, arg);
667 prop->setDoubleValue(unmodifiable + modifiable);
674 * Built-in command: swap two property values.
676 * property[0]: the name of the first property.
677 * property[1]: the name of the second property.
680 do_property_swap (const SGPropertyNode * arg)
682 SGPropertyNode * prop1 = get_prop(arg);
683 SGPropertyNode * prop2 = get_prop2(arg);
685 // FIXME: inefficient
686 const string & tmp = prop1->getStringValue();
687 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
688 prop2->setUnspecifiedValue(tmp.c_str()));
693 * Built-in command: Set a property to an axis or other moving input.
695 * property: the name of the property to set.
696 * setting: the current input setting, usually between -1.0 and 1.0.
697 * offset: the offset to shift by, before applying the factor.
698 * factor: the factor to multiply by (use negative to reverse).
701 do_property_scale (const SGPropertyNode * arg)
703 SGPropertyNode * prop = get_prop(arg);
704 double setting = arg->getDoubleValue("setting");
705 double offset = arg->getDoubleValue("offset", 0.0);
706 double factor = arg->getDoubleValue("factor", 1.0);
707 bool squared = arg->getBoolValue("squared", false);
708 int power = arg->getIntValue("power", (squared ? 2 : 1));
710 int sign = (setting < 0 ? -1 : 1);
716 setting = setting * setting * sign;
719 setting = setting * setting * setting;
722 setting = setting * setting * setting * setting * sign;
725 setting = pow(setting, power);
726 if ((power % 2) == 0)
731 return prop->setDoubleValue((setting + offset) * factor);
736 * Built-in command: cycle a property through a set of values.
738 * If the current value isn't in the list, the cycle will
739 * (re)start from the beginning.
741 * property: the name of the property to cycle.
742 * value[*]: the list of values to cycle through.
745 do_property_cycle (const SGPropertyNode * arg)
747 SGPropertyNode * prop = get_prop(arg);
748 std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
750 bool wrap = arg->getBoolValue("wrap", true);
751 // compatible with knob/pick animations
752 int offset = arg->getIntValue("offset", 1);
755 int nSelections = values.size();
757 if (nSelections < 1) {
758 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
762 // Try to find the current selection
763 for (int i = 0; i < nSelections; i++) {
764 if (compare_values(prop, values[i])) {
770 if (selection < 0) { // default to first selection
775 selection = (selection + nSelections) % nSelections;
777 SG_CLAMP_RANGE(selection, 0, nSelections - 1);
781 prop->setUnspecifiedValue(values[selection]->getStringValue());
787 * Built-in command: randomize a numeric property value.
789 * property: the name of the property value to randomize.
790 * min: the minimum allowed value.
791 * max: the maximum allowed value.
794 do_property_randomize (const SGPropertyNode * arg)
796 SGPropertyNode * prop = get_prop(arg);
797 double min = arg->getDoubleValue("min", DBL_MIN);
798 double max = arg->getDoubleValue("max", DBL_MAX);
799 prop->setDoubleValue(sg_random() * (max - min) + min);
804 * Built-in command: interpolate a property value over time
806 * property: the name of the property value to interpolate.
807 * type: the interpolation type ("numeric", "color", etc.)
808 * easing: name of easing function (see http://easings.net/)
809 * value[0..n] any number of constant values to interpolate
810 * time/rate[0..n] time between each value, number of time elements must
811 * match those of value elements. Instead of time also rate can
812 * be used which automatically calculates the time to change
813 * the property value at the given speed.
815 * property[1..n+1] any number of target values taken from named properties
816 * time/rate[0..n] time between each value, number of time elements must
817 * match those of value elements. Instead of time also rate can
818 * be used which automatically calculates the time to change
819 * the property value at the given speed.
822 do_property_interpolate (const SGPropertyNode * arg)
824 SGPropertyNode * prop = get_prop(arg);
828 simgear::PropertyList time_nodes = arg->getChildren("time");
829 simgear::PropertyList rate_nodes = arg->getChildren("rate");
831 if( !time_nodes.empty() && !rate_nodes.empty() )
832 // mustn't specify time and rate
835 simgear::PropertyList::size_type num_times = time_nodes.empty()
839 simgear::PropertyList value_nodes = arg->getChildren("value");
840 if( value_nodes.empty() )
842 simgear::PropertyList prop_nodes = arg->getChildren("property");
844 // must have one more property node
845 if( prop_nodes.size() != num_times + 1 )
848 value_nodes.reserve(num_times);
849 for( size_t i = 1; i < prop_nodes.size(); ++i )
850 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
854 if( value_nodes.size() != num_times )
858 deltas.reserve(num_times);
860 if( !time_nodes.empty() )
862 for( size_t i = 0; i < num_times; ++i )
863 deltas.push_back( time_nodes[i]->getDoubleValue() );
867 for( size_t i = 0; i < num_times; ++i )
869 // TODO calculate delta based on property type
870 double delta = value_nodes[i]->getDoubleValue()
872 ? value_nodes[i - 1]->getDoubleValue()
873 : prop->getDoubleValue()
875 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
879 return prop->interpolate
881 arg->getStringValue("type", "numeric"),
884 arg->getStringValue("easing", "linear")
889 * Built-in command: reinit the data logging system based on the
890 * current contents of the /logger tree.
893 do_data_logging_commit (const SGPropertyNode * arg)
895 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
901 * Built-in command: Add a dialog to the GUI system. Does *not*
902 * display the dialog. The property node should have the same format
903 * as a dialog XML configuration. It must include:
905 * name: the name of the GUI dialog for future reference.
908 do_dialog_new (const SGPropertyNode * arg)
910 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
915 // Note the casting away of const: this is *real*. Doing a
916 // "dialog-apply" command later on will mutate this property node.
917 // I'm not convinced that this isn't the Right Thing though; it
918 // allows client to create a node, pass it to dialog-new, and get
919 // the values back from the dialog by reading the same node.
920 // Perhaps command arguments are not as "const" as they would
922 gui->newDialog((SGPropertyNode*)arg);
927 * Built-in command: Show an XML-configured dialog.
929 * dialog-name: the name of the GUI dialog to display.
932 do_dialog_show (const SGPropertyNode * arg)
934 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
935 gui->showDialog(arg->getStringValue("dialog-name"));
941 * Built-in Command: Hide the active XML-configured dialog.
944 do_dialog_close (const SGPropertyNode * arg)
946 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
947 if(arg->hasValue("dialog-name"))
948 return gui->closeDialog(arg->getStringValue("dialog-name"));
949 return gui->closeActiveDialog();
954 * Update a value in the active XML-configured dialog.
956 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
959 do_dialog_update (const SGPropertyNode * arg)
961 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
963 if (arg->hasValue("dialog-name"))
964 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
966 dialog = gui->getActiveDialog();
969 dialog->updateValues(arg->getStringValue("object-name"));
977 do_open_browser (const SGPropertyNode * arg)
980 if (arg->hasValue("path"))
981 path = arg->getStringValue("path");
983 if (arg->hasValue("url"))
984 path = arg->getStringValue("url");
988 return openBrowser(path);
992 * Apply a value in the active XML-configured dialog.
994 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
997 do_dialog_apply (const SGPropertyNode * arg)
999 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1001 if (arg->hasValue("dialog-name"))
1002 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1004 dialog = gui->getActiveDialog();
1007 dialog->applyValues(arg->getStringValue("object-name"));
1016 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1020 do_gui_redraw (const SGPropertyNode * arg)
1022 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1029 * Adds model to the scenery. The path to the added branch (/models/model[*])
1030 * is returned in property "property".
1033 do_add_model (const SGPropertyNode * arg)
1035 SGPropertyNode * model = fgGetNode("models", true);
1037 for (i = 0; model->hasChild("model",i); i++);
1038 model = model->getChild("model", i, true);
1039 copyProperties(arg, model);
1040 if (model->hasValue("elevation-m"))
1041 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1042 * SG_METER_TO_FEET);
1043 model->getNode("load", true);
1044 model->removeChildren("load");
1045 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1050 * Built-in command: play an audio message (i.e. a wav file) This is
1051 * fire and forget. Call this once per message and it will get dumped
1052 * into a queue. Messages are played sequentially so they do not
1056 do_play_audio_sample (const SGPropertyNode * arg)
1058 SGSoundMgr *smgr = globals->get_soundmgr();
1060 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1064 string path = arg->getStringValue("path");
1065 string file = arg->getStringValue("file");
1066 float volume = arg->getFloatValue("volume");
1067 // cout << "playing " << path << " / " << file << endl;
1069 FGSampleQueue *queue = globals->get_chatter_queue();
1071 queue = new FGSampleQueue(smgr, "chatter");
1072 queue->tie_to_listener();
1073 globals->set_chatter_queue(queue);
1076 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1077 msg->set_volume( volume );
1082 } catch (const sg_io_exception&) {
1083 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1084 "failed to load" << path << '/' << file);
1090 * Built-in command: commit presets (read from in /sim/presets/)
1093 do_presets_commit (const SGPropertyNode * arg)
1095 if (fgGetBool("/sim/initialized", false)) {
1098 // Nasal can trigger this during initial init, which confuses
1099 // the logic in ReInitSubsystems, since initial state has not been
1100 // saved at that time. Short-circuit everything here.
1101 flightgear::initPosition();
1108 * Built-in command: set log level (0 ... 7)
1111 do_log_level (const SGPropertyNode * arg)
1113 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1120 do_decrease_visibility (const SGPropertyNode * arg)
1122 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1127 do_increase_visibility (const SGPropertyNode * arg)
1129 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1134 * An fgcommand to allow loading of xml files via nasal,
1135 * the xml file's structure will be made available within
1136 * a property tree node defined under argument "targetnode",
1137 * or in the given argument tree under "data" otherwise.
1139 * @param filename a string to hold the complete path & filename of an XML file
1140 * @param targetnode a string pointing to a location within the property tree
1141 * where to store the parsed XML file. If <targetnode> is undefined, then the
1142 * file contents are stored under a node <data> in the argument tree.
1146 do_load_xml_to_proptree(const SGPropertyNode * arg)
1148 SGPath file(arg->getStringValue("filename"));
1149 if (file.str().empty())
1152 if (file.extension() != "xml")
1153 file.concat(".xml");
1155 std::string icao = arg->getStringValue("icao");
1157 if (file.isRelative()) {
1158 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1159 if (!absPath.isNull())
1163 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1164 << file.str() << "'.");
1169 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1170 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1171 << file.str() << " at ICAO:" << icao);
1176 if (fgValidatePath(file, false).empty()) {
1177 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1178 "(unauthorized access)");
1182 SGPropertyNode *targetnode;
1183 if (arg->hasValue("targetnode"))
1184 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1186 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1189 readProperties(file.c_str(), targetnode, true);
1190 } catch (const sg_exception &e) {
1191 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1199 do_load_xml_from_url(const SGPropertyNode * arg)
1201 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1203 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1207 std::string url(arg->getStringValue("url"));
1211 SGPropertyNode *targetnode;
1212 if (arg->hasValue("targetnode"))
1213 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1215 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1217 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1219 if (arg->hasChild("body"))
1220 req->setBodyData(arg->getChild("body"));
1222 // connect up optional reporting properties
1223 if (arg->hasValue("complete"))
1224 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1225 if (arg->hasValue("failure"))
1226 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1227 if (arg->hasValue("status"))
1228 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1230 http->makeRequest(req);
1236 * An fgcommand to allow saving of xml files via nasal,
1237 * the file's structure will be determined based on what's
1238 * encountered in the passed (source) property tree node
1240 * @param filename a string to hold the complete path & filename of the (new)
1242 * @param sourcenode a string pointing to a location within the property tree
1243 * where to find the nodes that should be written recursively into an XML file
1244 * @param data if no sourcenode is given, then the file contents are taken from
1245 * the argument tree's "data" node.
1249 do_save_xml_from_proptree(const SGPropertyNode * arg)
1251 SGPath file(arg->getStringValue("filename"));
1252 if (file.str().empty())
1255 if (file.extension() != "xml")
1256 file.concat(".xml");
1258 if (fgValidatePath(file, true).empty()) {
1259 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1260 "(unauthorized access)");
1264 SGPropertyNode *sourcenode;
1265 if (arg->hasValue("sourcenode"))
1266 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1267 else if (arg->getNode("data", false))
1268 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1273 writeProperties (file.c_str(), sourcenode, true);
1274 } catch (const sg_exception &e) {
1275 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1283 do_press_cockpit_button (const SGPropertyNode *arg)
1285 const char *prefix = arg->getStringValue("prefix");
1287 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1290 string prop = string(prefix) + "-button";
1293 if (arg->getBoolValue("latching"))
1294 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1298 fgSetDouble(prop.c_str(), value);
1299 fgSetBool(arg->getStringValue("discrete"), value > 0);
1305 do_release_cockpit_button (const SGPropertyNode *arg)
1307 const char *prefix = arg->getStringValue("prefix");
1309 if (arg->getBoolValue("guarded")) {
1310 string prop = string(prefix) + "-guard";
1311 if (fgGetDouble(prop.c_str()) < 1) {
1312 fgSetDouble(prop.c_str(), 1);
1317 if (! arg->getBoolValue("latching")) {
1318 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1319 fgSetBool(arg->getStringValue("discrete"), false);
1325 // Optional profiling commands using gperftools:
1326 // http://code.google.com/p/gperftools/
1328 #if !FG_HAVE_GPERFTOOLS
1330 no_profiling_support()
1336 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1342 do_profiler_start(const SGPropertyNode *arg)
1344 #if FG_HAVE_GPERFTOOLS
1345 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1346 ProfilerStart(filename);
1349 no_profiling_support();
1355 do_profiler_stop(const SGPropertyNode *arg)
1357 #if FG_HAVE_GPERFTOOLS
1361 no_profiling_support();
1368 do_set_scenery_paths(const SGPropertyNode* arg)
1370 SGPropertyNode* sim = fgGetNode("/sim", true);
1371 sim->removeChildren("fg-scenery");
1373 globals->clear_fg_scenery();
1375 std::string terrasyncPath(fgGetString("/sim/terrasync/scenery-dir"));
1376 bool seenTerrasyncPath = false;
1378 simgear::PropertyList paths = arg->getChildren("path");
1379 for (size_t i = 0; i < paths.size(); ++i) {
1380 std::string s = paths[i]->getStringValue();
1381 if (s == terrasyncPath) {
1382 seenTerrasyncPath = true;
1385 globals->append_fg_scenery(s);
1388 if (fgGetBool("/sim/terrasync/enabled") && !seenTerrasyncPath) {
1389 globals->append_fg_scenery(terrasyncPath);
1392 if (paths.empty()) {
1393 // no scenery paths set *at all*, use the data in FG_ROOT
1394 SGPath root(globals->get_fg_root());
1395 root.append("Scenery");
1396 globals->append_fg_scenery(root.str());
1399 // might need to drop ground-nets from the DB. Also need to drop
1400 // them from memory, but this is tricky since FGAirportDynamics holds
1401 // an instance directly, and AI code may have pointers to ground-net
1402 // nodes. For now we'll leave-in memory versions untouched.
1403 flightgear::NavDataCache::instance()->dropGroundnetsIfRequired();
1408 ////////////////////////////////////////////////////////////////////////
1410 ////////////////////////////////////////////////////////////////////////
1414 * Table of built-in commands.
1416 * New commands do not have to be added here; any module in the application
1417 * can add a new command using globals->get_commands()->addCommand(...).
1421 SGCommandMgr::command_t command;
1423 { "null", do_null },
1424 { "nasal", do_nasal },
1425 { "exit", do_exit },
1426 { "reset", do_reset },
1427 { "reposition", do_reposition },
1428 { "switch-aircraft", do_switch_aircraft },
1429 { "pause", do_pause },
1430 { "load", do_load },
1431 { "save", do_save },
1432 { "save-tape", do_save_tape },
1433 { "load-tape", do_load_tape },
1434 { "panel-load", do_panel_load },
1435 { "preferences-load", do_preferences_load },
1436 { "toggle-fullscreen", do_toggle_fullscreen },
1437 { "view-cycle", do_view_cycle },
1438 { "screen-capture", do_screen_capture },
1439 { "hires-screen-capture", do_hires_screen_capture },
1440 { "tile-cache-reload", do_tile_cache_reload },
1442 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1443 { "set-outside-air-temp-degc", do_set_oat_degc },
1444 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1445 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1447 { "property-toggle", do_property_toggle },
1448 { "property-assign", do_property_assign },
1449 { "property-adjust", do_property_adjust },
1450 { "property-multiply", do_property_multiply },
1451 { "property-swap", do_property_swap },
1452 { "property-scale", do_property_scale },
1453 { "property-cycle", do_property_cycle },
1454 { "property-randomize", do_property_randomize },
1455 { "property-interpolate", do_property_interpolate },
1456 { "data-logging-commit", do_data_logging_commit },
1457 { "dialog-new", do_dialog_new },
1458 { "dialog-show", do_dialog_show },
1459 { "dialog-close", do_dialog_close },
1460 { "dialog-update", do_dialog_update },
1461 { "dialog-apply", do_dialog_apply },
1462 { "open-browser", do_open_browser },
1463 { "gui-redraw", do_gui_redraw },
1464 { "add-model", do_add_model },
1465 { "play-audio-sample", do_play_audio_sample },
1466 { "presets-commit", do_presets_commit },
1467 { "log-level", do_log_level },
1468 { "replay", do_replay },
1470 { "decrease-visibility", do_decrease_visibility },
1471 { "increase-visibility", do_increase_visibility },
1473 { "loadxml", do_load_xml_to_proptree},
1474 { "savexml", do_save_xml_from_proptree },
1475 { "xmlhttprequest", do_load_xml_from_url },
1476 { "press-cockpit-button", do_press_cockpit_button },
1477 { "release-cockpit-button", do_release_cockpit_button },
1478 { "dump-scenegraph", do_dump_scene_graph },
1479 { "dump-terrainbranch", do_dump_terrain_branch },
1480 { "print-visible-scene", do_print_visible_scene_info },
1481 { "reload-shaders", do_reload_shaders },
1482 { "reload-materials", do_materials_reload },
1483 { "set-scenery-paths", do_set_scenery_paths },
1485 { "profiler-start", do_profiler_start },
1486 { "profiler-stop", do_profiler_stop },
1488 { 0, 0 } // zero-terminated
1493 * Initialize the default built-in commands.
1495 * Other commands may be added by other parts of the application.
1500 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1501 for (int i = 0; built_ins[i].name != 0; i++) {
1502 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1503 globals->get_commands()->addCommand(built_ins[i].name,
1504 built_ins[i].command);
1507 typedef bool (*dummy)();
1508 fgTie( "/command/view/next", dummy(0), do_view_next );
1509 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1511 globals->get_props()->setValueReadOnly( "/sim/debug/profiler-available",
1512 bool(FG_HAVE_GPERFTOOLS) );
1515 // end of fg_commands.cxx