VR-Forces Developer's Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
8 - 3D Graphics

This section describes the technologies the GUI API uses to render 3D graphics.

This section describes the technologies the GUI API  uses to render 3D graphics.

7.1 - Rendering 3D Images

The component responsible for drawing 3D images onto a screen is called a renderer. Each display engine owns one. The renderer is based on OpenSceneGraph (OSG).

Distributed objects usually affect the scene graph. They can add nodes, remove nodes, change transforms, and change state. Therefore, when a master display engine calls an agent, it is causing changes to the scene graphs of external display engines. In the figure, the master display engine has an agent. The agent has a corresponding distributed object that exists in each display engine. The distributed object adds nodes to the scene (the Tank Group Node) and positions them in the world using a transform.

vrv_agentanddistribuedobject.png
Agent and Distributed Object

7.2 - The Renderer

The core GUI API framework abstracts away from the underlying rendering implementation. This separation ensures that the rendering-independent code remains independent of OSG, while the rendering code exists in the libraries that depend on OSG. (VR-Forces can support alternate rendering solutions.) The class responsible for rendering in VR-Forces is DtRenderer. The DtRenderer provides an interface for updating the scene graph and rendering the scene. The DtRenderer instance is owned by the display engine. Its update() and render() functions are called each display engine tick.

For more information, please see 2.4 - The Rendering System Layer.

7.3 - OpenSceneGraph Extensions in VR-Forces

VR-Forces implements extensions to OpenSceneGraph. The SilverLining cloud and ephemeris model is integrated by a custom group node and two drawables. An OSG drawable is the generic interface that OSG provides for doing OpenGL drawing. The SpeedTree vegetation rendering is an example of a custom drawable. The DtSpeedTreeDrawable can make the SpeedTree rendering API calls. Once a custom model is created, it is free to create custom drawables, which are added to geode nodes.

7.4 - Cockpit Display Updaters

A cockpit display updater is a C++ object that updates part of a GL Studio cockpit display (HUD). An updater examines the entity state and sends the cockpit display object or its agent the appropriate message. All updaters send their values as text strings, as required by GL Studio cockpit displays.

VR-Forces provides updaters for the cockpit displays it ships. However, you can use the GUI APIand GL Studio to replace updaters or add custom updaters to be used with the supplied cockpit displays or your own cockpit displays. Custom updaters must derive from DtGlStudioVrlAttributeUpdater or DtGlStudioObjectAttributeUpdater. Updaters are created using a creator object. New updater creator objects are registered with the factory.

Creators have a name and a protocol. This is because updaters that work with DIS entities do not work with HLA entities. You can generate multiple updaters by using the shared source technique that is used elsewhere in the GUI API. (For more information, please see 5.2.2 Using Shared Source Files for Simulation Drivers.) The supported protocols are DtDis, DtHla13, DtHla1516, DtHla1516e, and Object. The updater factory is in the DtSharedCockpitSettings object. Registering a new creator is done through its registerUpdater() function.

VR-Forces provides the following cockpit display updaters:

Updaters can exist in the simulation thread, owned by the GL Studio Visualizer, or in the render thread, owned by the GL Studio cockpit display object.

Updaters that live in the simulation thread have access to the entire simulation state in the entity state repository. These updaters are updated at the same rate as the network thread (approximately 15 times per second). The values that these updaters send are not smoothed in the cockpit display. These updaters are derived from the DtGlStudioVrlAttributeUpdater and have a protocol of DtDis, DtHla13, DtHla1516, or DtHla1516e.

Updaters that live in the render thread are owned by the GL Studio cockpit display object. They have access to the cockpit display object's smoother. This smoother is updated by the simulation thread and the position, velocity, acceleration, and rotation are smoothed between updates. The render thread updaters update their values approximately 60 times per second. These updaters are registered with a protocol of Object.

Note
It is important to install new updaters after the display engine is initialized. Connect to the display engine object's post_initialize signal to be notified when it is done initializing. Then install your updaters.

7.5 - Making OpenGL Calls from OSG Drawables

It is possible to call OpenGL directly from an OSG drawable. It is very easy to corrupt the scene rendering when you do this. OSG maintains a copy of the OpenGL state in its own state object osg::State. If this state object and the actual OpenGL state are not synchronized, then the rendering will not be correct. If you must call OpenGL directly, you must undo any changes to the OpenGL state that you make. After your code is executed, the OpenGL state must be returned to the values it had before your code was executed. This will ensure that the OSG and OpenGL states are synchronized.

The following pseudo-code is an example of what must happen for all OpenGL states:

//For all states you want, check the existing OSG state.
If(osg_state != desired_state)
{
OPENGL_setState(desired_state);
}
//Call render commands
OPENGL_renderCommands();
//For all states you changed, restore back to the OSG state.
If(osg_state != desired_state)
{
OPENGL_setState(osg_state);
}

7.5.1 Debugging OpenGL

OpenGL has a callback that sends debug messages to the console. To enable this callback, set the VRV_GL_DEBUG environment variable to any value. (The value does not matter. The environment variable just needs to exist.)

7.6 - Transforming Nodes Programmatically

You can associate code with particular nodes in a scene graph using a configuration file called a meta file. A meta file lets you change the behavior of an object without having to recompile code. This approach is used to animate windsocks, and flags on terrain and ships. For example, windsocks rotate based on wind direction and change state based on the speed of the wind. The parameters that control how the windsock responds are in its meta file.

Note
This feature is still experimental and can only be applied under particular circumstances on particular nodes in the scene graph.

7.6.1 Node Transformation Components

Programmatic node transformation depends on the interaction of a meta file, a properly annotated model, and supporting code.

7.6.2 Anatomy of a Meta File

A meta file uses a JSON format and parser to convert the document into data that VR-Forces can use. As with all JSON files, braces ({}) are used to hold different name/value pairs, square brackets ([]) are used for arrays, and name:value is used for name/value pairs. VR-Forces emits a warning message when there is a syntax error. It is usually easier to copy a working file and modify it than to write one from scratch.

Note
There are several JSON editors available online (such as https://www.jsoneditoronline.org/) or plugins for NotePad++ that color code the structure of the file and indicate any errors.

7.6.2.1 Meta File Keywords

The following is an example meta file:

{
"NodeFeatures": [
{
"Linkage": {
"Comment": "Traversal will match based on node name or annotation",
"NodeName": "sw1",
"AnnotationName": ""
},
"FeatureData": [
{
"FeatureName": "WindSwitchPart",
"Comment1": "Change state based on wind speed (km/h).",
"Comment2": "0-5 km/h is for switch state 0, 5-10 is for state 1, ...",
"WindSpeed": [
5,
10,
15
],
"WindState": [
0,
1,
2
]
}
]
}
]
}

The keywords in the example meta file are as follows:

7.6.3 Adding New Transforms

If you want to add your own programmatic transforms, you must:

  1. Edit the models that you want to change programmatically. To do this you need an editing tool such as Presagis Creator.

  2. Create a new meta file. Specify the node names or annotations to match. Specify the feature name that matches the name of the meta object in the code. Specify an additional parameters for the object.

  3. Write the code. DtWindSwitchTickable and DtShipFlagDirTickable are examples of custom meta file updating and configuration code. The new class must be derived from DtVirtualBaseClass. The examples that have been implemented in VR-Forces inherit from DtTickable and DtVirtualBaseClass. However, the only required class to derive from is the DtVirtualBaseClass.
  4. Create a creator for the new object. See DtMetaObjectCreator.h. The creator class should derive from DtMetaObjectCreator.
  5. Register your object with the DtMetaObjectFactory. See examples in vrvOsg.cxx. The following code shows how to register DtWindSwitchTickable with the DtMetaObjectFactory:

    DtMetaObjectFactory& mof = DtMetaObjectFactory::instance(de);
    mof.addCreator(DtWindSwitchTickable::theWindSwitchFeatureName, new DtWindSwitchTickableCreator());

    The variable, theWindSwitchFeatureName, matches the FeatureName in the meta file. This lets VR-Forces know what type of object to create.

  6. For objects that have model definitions, add a metaFileName entry to the model definition. For items such as terrain patches, which do not have model definitions, put the meta file in the same directory as the medf file for the terrain.

7.6.4 Restrictions and Limitations

The following are restrictions and limitations apply to programmatically transforming nodes:

It is easier to use similar orientations and facing directions for multiple nodes (e.g. multiple flags on terrain). Different orientations (e.g. a circle of flags oriented in different directions) would need more sophisticated code to undo the local transforms and put the flags into a common space for calculating wind direction.

For an example of how to use meta files and code, see Example of Transforming Nodes Programmatically.

7.6.0 - Example of Transforming Nodes Programmatically

This example shows how VR-Forces uses meta files and related code to animate the flag on the Arleigh Burke ship.

7.6.0.1 - Editing the Arleigh Burke Model

The Arleigh Burke model was modified to include specific nodes for the flag at the back of the ship. The flag has three overlapping models for the three wind states (no wind, low wind, and high wind). Figure 1 illustrates the flag models:

arleighburkeflag.png
Figure 1. Flag Model for Arleigh Burke

Figure 2 illustrates the structure of the specific nodes for the flag in Creator.

vrv_flagnodes.png
Figure 2. Node Structure for the Flags

The node named 'FlagDir' is a DoF (degree of freedom) node. The FlagDir node rotates the flag to fly in the wind direction. The FlagDir node also has an annotation as seen in Figure 3. This annotation is used in the meta file to find the FlagDir node in the scene graph when Vantage traverses it.

vrv_flagdirnode.png
Figure 3. Annotation for FlagDir Node

The node named sw2 is used to set the flag state in this example. sw2 is a switch node that has 3 states (nodes g323, g323_1, g325). While FlagDir is for orientation, the sw2 node is for making the flag appear upright when the wind is high. The node has an annotation as seen in Figure 4.

vrv_sw2node.png
Figure 4: Flag Switch Node

For matching a node, either the node name or the annotation (or both) can be provided. Any node that matches either criterion will be processed. For the flag state, both the node name and annotation are used for matching criteria.

7.6.0.2 - The Arleigh Burke Meta File

The Arleigh Burke meta file is in the data directory: data\Vehicles\Surface\ddg51_arleigh-burke_navy\1407007162_arleigh-burke_ddg51_arleigh-burke_navy.meta. The meta file for the Arleigh Burke flag is as follows:

{
"NodeFeatures": [
{
"Linkage": {
"Comment": "Traversal will match up this feature based on NodeName match OR AnnotationName match",
"NodeName": "sw2",
"AnnotationName": "@dis switch wind_effect"
},
"FeatureData": [
{
"FeatureName": "ShipFlagSwitch",
"Comment": "Change state based on wind speed. Each state corresponds to a km/h speed",
"WindSpeed": [
5,
10,
15
],
"WindState": [
0,
1,
2
]
}
]
},
{
"Linkage": {
"Comment": "Traversal will match up this feature based on NodeName match OR AnnotationName match",
"NodeName": "",
"AnnotationName": "@dis articulated_part 7872"
},
"FeatureData": [
{
"FeatureName": "ShipFlagDir",
"Comment": "This part rotates to align with the net wind velocity (= wind_dir only) (use CW, CCW for rotation direction) (use RotOffsetDeg to compensate for model rotation)",
"RotOffsetDeg": 0,
"RotDir": "CCW"
}
]
}
]
}
]
}

The NodeName and AnnotationName fields match the node name and comments in the model. This is the link between the asset and the meta file.

FeatureName is the link between the meta file and the code. Each specific FeatureName corresponds to a particular class in the Vantage code.

7.6.0.3 - Coding the Arleigh Burke Flag

For the meta file to influence the runtime visuals, new code must be written. The flag code class hierarchy is shown in Figure 4.

vrv_arleighburkeflagclasshierarchy.png
Figure 4: The Classes Related to the Flag Orientation and State

Look at DtShipFlagSwitchTickable in Figure 4. Since the flag on the ship may change state on every frame, DtShipFlagSwitchTickable inherits from DtTickable. DtDynamicFeatureTickable includes common elements for all the terrain flags and ship flags.

7.6.0.4 - The Creator Class

The object needs a creator class for dynamic construction. The following classes are derived from DtMetaObjectCreator:

In Vantage, there is a DtMetaObjectFactory, which produces the objects based on the FeatureName string. The FeatureName is the link between the meta file and the code (via the DtMetaObjectFactory). The creator constructor has many arguments. However, not every meta object needs to use all the arguments.

7.6.0.5 - Parsing the Meta File Information

RapidJSON is used to parse the configuration parameters for the object. DtShipFlagSwitchTickable.cxx contains an example of code for parsing in the configuration data. The following code demonstrates the use of RapidJSON to extract information out of a JSON document. VR-Forces uses the RapidJSON library to parse the meta file. The RapidJSON library is well-documented, so it is straightforward to find other examples of parsing more complicated parameters.

void DtShipFlagSwitchTickable::configure(osg::Node* n,
const rapidjson::Value& windJsonData)
{
// Get our node and cast it to the correct type for what we expect
myWindSwitchNode = dynamic_cast<osgSim::MultiSwitch*>(n);
if(!myWindSwitchNode)
{
myDe.DT_LOG_WARN << "DtShipFlagSwitchTickable: node (" << n->getName()
<< ") with type (" << n->className()
<< ") is not convertible to MultiSwitch" << std::endl;
}
// Get the feature name
myFeatureName = windJsonData[DtMetaFileManager::theTagFeatureName].GetString();
// Get the array of wind speeds
if(!windJsonData.HasMember(theTagWindSpeeds))
{
myDe.DT_LOG_WARN << "Error: Could not find entry (" << theTagWindSpeeds
<< ") in feature (" << myFeatureName << ")" << std::endl;
return;
}
const rapidjson::Value& speedsArray = windJsonData[theTagWindSpeeds];
const int numSpeeds = speedsArray.Size();
// Get the array of switches
if(!windJsonData.HasMember(theTagSwitchIndices))
{
myDe.DT_LOG_WARN << "Error: Could not find entry (" << theTagSwitchIndices
<< ") in feature (" << myFeatureName << ")" << std::endl;
return;
}
const rapidjson::Value& statesArray = windJsonData[theTagSwitchIndices];
const int numStates = statesArray.Size();
if(numSpeeds != numStates)
{
myDe.DT_LOG_WARN << "Error: Number of wind speeds (" << numSpeeds
<< ") does not match the number of wind switch states ("
<< numStates << "). Using minimum." << std::endl;
return;
}
int numWindElements = DtMin(numSpeeds, numStates);
for (int i = 0; i < numWindElements; ++i)
{
myWindSpeeds.push_back(speedsArray[i].GetDouble());
mySwitchIndices.push_back(statesArray[i].GetInt());
}
}

7.6.0.6 - Registering with the DtTickableManager

Since DtShipFlagSwitchTickable is a DtTickable element, it is registered with the DtTickableManager so that its update function is called every frame as follows:

DtShipFlagSwitchTickable* DtShipFlagSwitchTickableCreator::create(...)
{
...
windTickable->configure(node, jsonObject);
// This object is tickable, so add this object to the tickable manager
de.renderer().tickableManager().addTickableObject( windTickable );
return windTickable;
}

If your object is not updated every frame, this step is optional.

7.6.0.7 - Creating the Update Function

The DtShipFlagSwitchTickable::Update function is called every frame, so update tries to return early if parameters have not changed since the last frame. The flag also has a smoother so that the direction does not change drastically frame to frame.

void DtShipFlagSwitchTickable::update(double tNow)
{
if(!myWindSwitchNode)
{
return;
}
// winDirRad = radiansClockwiseFromNorth
// in radians East from North. This is the direction the wind is
// coming from
float windDirRad = myEnvironment.windDirection();
// In meters / second!
float windSpeedMperS = myEnvironment.windSpeed();
// If there is no sceneObj, use only the
// wind speed (not wind+ship speed)
double windSpeed = windSpeedMperS;
// Get the direction and speed of the current ship
// This should have been set in DtOsgArticulatedModel
if(!mySceneObject)
{
// Do the simple thing - assume ship speed = 0
SetWindNodeSwitch(windSpeed);
return;
}
// Calculate the wind direction as a vector
DtVector windDirVec = computeWindVec(mySceneObject, windDirRad);
// Get the ship updater
DtDeadReckonUpdater* updater = dynamic_cast<DtDeadReckonUpdater*>(mySceneObject->findUpdater());
DtVector shipVelMperS;
if(updater)
{
// Get the ship velocity (assuming m/s)
shipVelMperS = updater->approxVelocity(tNow);
}
else
{
DtVector currPos;
mySceneObject->getPosition(0, currPos);
DtVector deltaPos = currPos - myLastPos;
DtTime deltaTime = tNow - myLastTime;
if(deltaTime <= 0)
{
return;
}
DtVector velocity;
DtVecScale(deltaPos, 1.0f/deltaTime, velocity);
shipVelMperS = velocity;
myLastPos = currPos;
myLastTime = tNow;
}
// The flag direction is the opposite of the boat velocity
DtVector flagVel;
DtVecNeg(shipVelMperS, flagVel);
// Get the wind direction scaled by the wind speed
DtVector scaledWindVec;
DtVecScale(windDirVec, windSpeedMperS, scaledWindVec);
// Compute combined ship+wind vector
DtVector combinedWindDir = scaledWindVec + flagVel;
// This is the wind speed taking into account the ship and the wind
windSpeed = DtMath::Sqrt(combinedWindDir.magnitudeSquared());
myFlagSpeedSmoother.addValue(windSpeed);
// Smooth if there is enough data or
// else use the raw wind speed
if(myFlagSpeedSmoother.queueFilled())
{
windSpeed = myFlagSpeedSmoother.currAvg();
}
// Wind speed didn't change, node switch state shouldn't change
if(windSpeed == myLastWindSpeed)
{
return;
}
else
{
SetWindNodeSwitch(windSpeed);
myLastWindSpeed = windSpeed;
}
}

If your object does not need to be updated, this step is optional.

7.6.0.8 - Register with the DtMetaObjectFactory

In order for the DtShipFlagSwitchTickable object to be available to VR-Forces, it needs to be registered with the DtMetaObjectFactory. This occurs in vrvOsg.cxx file in the init function. However, you can register objects in their own files as well:

// Register the creators with the DtMetaObjectFactory
// the*FeatureName must match "FeatureName" field in the meta file
DtMetaObjectFactory& mof = DtMetaObjectFactory::instance(de);
mof.addCreator(DtShipFlagSwitchTickable::theShipFlagSwitchFeatureName, new DtShipFlagSwitchTickableCreator());

In this code, theShipFlagSwitchFeatureName refers to the string "ShipFlagSwitch", which matched the FeatureName in the meta file. This is how the connection between the code and the meta file is established.

7.6.0.9 - Traversing the Scene Graph

You must attach the code to matching nodes. The matching is done through a traversal, which in DtOsgArticulatedModel and DtOsgTerrainPatch is done in a function called applyMetaFile. applyMetaFile relies on the DtMetaFileVisitor which is used as follows:

DtMetaFileVisitor metaFileVisitor(myDe, myModelMetaFeatures, myModelMetaAttachments, myModelDefinition, elementId, mySceneObjectId, myUniqueId, myIsInstanced);
rootNode->accept(metaFileVisitor);

A function similar to applyMetaFile would be needed in custom classes to associate the meta file objects with the nodes in the scene graph.

7.6.0.10 - Instancing Support

You can incorporate instancing into a meta object. An example of handling instanced data is provided in the update functions. Ships are not instanced, but flags on terrain can be instanced. The instanced path for an update function is as follows:

// update the multiswitch
unsigned int switchIndex = getSwitchIndexForSpeed(windSpeed);
unsigned int switchSet = myWindSwitchNode->getActiveSwitchSet();
myWindSwitchNode->setSingleChildOn(switchSet, switchIndex);
// Instanced path
if(myUseInstancing)
{
// Use myUniqueId from DtOsgArticulatedModel
DtInstanceState* instanceState = myInstanceManager.findInstanceState(myUniqueId);
if(instanceState)
{
unsigned int numChildren = myWindSwitchNode->getNumChildren();
for (unsigned int childIx = 0; childIx < numChildren; ++childIx)
{
bool state = myWindSwitchNode->getChildValue(switchIndex, childIx);
myInstanceManager.setSwitchState(*instanceState, myNodeTypeIndex, childIx, state);
}
}
}

The instancing path needs specific code that mirrors code in DtOsgArticulatedModel. In this example, the node is set normally and then the state is read back to update the instanced data.

7.7 - VR-Vantage Shader Architecture

See exampleCustomShaders for an example of how to modify the VR-Vantage shaders.

7.7.1 OsgEarth Virtual Programs

VR-Forces takes advantage of the osgEarth framework for shader composition called virtual programs. These virtual programs allow multiple libraries to contribute to a shader program without needing to have the full program available and even apply the same shader function to multiple programs. OsgEarth has in-depth documentation here: http://docs.osgearth.org/en/latest/developer/shader_composition.html

7.7.2 Global Shader Variables

VR-Forces shaders use global variables to pass information between virtual program functions. Here is a list of some important globals you may want to use, what they are used for, and when you can modify them. All of these globals are only available in the fragment shader.

7.7.3 Shader Variants

Variants are used to pass data between the vertex shader and the fragment shader. The following list describes some important variants used by the VR-Vantage shaders, when they are set, and when they are used:

This section describes the technologies the GUI API uses to render 3D graphics.


Document ID: Generated on Thu Oct 15 21:27:02 EDT 2026 from SVN revision 296421
Copyright © 2005-2026 MAK Technologies. All Rights Reserved (www.mak.com)