Howto:Add new fgcommands to FlightGear: Difference between revisions

From FlightGear wiki
Jump to navigation Jump to search
Line 205: Line 205:
== Reaching out to subsystems ==
== Reaching out to subsystems ==


Quite possibly, you may need to reach out to some other subsystems to implement a certain fgcommand, this is accomplished by using the globals-> pointer, which allows you to access other subsystems easily. Please refer to [http://gitorious.org/fg/flightgear/blobs/next/src/Main/globals.cxx#line120 $FG_SRC/Main/globals.cxx] and its header file [http://gitorious.org/fg/flightgear/blobs/next/src/Main/globals.hxx globals.hxx]. A number of helpful usage examples can be found by searching fg_commands.cxx for "globals->".
Quite possibly, you may need to reach out to some other subsystems to implement a certain fgcommand, such as accessing the sound system, the networking system or the FDM system, this is accomplished by using the globals-> pointer, which allows you to access other subsystems easily. Please refer to [http://gitorious.org/fg/flightgear/blobs/next/src/Main/globals.cxx#line120 $FG_SRC/Main/globals.cxx] and its header file [http://gitorious.org/fg/flightgear/blobs/next/src/Main/globals.hxx globals.hxx]. A number of helpful usage examples can be found by searching fg_commands.cxx for "globals->".





Revision as of 15:03, 28 July 2012

Background

So called "fgcommands" are FlightGear extension functions which can be invoked in a number of different ways, such as embedded in various XML files (in the form of "action" bindings), but also via Nasal scripts using the fgcommand() extension function. In addition, it is also possible to invoke fgcommands using the telnet/props interface, so that a simple form of "Remote Procedure Calling" can be implemented, i.e. triggering code via telnet to be run inside the FlightGear process.

Compared to Nasal extension functions, the nice thing about "fgcommands" is that they are not just available to Nasal scripts, but that they can also be used by lots of other FlightGear systems directly without resorting to scripts and registering listeners, such as in the form of GUI bindings, mouse/keyboard handlers and so on.

Of course, there are some disadvantages too: fgcommands always need their arguments wrapped in a property tree structure. This is because they don't have any concept of Nasal and its internal data structures, as they need to work with just XML files and the property tree.

So there is a certain marshaling/conversion overhead involved here. While this is certainly negligible for simple commands that are run rarely, this overhead may add up once a certain fgcommand gets called repeatedly at a high rate. In such cases it may be more efficient to let the command work with argument lists (vectors) rather than just a single argument, so that multiple tasks can be completed by a single invocation.

An overview of fgcommands currently available and supported is provided in $FG_ROOT/Docs/README.commands.

Creating a new fgcommand is fairly simple actually. The source code you need to look at is in $FG_SRC/Main/fg_commands.cxx.


All commands are listed there, beginning in line #160. The signature of these callback functions is always such that they:

  • have static linkage
  • return a bool (true/false, 1/0)
  • accept one const pointer to a SGPropertyNode (const SGPropertyNode * arg)

The simplest command can be found in line 167, the do_null() command which does nothing:

/**
 * Built-in command: do nothing.
 */
static bool
do_null (const SGPropertyNode * arg)
{
  return true;
}


To see if that's actually doing something, you could add a printf or cout statement and rebuild FlightGear (you'll probably want to use a new git branch for these experiments, in order not to mess up your main branch - when doing that you'll just need to "git add fg_commands.cxx && git commit -m test" after making modifications):

/**
 * Built-in command: do nothing.
 */
static bool
do_null (const SGPropertyNode * arg)
{
  printf("Okay: doing nothing :)");
  return true;
}

Next, you could run the modified fgcommand by using the Nasal console (make sure to watch your console):

 fgcommand("null");

Regarding the syntax of the fgcommand() function: the first parameter is the name of the command that you'd like to run, the second parameter points to an optional property node that contains all the required parameters, that are separately set up.

Argument processing

All callback functions need to accept a single argument, i.e. a const pointer: const SGPropertyNode*. This single argument is used to pass a property sub branch to each fgcommand. This means that each fgcommand is responsible for parsing and processing its function arguments.


For instance, imagine a command that accepts three different parameters to play an audio file:

  • path
  • file
  • volume

These all need to be first set up in the property tree separately, i.e. using setprop:

 setprop("/temp1/path","my path" );
 setprop("/temp1/file","filename" );
 setprop("/temp1/volumen", 1);
 fgcommand("null", "/temp1");

You could just as well use a temporary property tree object, rather than the global property tree:

 var myTree = props.Node.new( {"filename": "stars.jpeg"} );
 fgcommand("null", myTree);

This would turn the hash initialized into a property tree structure, an even shorter version would be:

 fgcommand("null", props.Node.new( {"filename": "stars.jpeg"} ) );

In general, using a temporary property tree object is preferable and recommended if you don't need to access the data in the global property tree otherwise.

So, what the C++ code is doing once it is called, is getting the arguments out of the property argument, see line 1183:

 string path = arg->getStringValue("path");
 string file = arg->getStringValue("file");
 float volume = arg->getFloatValue("volume");

This is accomplished using the Property Tree API, i.e. the methods available in the SGPropertyNode class: http://simgear.sourceforge.net/doxygen/classSGPropertyNode.html

The most frequently used methods are:

  • bool getBoolValue () const: Get a bool value for this node.
  • int getIntValue () const: Get an int value for this node.
  • long getLongValue () const: Get a long int value for this node.
  • float getFloatValue () const: Get a float value for this node.
  • double getDoubleValue () const: Get a double value for this node.
  • const char * getStringValue () const: Get a string value for this node.

However, before actually trying to read in an argument, it is better to first check if the node is actually available, too:

 if (arg->hasValue("path"))
  string path = arg->getStringValue("path");

If an important argument is missing that you cannot set to some sane default value, you should show an error message and return false, to leave the function early:

 if (arg->hasValue("path"))
  string path = arg->getStringValue("path");
  else {
   printf("Cannot play audio file without a file name");
   return false;
  }

There is also a helper macro called SG_LOG available to print debug messages to the console:

 if (arg->hasValue("path"))
  string path = arg->getStringValue("path");
  else {
   SG_LOG(SG_GENERAL, SG_ALERT,"Cannot play audio file without a file name");
   return false;
  }

Exception handling

To be on the safe side, complex fgcommands, which may terminate for one reason or another (such as missing files), should make use of exception handling to catch exceptions and deal with them gracefully, so that they cannot affect the simulator critically.

This is accomplished by using standard C++ try/catch blocks, usually catching an sg_exception. The SG_LOG() macro can be used to print debugging information to the console. If you'd like to display error information using the native FlightGear GUI, you can use the "guiErrorMessage(const char*,sg_exception)" helper.

For example, see the callback function "do_preferences_load" in line 445:

/**
 * Built-in command: (re)load preferences.
 *
 * path (optional): the file name to load the panel from (relative
 * to FG_ROOT). Defaults to "preferences.xml".
 */
static bool
do_preferences_load (const SGPropertyNode * arg)
{
  try {
    fgLoadProps(arg->getStringValue("path", "preferences.xml"),
                globals->get_props());
  } catch (const sg_exception &e) {
    guiErrorMessage("Error reading global preferences: ", e);
    return false;
  }
  SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
  return true;
}


Hello World

For example, to implement a new "hello_world" command, that accepts a single parameter named "name":

/**
 * Built-in command: print hello world (name) to the console
 *
 * name (optional): the file name to load the panel from
 * 
 */
static bool
do_hello_world (const SGPropertyNode * arg)
{
  string name = "anonymous"; // default
  if (!arg->hasValue("name")) {
    guiErrorMessage("Cannot say hello without name!: ");
    return false;
  }
  name = arg->getStringValue("name");
  try {
    SG_LOG(SG_GENERAL, SG_ALERT, "Hello World:"<<name.c_str() );
  } catch (const sg_exception &e) {
    guiErrorMessage("Error saying HELLO WORLD: ", e);
    return false;
  }
  return true;
}


After adding the new callback to the callback list and rebuilding FlightGear, you can easily invoke the new "hello_world" fgcommand using the Nasal console like this:

 fgcommand("hello_world", props.Node.new( {"name": "Howard Hughes"} ));

Reaching out to subsystems

Quite possibly, you may need to reach out to some other subsystems to implement a certain fgcommand, such as accessing the sound system, the networking system or the FDM system, this is accomplished by using the globals-> pointer, which allows you to access other subsystems easily. Please refer to $FG_SRC/Main/globals.cxx and its header file globals.hxx. A number of helpful usage examples can be found by searching fg_commands.cxx for "globals->".


A list of methods available to access certain subsystems is provided here in globals.hxx, beginning in line 220.

Adding new commands

All new commands must have the previously described signature, the functions should then be added to the list of built-in commands, beginning in line 1467. The list of built-in commands maps the human-readable names used in README.commands to the names of the internal C++ functions implementing them.

When you send patches or file merge requests for new fgcommands, please also make sure to send patches for README.commands, too - so that your new commands are documented there.

This was just an introduction intended to get you started, most of the missing information can be learned by referring to the plethora of existing fgcommands and see how they are implemented and working.

Please get in touch if you think that there's something missing here, or just add your information directly!