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.
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.
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".
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.
#include <algorithm>
#include <vector>
#define SHOW_GRAVITY_ONLY
#define SHOW_NO_FORCES
struct DtBallisticShotDefinition
{
DtVector myPosition;
DtVector myVelocity;
double myMaxDistance;
int myCount;
double myRateOfFire;
int myTracerInterval;
std::string myArcLabel;
};
namespace
{
DtVector DtScaledMuzzleVelocity(const DtVector& rawVelocity)
{
const double velocityScale = 0.25;
DtVector scaled;
DtVecScale(rawVelocity, velocityScale, scaled);
return scaled;
}
const std::vector<DtBallisticShotDefinition>& DtBallisticShotDefinitions()
{
static const std::vector<DtBallisticShotDefinition> theDefinitions = []()
{
std::vector<DtBallisticShotDefinition> definitions;
#ifdef USE_GEOCENTRIC_TERRAIN
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,
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,
#else
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,
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,
#endif
return definitions;
}();
return theDefinitions;
}
}
{
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)
{
{
return false;
}
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;
};
, myCoordinateSystem( nullptr )
, myWindSpeed( 0.0f )
, myWindDirection( 0.0f )
, myFireRequestedB( false )
, myFireRequestedN( false )
, myFireRequestedM( false )
, myPreviewRequestedB( false )
, myPreviewRequestedN( false )
, myPreviewRequestedM( false )
, myRemoveRequested( false )
, myEventProcessor( nullptr )
{
myCoordinateSystem = am.
de().sharedState().coordinateSystem().clone();
if (myCoordinateSystem == nullptr)
{
DtTHROW_NEW(DtCorruptedState, "myDe.sharedState().coordinateSystem().clone() failed.");
}
slot_coordinateSystemChanged();
}
{
}
{
static std::string name = "DtExampleBallisticsDriver";
return name;
}
{
#ifdef USE_GEOCENTRIC_TERRAIN
std::string groundDbPath =
myAgentManager.de().dePathConfiguration().sharedDataPath();
groundDbPath += "/TerrainData/TerrainConfiguration/Ala Moana.mtf";
#else
std::string groundDbPath =
myAgentManager.de().dePathConfiguration().sharedDataPath();
groundDbPath += "/TerrainData/TerrainConfiguration/Ground_DB II.mtf";
#endif
DtSkyObjectSignaler& skySignal = DtSkyObjectSignaler::instance(
myAgentManager.de());
this, boost::placeholders::_1)));
this, boost::placeholders::_1)));
DtInputDriver& inputDriver =
myAgentManager.de().driverManager().inputDriver();
return true;
}
{
{
DtInputDriver& inputDriver =
myAgentManager.de().driverManager().inputDriver();
}
return true;
}
{
const std::vector<DtBallisticShotDefinition>& definitions = DtBallisticShotDefinitions();
{
if (definitions.size() > 0)
{
}
}
{
if (definitions.size() > 1)
{
}
}
{
if (definitions.size() > 2)
{
}
}
{
if (definitions.size() > 0)
{
}
}
{
if (definitions.size() > 1)
{
}
}
{
if (definitions.size() > 2)
{
}
}
{
{
DtBallisticManager& ballisticManager = DtBallisticManager::instance(
myAgentManager.de());
{
}
}
}
return true;
}
{
}
{
}
DtVector position, DtVector& east, DtVector& north, DtVector& up)
{
{
return;
}
if (!converter)
{
return;
}
}
{
}
{
double muzzleVelocity = std::sqrt(def.myVelocity.magnitudeSquared());
if (muzzleVelocity <= 0.0)
{
return;
}
double lifeTime = (def.myMaxDistance / muzzleVelocity) * 2.0;
double timeStep = lifeTime / 100.0;
DtBulletDefinition bulletDef;
DtVector east(1.0, 0.0, 0.0);
DtVector north(0.0, 1.0, 0.0);
DtVector up(0.0, 0.0, 1.0);
DtCoordinateFrame frame(
dvec3(east.x(), east.y(), east.z()),
dvec3(north.x(), north.y(), north.z()),
dvec3(up.x(), up.y(), up.z()));
dvec3 origin =
dvec3(def.myPosition.x(), def.myPosition.y(), def.myPosition.z());
dvec3 velocity =
dvec3(def.myVelocity.x(), def.myVelocity.y(), def.myVelocity.z());
const float previewAliveTime = 10.0f;
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;
}
if (!multiLine)
{
return;
}
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;
}
};
{
0.0);
dvec3 windVelocityInFrame =
frame.right() * windVelocityEnu.x +
frame.forward() * windVelocityEnu.y +
frame.up() * windVelocityEnu.z;
DtBallisticEnvironment environment;
drawArc(def.myArcLabel + " Wind+Gravity", 0.0, 1.0, 0.0, environment);
}
#ifdef SHOW_GRAVITY_ONLY
{
DtBallisticEnvironment environment;
drawArc(def.myArcLabel + " Gravity", 1.0, 1.0, 0.0, environment);
}
#endif
#ifdef SHOW_NO_FORCES
{
DtBallisticEnvironment environment;
drawArc(def.myArcLabel + " No Forces", 1.0, 0.0, 0.0, environment);
}
#endif
{
}
}
{
DtBallisticManager::BallisticData ballisticData;
ballisticData.
myCount = def.myCount;
DtBallisticManager::BallisticIdentifier identifier;
DtBallisticManager& ballisticManager = DtBallisticManager::instance(
myAgentManager.de());
}
{
}
{
for (const DtBallisticShotDefinition* def : active)
{
}
}
{
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
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)
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