VR-Vantage
Loading...
Searching...
No Matches
exampleBallistics

Overview

This example demonstrates the VR-Vantage ballistics system in isolation. It creates a plug-in driver, DtExampleBallisticsDriver, that fires bursts of GPU tracer rounds in response to key presses, removes them again, and previews the predicted trajectory of each shot. The example shows no platform or vehicle: the only things drawn are the GPU tracers and the trajectory-preview arcs.

Expected Result

Tracer bursts and predicted trajectory arcs

When you press one of the fire keys, a burst of tracer rounds is fired from a fixed muzzle position and travels along a ballistic trajectory under the influence of gravity and wind. Each fire key produces a differently coloured tracer burst. As a tracer passes near the observer, the "Bullet Flyby" proximity sound plays.

When you press Shift together with a fire key, nothing is fired. Instead, the driver draws the predicted trajectory of that same shot as three coloured arcs: green for wind plus gravity, yellow for gravity only, and red for no forces. Comparing the arcs shows how much wind and gravity bend the path. The arcs remain visible for 10 seconds, and if you change the wind while they are displayed the green wind-and-gravity arc re-bends immediately to match.

Example details

The example is built around the DtBallisticManager singleton, which owns the GPU ballistics simulation. The driver installs a DtEventProcessorInterface to watch for key presses. On a fire key it fills in a DtBallisticManager::BallisticData record and calls DtBallisticManager::createProjectiles(). On a Shift+key it runs the CPU-side DtTrajectoryPredictor instead and renders the result with DtDebugShapes.

Both the fire path and the preview path read the same per-key parameters from a single shot table, so the previewed arc always matches the burst that would be fired. Each entry describes a burst: the muzzle position and velocity, maximum range, the number of rounds, the rate of fire, how often a round is a visible tracer (the tracer interval), and the tracer appearance (DtTracerDefinition). The proximity sound group is always "Bullet Flyby".

The driver demonstrates several capabilities of the ballistics system:

  • Firing bursts. Three fire keys each fire a burst with a distinct tracer colour and cadence:
    • 'B' fires a 15-round burst of orange (DtTracerDefinition::orangeHeavy()) tracers at 750 rounds per minute, with every 5th round visible.
    • 'N' fires a 3-round burst of red (DtTracerDefinition::red()) tracers at 550 rounds per minute, with every round visible.
    • 'M' fires a 3-round burst of green (DtTracerDefinition::green()) tracers at 550 rounds per minute, with every 2nd round visible.
  • Previewing trajectories. Holding Shift while pressing 'B', 'N', or 'M' draws the predicted trajectory for that shot without firing. Three arcs are drawn: green (wind and gravity), yellow (gravity only), and red (no forces). The predictor uses DtTrajectoryPredictor with a DtBallisticEnvironment built from the local coordinate frame. Each arc stays on screen for 10 seconds and then self-expires, or can be cleared sooner with the 'R' key.
  • Removing. The 'R' key calls DtBallisticManager::removeProjectiles() for every burst fired so far and clears every predicted arc.
  • Wind. The driver connects to wind speed and wind direction change signals. The fired tracers use the current wind, and any preview arc currently on screen is re-predicted the moment the wind speed or direction changes, so the green wind-and-gravity arc bends in real time to track the latest wind.
  • Terrain independence. The hardcoded muzzle positions and velocities are selected at compile time by the USE_GEOCENTRIC_TERRAIN switch so the example works on both geocentric (ECEF) and flat-earth terrains.

The Example

The entry point exampleBallistics.cxx registers the plug-in and creates the DtExampleBallisticsDriver. The driver's onStart() loads the terrain, connects the wind signals, and installs the key event processor. onTick() polls the per-key fire and preview flags each frame, calling fireShot() to launch a tracer burst and predictShot() to draw a trajectory preview, both reading the shared shot table.

Building the Example

VR-Vantage includes pre-built versions of the example plug-in. To build it yourself, follow the instructions at Building VR-Vantage Examples, Applications, and Plug-ins.

Running the Example

This example is a plug-in. You can run it by running vrvStealth.exe –plugin ../examples/plugins/release/exampleBallistics.dll (on Windows) or vrvStealth.exe –plugin ../examples/plugins/release/libexampleBallistics.so (on Linux) from the command prompt. Once running, press 'B', 'N', or 'M' to fire a tracer burst, hold Shift with 'B', 'N', or 'M' to preview a trajectory, and press 'R' to remove everything. For more information about running examples, please see Running Applications and Examples.

Example Source Files


exampleBallistics.cxx

/*****************************************************************************
* Copyright (c) 2026 MAK Technologies, Inc.
* All rights reserved.
*****************************************************************************/
#include <vrvCore/DtDe.h>
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtWidgets/QToolBar>
// Use the VR-Vantage namespace.
// All classes in VR-Vantage are in this namespace.
using namespace makVrv;
static vrvSignalsLib::connection postInitializeConnection;
class DtExampleBallisticsToolbar : public DtToolbar
{
public:
DtExampleBallisticsToolbar( DtDe& de )
: DtToolbar( de, "DtExampleBallisticsToolbar" )
{
}
virtual ~DtExampleBallisticsToolbar() {}
virtual QToolBar* createToolbar( DtDe& de, QWidget* parent )
{
QString title = QObject::tr("Ballistics Example Toolbar");
QToolBar* tb = new QToolBar( parent );
tb->setWindowTitle( title );
tb->setObjectName( title );
return tb;
}
};
void initializeMinimalUI( DtDeInitializer&, DtDe&,
{
// Create DtExampleDriver.
// The driver is now owned by the display engine. Do not delete it.
de.driverManager().addDriver(driver);
// Start the driver, creating the agent.
de.driverManager().startDriver(driver);
// Disconnect now that the one-time post-initialize setup is complete.
postInitializeConnection.disconnect();
}
void init(DtDe& de)
{
// Ensure that init only gets called once
// (not strictly necessary here, but this is good practice in general)
// We only want to create the driver if we are running in master mode.
if (de.isInMasterMode())
{
//DtVrvApplication* app = DtVrvApplication::findFromDe(de);
//if (app)
//{
// DtVrvApplication::ApplicationTransform functor = boost::bind(&initializeMinimalUI, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3);
// app->installPostPluginTransform(functor, "MinimalUIPostPluginTransform");
//}
// The accessory must be created after the DE's initialization is
// finished, to make sure all the objects it uses exist.
postInitializeConnection = de.signal_postInitialize.connect(boost::bind(
&installDriver, std::ref(de)));
}
}
{
// Setup the plug-in. Normally, the init function and functionality
// should be in its own library.
init(*de);
return true;
}
void initializeMinimalUI( DtDeInitializer& deInit, DtDe& de,
{
// Register the toolbar so it can be added to the gui.
DtQtToolbarAssembler::instance(de).registerToolbar(
new DtExampleBallisticsToolbar(de) );
// Register the toolbar menuitem so it can be added to the toolbar.
DtQtMenuAssembler::instance(de).registerMenu(
// Add the example's toolbar with the FireDetonateLines toggle button.
toolbar.addToolbarPath( DtToolbarPath::toolbar("DtExampleBallisticsToolbar") );
toolbar.addToolbarPath( DtToolbarPath::toolbar("DtExampleBallisticsToolbar").item("DtFireDetonateLinesItem") );
// Tell the De not to show the startup screen. This must be done here
// because it will be overwritten if set with the rest of the configs.
}
Contains makVrv::DtDe class.
#define DT_DE_INIT_ONCE(de)
This macro is called by modules in their init() function. This macro ensures that the module is only ...
Definition DtDe.h:30
Contains makVrv:DtMasterScene class.
Contains classes used as menu items on the entity menu.
Contains the DtExampleBallisticsDriver class declaration.
Contains makVrv::DtQtToolbarAssembler class.
Contains makVrv::DtStealthConfiguration class.
Contains makVrv::DtToolbar class declaration.
Contains makVrv::DtVrvApplication implementation.
Driver that demonstrates firing GPU tracer bursts and previewing predicted ballistic trajectories.
Definition DtExampleBallisticsDriver.h:38
The DtDe is the core component of any VR-Vantage application. It owns a DtRenderer,...
Definition DtDe.h:77
DtAgentManager & agentManager()
Get the scene manager.
virtual bool isInMasterMode() const
Returns true if the DtDe is in master mode.
virtual DtDriverManager & driverManager()
The DtMasterScene accessor. The function will throw before the initialize function is called.
boost::signalslib::signal< void()> signal_postInitialize
Definition DtDe.h:535
The initialization configuration for the makVrv::DtDe.
Definition DtDeInitializer.h:40
void addDriver(DtDriver *driver)
Add a host driver to the master scene. The host is now owned by the Master Scene.
void startDriver(DtDriver *driver)
Start a driver driver modifying the scene.
Definition DtEntitySettingsItems.h:195
A configuration of a menu layout. A menu configuration manages an ordered collection of menu paths th...
Definition DtMenuConfiguration.h:44
A configuration of the pages in the gui.
Definition DtPageConfiguration.h:26
static DtQtMenuAssembler & instance(DtDe &de)
Get an instance of the assembler.
static DtQtToolbarAssembler & instance(DtDe &de)
Get an instance of the assembler.
A configuration of the toolbar layout.
Definition DtToolbarConfiguration.h:26
void addToolbarPath(const DtToolbarPath &)
Adds the toolbar path (as well as its entire family).
The base class for VR-Vantage toolbars.
Definition DtToolbar.h:27
static ToolbarPathBuilder toolbar(const std::string &name)
This owns a list of display engine configurations.
Definition DtVrvApplicationConfiguration.h:33
const UIConfiguration & masterModeUIConfiguration() const
void setMasterModePageConfiguration(const DtPageConfiguration &pageConfig)
void setMasterModeToolbarConfiguration(const DtToolbarConfiguration &toolbarConfig)
void setMasterModeMenuConfiguration(const DtMenuConfiguration &menuConfig)
DT_DLL_EXAMPLEACCESSORY void init(makVrv::DtDe &de)
Contains DLL export macros for the exampleBallistics plugin.
DT_DLL_EXAMPLEPROJECTILE void installDriver(makVrv::DtDe &de)
DT_DE_PLUGIN_EXPORT_MACRO bool initDeModule(makVrv::DtDe *de)
Contains DtCreateSensorFieldOfViewCommand and DtCreateSensorFieldOfViewCommandCreator class declarati...
Definition DtGridLinesSettingsRecord.h:16
bool myShowStartupScreen
Definition DtVrvApplicationConfiguration.h:42

DtExampleBallisticsDriver.cxx

/*****************************************************************************
* Copyright (c) 2026 MAK Technologies, Inc.
* All rights reserved.
*****************************************************************************/
#include <vrvCore/DtDe.h>
#include <algorithm>
#include <vector>
// Use the VR-Vantage namespace.
// All classes in VR-Vantage are in this namespace.
using namespace makVrv;
//#define USE_GEOCENTRIC_TERRAIN
#define SHOW_GRAVITY_ONLY
#define SHOW_NO_FORCES
struct DtBallisticShotDefinition
{
DtVector myPosition;
DtVector myVelocity;
double myMaxDistance;
int myCount;
double myRateOfFire;
int myTracerInterval;
DtTracerDefinition myTracerDefinition;
std::string myArcLabel;
};
namespace
{
// Scales a raw muzzle velocity by the shared velocity scale factor
// (1.0 keeps the original speed; 0.25 fires four times slower).
DtVector DtScaledMuzzleVelocity(const DtVector& rawVelocity)
{
const double velocityScale = 0.25;
DtVector scaled;
DtVecScale(rawVelocity, velocityScale, scaled);
return scaled;
}
// Returns the three per-key shot definitions, built once. The muzzle
// position, velocity, and range vary by terrain type, selected at compile
// time by USE_GEOCENTRIC_TERRAIN.
const std::vector<DtBallisticShotDefinition>& DtBallisticShotDefinitions()
{
static const std::vector<DtBallisticShotDefinition> theDefinitions = []()
{
std::vector<DtBallisticShotDefinition> definitions;
#ifdef USE_GEOCENTRIC_TERRAIN
// Near Ala Moana, Honolulu, Hawaii (geocentric ECEF coordinates).
definitions.push_back({
DtVector(-5506817.128206, -2240932.121720, 2301773.052875),
DtScaledMuzzleVelocity(DtVector(-365.649048, 761.991699, -115.231880)),
258.1192626953, 15, 750.0 / 60.0, 5,
definitions.push_back({
DtVector(-5506976.325637, -2240559.782043, 2301862.716279),
DtScaledMuzzleVelocity(DtVector(218.335922, -614.219727, -550.156860)),
198.2325134277, 3, 550.0 / 60.0, 1,
DtTracerDefinition::red(), "Shot N" });
definitions.push_back({
DtVector(-5506878.107655, -2240862.760257, 2301961.459429),
DtScaledMuzzleVelocity(DtVector(-132.207169, 511.155518, -669.962891)),
272.3383483887, 3, 550.0 / 60.0, 2,
DtTracerDefinition::green(), "Shot M" });
#else
// Ground_DB II ECEF coordinates (from DIS fire PDUs).
definitions.push_back({
DtVector(-521.924, -845.68, 61.8551),
DtScaledMuzzleVelocity(DtVector(789.674, 302.878, -110.854)),
318.4730529785, 15, 750.0 / 60.0, 5,
definitions.push_back({
DtVector(-164.228, -268.048, 36.5075),
DtScaledMuzzleVelocity(DtVector(-128.745, -938.665, -32.1992)),
470.5762329102, 3, 550.0 / 60.0, 1,
DtTracerDefinition::red(), "Shot N" });
definitions.push_back({
DtVector(-153.321, -270.162, 36.5229),
DtScaledMuzzleVelocity(DtVector(-135.452, -841.676, -29.0304)),
469.6385498047, 3, 550.0 / 60.0, 2,
DtTracerDefinition::green(), "Shot M" });
#endif
return definitions;
}();
return theDefinitions;
}
}
class DtBallisticFireEventProcessor : public DtEventProcessorInterface
{
public:
DtBallisticFireEventProcessor(bool& fireRequestedB, bool& fireRequestedN, bool& fireRequestedM,
bool& previewRequestedB, bool& previewRequestedN, bool& previewRequestedM,
bool& removeRequested)
: myFireRequestedB(fireRequestedB)
, myFireRequestedN(fireRequestedN)
, myFireRequestedM(fireRequestedM)
, myPreviewRequestedB(previewRequestedB)
, myPreviewRequestedN(previewRequestedN)
, myPreviewRequestedM(previewRequestedM)
, myRemoveRequested(removeRequested)
, myClassName("DtBallisticFireEventProcessor")
{
}
virtual ~DtBallisticFireEventProcessor() {}
virtual bool processMouseEvent(const DtMouseEvent& ev, DtChannel& channel) { return false; }
virtual bool processKeyboardEvent(const DtKeyEvent& ev, DtChannel& channel)
{
if (ev.eventType() != DtKeyEvent::KEY_DOWN)
{
return false;
}
DtKeyState::KeyType key = ev.keyState().keyType();
DtKeyState::KeyModifier modifiers = ev.keyState().modifiers();
if (modifiers == DtKeyState::NO_MODIFIER)
{
if (key == DtKeyState::KEY_B)
{
myFireRequestedB = true;
return true;
}
if (key == DtKeyState::KEY_N)
{
myFireRequestedN = true;
return true;
}
if (key == DtKeyState::KEY_M)
{
myFireRequestedM = true;
return true;
}
if (key == DtKeyState::KEY_R)
{
myRemoveRequested = true;
return true;
}
}
else if (modifiers == DtKeyState::SHIFT_MODIFIER)
{
if (key == DtKeyState::KEY_B)
{
myPreviewRequestedB = true;
return true;
}
if (key == DtKeyState::KEY_N)
{
myPreviewRequestedN = true;
return true;
}
if (key == DtKeyState::KEY_M)
{
myPreviewRequestedM = true;
return true;
}
}
return false;
}
virtual const std::string& className() { return myClassName; }
protected:
bool& myFireRequestedB;
bool& myFireRequestedN;
bool& myFireRequestedM;
bool& myPreviewRequestedB;
bool& myPreviewRequestedN;
bool& myPreviewRequestedM;
bool& myRemoveRequested;
std::string myClassName;
};
: makVrv::DtDriver( am, "DtExampleBallisticsDriver" )
, myCoordinateSystem( nullptr )
, myWindSpeed( 0.0f )
, myWindDirection( 0.0f )
, myFireRequestedB( false )
, myFireRequestedN( false )
, myFireRequestedM( false )
, myPreviewRequestedB( false )
, myPreviewRequestedN( false )
, myPreviewRequestedM( false )
, myRemoveRequested( false )
, myEventProcessor( nullptr )
{
// Going forward we recommend locally cloning and keeping the coordinate system in sync
// with signals for ensuring thread safe operations on client side
myCoordinateSystem = am.de().sharedState().coordinateSystem().clone();
if (myCoordinateSystem == nullptr)
{
DtTHROW_NEW(DtCorruptedState, "myDe.sharedState().coordinateSystem().clone() failed.");
}
myConnections += DtDeSharedStateSignaler::instance( am.de() ).signal_coordinateSystemChanged.connect(
slot_coordinateSystemChanged();
}
{
}
const std::string& DtExampleBallisticsDriver::className() const
{
static std::string name = "DtExampleBallisticsDriver";
return name;
}
{
#ifdef USE_GEOCENTRIC_TERRAIN
// Load the geocentric terrain programatically.
DtScene& sceneDriver = myAgentManager.de().scene();
std::string groundDbPath = myAgentManager.de().dePathConfiguration().sharedDataPath();
groundDbPath += "/TerrainData/TerrainConfiguration/Ala Moana.mtf";
sceneDriver.loadTerrain( groundDbPath );
#else
// Load Ground_DB II programatically.
DtScene& sceneDriver = myAgentManager.de().scene();
std::string groundDbPath = myAgentManager.de().dePathConfiguration().sharedDataPath();
groundDbPath += "/TerrainData/TerrainConfiguration/Ground_DB II.mtf";
sceneDriver.loadTerrain( groundDbPath );
#endif
DtSkyObjectSignaler& skySignal = DtSkyObjectSignaler::instance(myAgentManager.de());
myConnections.manageConnection(
skySignal.signal_windSpeedChanged.connect(
this, boost::placeholders::_1)));
myConnections.manageConnection(
skySignal.signal_windDirectionChanged.connect(
this, boost::placeholders::_1)));
// Register key bindings: 'B'/'N'/'M' fire tracer bursts, Shift+'B'/'N'/'M'
// preview the predicted trajectory, and 'R' removes everything.
myEventProcessor = new DtBallisticFireEventProcessor(
DtInputDriver& inputDriver = myAgentManager.de().driverManager().inputDriver();
return true;
}
{
{
DtInputDriver& inputDriver = myAgentManager.de().driverManager().inputDriver();
myEventProcessor = nullptr;
}
// Remove any predicted trajectory arcs still being displayed.
return true;
}
{
const std::vector<DtBallisticShotDefinition>& definitions = DtBallisticShotDefinitions();
// Fire a tracer burst for each fire key pressed this frame. The B/N/M keys
// map to shot indices 0/1/2; guard each access on the table size so a future
// change to the shot table cannot index out of range.
{
if (definitions.size() > 0)
{
fireShot(definitions[0]);
}
}
{
if (definitions.size() > 1)
{
fireShot(definitions[1]);
}
}
{
if (definitions.size() > 2)
{
fireShot(definitions[2]);
}
}
// Preview the predicted trajectory for each Shift+key pressed this frame.
{
if (definitions.size() > 0)
{
predictShot(definitions[0]);
}
}
{
if (definitions.size() > 1)
{
predictShot(definitions[1]);
}
}
{
if (definitions.size() > 2)
{
predictShot(definitions[2]);
}
}
// Remove all fired bursts and predicted arcs when 'R' is pressed.
{
if (!myFiredIdentifiers.empty())
{
DtBallisticManager& ballisticManager = DtBallisticManager::instance(myAgentManager.de());
for (const auto& identifier : myFiredIdentifiers)
{
ballisticManager.removeProjectiles(identifier);
}
}
}
return true;
}
{
myWindSpeed = metersPerSecond;
}
{
myWindDirection = radians;
}
DtVector position, DtVector& east, DtVector& north, DtVector& up)
{
{
return;
}
DtCoordinateConverter* converter = myCoordinateSystem->converter();
if (!converter)
{
return;
}
converter->setupTopoFrame(position);
converter->enuToCig_vecTrans(DtVector(1.0, 0.0, 0.0), east);
converter->enuToCig_vecTrans(DtVector(0.0, 1.0, 0.0), north);
converter->enuToCig_vecTrans(DtVector(0.0, 0.0, 1.0), up);
}
{
myAgentManager.de().sharedState().coordinateSystem().type(),
myAgentManager.de().sharedState().coordinateSystem().parameters() );
}
void DtExampleBallisticsDriver::predictShot(const DtBallisticShotDefinition& def)
{
// Remove any existing arcs for this shot so a re-preview (for example after
// a wind change) replaces rather than duplicates them.
double muzzleVelocity = std::sqrt(def.myVelocity.magnitudeSquared());
if (muzzleVelocity <= 0.0)
{
return;
}
double lifeTime = (def.myMaxDistance / muzzleVelocity) * 2.0;
double timeStep = lifeTime / 100.0;
// Build the bullet from the same parameters used to fire the burst.
DtBulletDefinition bulletDef;
bulletDef.setMuzzleVelocity(muzzleVelocity);
bulletDef.setMaxDistance(def.myMaxDistance);
bulletDef.setMaxLifetime(lifeTime);
bulletDef.setMass(0.01);
bulletDef.setCaliber(5.56);
// Build the local ENU frame at the muzzle position.
DtVector east(1.0, 0.0, 0.0);
DtVector north(0.0, 1.0, 0.0);
DtVector up(0.0, 0.0, 1.0);
computeDirectionVectors(def.myPosition, east, north, up);
DtCoordinateFrame frame(
dvec3(east.x(), east.y(), east.z()),
dvec3(north.x(), north.y(), north.z()),
dvec3(up.x(), up.y(), up.z()));
// Start the prediction at the exact muzzle position so the previewed arc
// lines up with the fired tracers, which launch from def.myPosition.
dvec3 origin = dvec3(def.myPosition.x(), def.myPosition.y(), def.myPosition.z());
dvec3 velocity = dvec3(def.myVelocity.x(), def.myVelocity.y(), def.myVelocity.z());
velocity.normalize();
velocity *= bulletDef.muzzleVelocity();
DtDe& de = myAgentManager.de();
// How long a previewed arc stays on screen, in seconds, before it
// self-expires. The 'R' key still clears arcs on demand before this elapses.
const float previewAliveTime = 10.0f;
// Predicts one trajectory and stitches it into a coloured multi-line shape.
auto drawArc = [&](const std::string& label, double red, double green, double blue,
const DtBallisticEnvironment& environment)
{
DtTrajectoryPredictor trajectoryPredictor;
std::vector<DtTrajectoryPoint> trajectory =
trajectoryPredictor.predictTrajectory(origin, velocity, bulletDef, environment, lifeTime, timeStep);
if (trajectory.empty())
{
return;
}
DtGeom3dLinesComponent* multiLine = de.renderer().debugShapes().addMultiLine(label, previewAliveTime);
if (!multiLine)
{
return;
}
multiLine->setCurrentColor(red, green, blue, 1.0);
multiLine->setCurrentStartColor(red, green, blue, 1.0);
multiLine->setCurrentEndColor(red, green, blue, 1.0);
DtVector pointA(0.0, 0.0, 0.0);
DtVector pointB(0.0, 0.0, 0.0);
int index = -1;
for (const DtTrajectoryPoint& point : trajectory)
{
pointB = pointA;
pointA = DtVector(point.position().x, point.position().y, point.position().z);
if (index == -1)
{
index = 0;
continue;
}
multiLine->setLine(pointA, pointB, index);
++index;
}
};
// Wind and gravity (green).
{
dvec3 windVelocityEnu(
0.0);
dvec3 windVelocityInFrame =
frame.right() * windVelocityEnu.x +
frame.forward() * windVelocityEnu.y +
frame.up() * windVelocityEnu.z;
DtBallisticEnvironment environment;
environment.setCoordinateFrame(frame);
environment.setGravity(frame.up() * -9.81);
environment.setWindVelocity(windVelocityInFrame);
drawArc(def.myArcLabel + " Wind+Gravity", 0.0, 1.0, 0.0, environment);
}
#ifdef SHOW_GRAVITY_ONLY
// Gravity only (yellow).
{
DtBallisticEnvironment environment;
environment.setGravity(frame.up() * -9.81);
environment.setWindVelocity(dvec3(0.0, 0.0, 0.0));
drawArc(def.myArcLabel + " Gravity", 1.0, 1.0, 0.0, environment);
}
#endif
#ifdef SHOW_NO_FORCES
// No forces (red).
{
DtBallisticEnvironment environment;
environment.setGravity(dvec3(0.0, 0.0, 0.0));
environment.setWindVelocity(dvec3(0.0, 0.0, 0.0));
drawArc(def.myArcLabel + " No Forces", 1.0, 0.0, 0.0, environment);
}
#endif
// Remember this shot so its arcs can be re-predicted when the wind changes.
if (std::find(myActivePreviews.begin(), myActivePreviews.end(), &def) == myActivePreviews.end())
{
myActivePreviews.push_back(&def);
}
}
void DtExampleBallisticsDriver::fireShot(const DtBallisticShotDefinition& def)
{
DtBallisticManager::BallisticData ballisticData;
ballisticData.myPosition = def.myPosition;
ballisticData.myVelocity = def.myVelocity;
ballisticData.myMuzzleVelocity = std::sqrt(def.myVelocity.magnitudeSquared());
ballisticData.myMaxDistance = def.myMaxDistance;
ballisticData.myMaxLifetime = (def.myMaxDistance / ballisticData.myMuzzleVelocity) * 2.0;
ballisticData.myMass = 0.01;
ballisticData.myCaliber = 5.56;
ballisticData.myCount = def.myCount;
ballisticData.myRateOfFire = def.myRateOfFire;
ballisticData.myTracerInterval = def.myTracerInterval;
ballisticData.myTracerDefinition = def.myTracerDefinition;
ballisticData.myProximitySoundGroup = "Bullet Flyby";
DtBallisticManager::BallisticIdentifier identifier;
identifier.mySourceId = std::to_string(myAgentManager.createNewUniqueId());
myFiredIdentifiers.push_back(identifier);
DtBallisticManager& ballisticManager = DtBallisticManager::instance(myAgentManager.de());
ballisticManager.createProjectiles(identifier, ballisticData);
}
void DtExampleBallisticsDriver::removeArcsFor(const DtBallisticShotDefinition& def)
{
DtDe& de = myAgentManager.de();
de.renderer().debugShapes().removeMultiLine(def.myArcLabel + " Wind+Gravity");
de.renderer().debugShapes().removeMultiLine(def.myArcLabel + " Gravity");
de.renderer().debugShapes().removeMultiLine(def.myArcLabel + " No Forces");
}
{
// Copy the active list first because predictShot() appends to it; re-predict
// each displayed shot so the arcs reflect the latest wind speed/direction.
std::vector<const DtBallisticShotDefinition*> active = myActivePreviews;
for (const DtBallisticShotDefinition* def : active)
{
predictShot(*def);
}
}
{
for (const DtBallisticShotDefinition& def : DtBallisticShotDefinitions())
{
}
}
Contains makVrv:DtAgentManager class.
Contains makVrv::DtBallisticEnvironment class.
Contains the DtBallisticManager class declaration.
Contains makVrv::DtBulletDefinition class.
Contains makVrv::DtCoordinateFrame class.
Contains makVrv::DtDeSharedState class.
Contains makVrv::DtDeSharedStateSignaler class.
Contains the makVrv::DtDebugShapes class declaration.
Interface for an event processor for a channel.
#define dvec3
Definition DtGlslToDtDefines.h:17
Contains makVrv::DtInputDriver class.
This file contains the declaration for the class DtKeyEvent.
Contains makVrv::DtRenderer class.
Contains makVrv::DtScene class.
Contains makVrv::DtSkyObject class.
Contains makVrv::DtTrajectoryPredictor class.
DtExampleBallisticsDriver(makVrv::DtAgentManager &am)
Constructor.
virtual void slot_windSpeedChanged(float metersPerSecond)
Handles a wind speed change; re-predicts any arcs currently on screen.
std::vector< const DtBallisticShotDefinition * > myActivePreviews
Shot definitions whose arcs are currently displayed, so they can be re-predicted when the wind change...
Definition DtExampleBallisticsDriver.h:124
virtual bool onStop()
Performs shutdown logic for the driver.
virtual void computeDirectionVectors(DtVector position, DtVector &east, DtVector &north, DtVector &up)
Computes local direction vectors for the given world position.
virtual void slot_windDirectionChanged(float radians)
Handles a wind direction change; re-predicts any arcs currently on screen.
bool myFireRequestedB
True if 'B' was pressed this frame (fire orange burst).
Definition DtExampleBallisticsDriver.h:108
bool myPreviewRequestedB
True if Shift+'B' was pressed this frame (preview orange shot).
Definition DtExampleBallisticsDriver.h:112
virtual bool onTick()
Performs update logic for the driver.
bool myPreviewRequestedM
True if Shift+'M' was pressed this frame (preview green shot).
Definition DtExampleBallisticsDriver.h:114
virtual const std::string & className() const
Returns the driver's class name.
void redrawActivePreviews()
Re-predicts every arc currently on screen so it reflects the latest wind speed and direction.
void removeArcsFor(const DtBallisticShotDefinition &def)
Removes the three predicted arcs previously drawn for one shot.
makVrv::DtSignalConnectionManager myConnections
Manages signal/slot lifetime connections.
Definition DtExampleBallisticsDriver.h:100
virtual void slot_coordinateSystemChanged()
Handles a coordinate-system change.
float myWindSpeed
Current wind speed in metres per second.
Definition DtExampleBallisticsDriver.h:105
virtual ~DtExampleBallisticsDriver()
Destructor.
void clearPredictedArcs()
Removes every predicted trajectory arc previously drawn by predictShot().
makVrv::DtEventProcessorInterface * myEventProcessor
Event processor for input handling.
Definition DtExampleBallisticsDriver.h:126
void fireShot(const DtBallisticShotDefinition &def)
Fires a GPU tracer burst described by the given shot definition.
std::deque< makVrv::DtBallisticManager::BallisticIdentifier > myFiredIdentifiers
Identifiers of previously fired bursts, stored for removal via the 'R' key.
Definition DtExampleBallisticsDriver.h:119
makVrv::DtCoordinateSystem * myCoordinateSystem
Local copy of the system-wide coordinate system, kept for thread safety.
Definition DtExampleBallisticsDriver.h:103
float myWindDirection
Current wind direction in radians.
Definition DtExampleBallisticsDriver.h:106
bool myPreviewRequestedN
True if Shift+'N' was pressed this frame (preview red shot).
Definition DtExampleBallisticsDriver.h:113
bool myFireRequestedN
True if 'N' was pressed this frame (fire red burst).
Definition DtExampleBallisticsDriver.h:109
bool myRemoveRequested
True if 'R' was pressed this frame (remove all).
Definition DtExampleBallisticsDriver.h:116
virtual bool onStart()
Performs startup logic for the driver.
bool myFireRequestedM
True if 'M' was pressed this frame (fire green burst).
Definition DtExampleBallisticsDriver.h:110
void predictShot(const DtBallisticShotDefinition &def)
Draws the predicted trajectory arcs for the given shot without firing. Any arcs already shown for thi...
The DtAgentManager manages the distributed scene object framework. This includes the objects and upda...
Definition DtAgentManager.h:39
DtDe & de()
Get the scene manager's Ig object.
Definition DtAgentManager.h:107
virtual void setWindVelocity(const dvec3 &wind)
Sets the wind velocity vector.
virtual void setGravity(const dvec3 &gravity)
Sets the gravity acceleration vector.
virtual void setCoordinateFrame(const DtCoordinateFrame &frame)
Sets the coordinate frame.
virtual void removeProjectiles(const BallisticIdentifier &id)=0
Cancels and removes all active projectiles fired by the given entity.
virtual void createProjectiles(const BallisticIdentifier &id, const BallisticData &data)=0
Spawns a burst of projectiles described by the given data.
virtual void setMaxLifetime(double lifetime)
Sets the maximum lifetime in seconds.
virtual void setMass(double mass)
Sets the mass in kilograms.
virtual void setMaxDistance(double distance)
Sets the maximum travel distance in metres.
virtual void setMuzzleVelocity(double velocity)
Sets the muzzle velocity in metres per second.
virtual void setCaliber(double caliber)
Sets the caliber in millimetres.
virtual double muzzleVelocity() const
Returns the muzzle velocity in metres per second.
virtual void setupTopoFrame(const DtVector &truth)
virtual void enuToCig_vecTrans(const DtVector &enuVec, DtVector &cigVec) const
convert to Cig vector from Enu vector
virtual DtRenderer & renderer() const
Get the renderer.
static DtDeSharedStateSignaler & instance(DtDe &de)
Get an instance used to emit, or to connect.
virtual void removeMultiLine(const std::string name)
virtual DtGeom3dLinesComponent * addMultiLine(const std::string name, float aliveTime=5.0f)
The DtDriver is an abstract class. Developers derive from this to create logic that "directs" things ...
Definition DtDriver.h:32
DtAgentManager & myAgentManager
Definition DtDriver.h:190
The DtEventProcessorInterface defines the generic interface for classes which handle input events....
Definition DtEventProcessorInterface.h:35
virtual void setCurrentColor(float r, float g, float b, float a)
virtual void setLine(const DtVector &pointA, const DtVector &pointB, LineHandle handle)
virtual void setCurrentStartColor(float r, float g, float b, float a)
virtual void setCurrentEndColor(float r, float g, float b, float a)
virtual void removeEventProcessor(DtEventProcessorInterface *epi)
virtual void addEventProcessorToFront(DtEventProcessorInterface *epi)
const DtKeyState & keyState() const
Get the state object associated with this event.
Definition DtKeyEvent.h:44
DtKeyEvent::KeyEventType eventType() const
Get the event type this event.
Definition DtKeyEvent.h:59
virtual KeyModifier modifiers() const
get the entire modifier vector instead of using the boolean accessors
virtual KeyType keyType() const
Get the type of key.
DtDebugShapes & debugShapes()
Get the debug shapes object for use with debugging geometry shapes.
bool loadTerrain(const DtUnicode &filePath)
Load the terrain from a file.
boost::signalslib::signal< void(float metersPerSecond)> signal_windSpeedChanged
Signal raised when the wind speed changes.
Definition DtSkyObject.h:258
boost::signalslib::signal< void(float radians) > signal_windDirectionChanged
Signal raised the wind direction changes.
Definition DtSkyObject.h:261
Visual and physical appearance parameters for a single tracer round type.
Definition DtTracerDefinition.h:33
static DtTracerDefinition red()
Red tracer preset (5.56mm NATO style, e.g. M196).
static DtTracerDefinition orangeHeavy()
Heavy-caliber orange tracer preset (.50 BMG style).
static DtTracerDefinition green()
Green tracer preset (7.62mm class, e.g. 57-N-231P).
virtual std::vector< DtTrajectoryPoint > predictTrajectory(const dvec3 &startPosition, const dvec3 &startVelocity, const DtBulletDefinition &bullet, const DtBallisticEnvironment &env, double maxTime, double timeStep)
Predicts the trajectory for a given duration.
void normalize(void)
normalize this vector in place
Definition DtVector3.h:167
double myMass
Mass of the projectile in kilograms.
Definition DtBallisticManager.h:59
double myMaxDistance
Maximum travel distance in meters before the projectile is despawned.
Definition DtBallisticManager.h:56
DtVector myPosition
World-space starting position of the projectile (meters).
Definition DtBallisticManager.h:44
int myTracerInterval
Tracer interval: every Nth round is a tracer; 0 = no tracers.
Definition DtBallisticManager.h:74
DtTracerDefinition myTracerDefinition
Visual and physical appearance of tracer rounds for this burst.
Definition DtBallisticManager.h:77
int myCount
Number of rounds in the burst; must be >= 1.
Definition DtBallisticManager.h:65
double myCaliber
Caliber (diameter) of the projectile in millimeters.
Definition DtBallisticManager.h:62
double myMaxLifetime
Maximum lifetime in seconds before the projectile is automatically despawned.
Definition DtBallisticManager.h:53
std::string myProximitySoundGroup
Name of the sound group for proximity audio. Matches a DtBallisticSoundGroup::myName in DtBallisticSo...
Definition DtBallisticManager.h:82
DtVector myVelocity
World-space initial velocity vector at the moment of firing (m/s).
Definition DtBallisticManager.h:47
double myMuzzleVelocity
Initial speed of the projectile leaving the barrel (m/s).
Definition DtBallisticManager.h:50
double myRateOfFire
Rate of fire in rounds per second; must be > 0.
Definition DtBallisticManager.h:71
DtString mySourceId
Unique string ID of the entity that fired the burst.
Definition DtBallisticManager.h:34

DtExampleBallisticsDriver.h

/*****************************************************************************
* Copyright (c) 2026 MAK Technologies, Inc.
* All rights reserved.
*****************************************************************************/
#pragma once
#include <deque>
#include <vector>
#include <matrix/vlVector.h>
#include <boost/bind/bind.hpp>
#include <boost/bind/placeholders.hpp>
namespace makVrv
{
class DtCoordinateSystem;
class DtEventProcessorInterface;
}
struct DtBallisticShotDefinition;
{
public:
virtual const std::string& className() const;
virtual bool onStart();
virtual bool onStop();
virtual bool onTick();
protected:
virtual void computeDirectionVectors(DtVector position, DtVector& east, DtVector& north, DtVector& up);
void fireShot(const DtBallisticShotDefinition& def);
void predictShot(const DtBallisticShotDefinition& def);
void removeArcsFor(const DtBallisticShotDefinition& def);
virtual void slot_windSpeedChanged(float metersPerSecond);
virtual void slot_windDirectionChanged(float radians);
protected:
float myWindSpeed;
std::deque<makVrv::DtBallisticManager::BallisticIdentifier> myFiredIdentifiers;
std::vector<const DtBallisticShotDefinition*> myActivePreviews;
};
Contains makVrv:DtDriver class.
Base class to provide boost signal/slot management.
The DtCoordinateSystem is used to manage the current coordinate system of the scene.
Definition DtCoordinateSystem.h:41
Class to manage disconnection of boost connections on deletion.
Definition DtSignalConnectionManager.h:21

[<< Examples] [Home] [Top of Page]