Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

perf(ww3d2): batch translucent particles and draw every one

Olcay Seyganeabc3b175a7a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91ead4710..188d6375b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ found and fixed — EA's own, not port damage.**
- A slow moment costs you a dropped frame, not a slow game.
- Explosions no longer catch the picture. The first time each kind of fire, smoke or blast reached the screen, the game stopped for 25 to 60ms to prepare it, and the opening volley of a fight cost 300ms at once. That work is kept on disk and ships with the game, so it happens while the map loads, in about 3ms, and the worst frame of the same battle went from 141ms to 38ms.
- The price, build time and power figures on the command bar buttons stopped costing you frames. All the buttons shared one piece of text, so every figure on the bar was lettered from scratch every frame, about 33 of them. Each now keeps its own: a battle that averaged 14ms a frame averages 11.7ms, frames slower than 60 a second went from one in six to one in a hundred, and the old renderer gets about 0.8ms back too. The money readout was lettered again every frame as well, for a number that had not changed; it is lettered when the number moves. Over a whole battle the game now letters 163 pieces of text where it lettered 68,227.
+- A screen full of fire and smoke is cheaper to draw. Thirty Inferno Cannons shelling twenty Crusaders used to send the graphics card 459 separate batches of see-through effects a frame, mostly the same texture again and again, and the game looked up the same seven card settings from scratch for every one of them. Matching effects go out together now, and settings that have not changed are not looked up again: 177 batches, and the same battle went from 11.6ms a frame to 8.6ms. It is at 6.7ms now, since the game stopped preparing everything it draws a second time for a copy of the picture nobody sees. Nothing on screen changes, the effects are drawn in exactly the order they were.
+- Raise the particle limit as far as you like and every puff gets drawn. Past about sixteen thousand smoke and fire sprites on screen the game quietly stopped drawing the rest: a test with 68,000 of them showed barely a fifth. A test with 101,000 now draws all of them at 8.3ms a frame, and in 1,200 frames not one fell below 60 a second. The first version that drew them all took 22.4ms; the rest came from sorting and copying them far less and from sharing the work across every core of the processor.
- Every animation runs on a clock instead of counting frames.
- Briefing and cutscene subtitles hold long enough to read again.
- The radar's under-attack pulse throbs instead of strobing, and no longer ends early.
diff --git a/GeneralsMD/Code/Data/Scenarios/particles100k.txt b/GeneralsMD/Code/Data/Scenarios/particles100k.txt
new file mode 100644
index 000000000..9cd2e88f5
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/particles100k.txt
@@ -0,0 +1,20 @@
+# A hundred thousand particles on one screen, the same frame every run.
+#
+# No unit in the game carries an effect that holds more than a few hundred particles, so this does
+# not come out of an army. It places 370 copies of the cinematic jet exhaust in a block, each one
+# emitting three particles every other frame. The INI says they live three hundred frames, but a
+# particle whose alpha falls under 0.02 is retired early, so a system settles at about 273 rather
+# than 450: 250 of them held 68,284. The count climbs for 300 frames and holds from there.
+#
+# generals.exe -win -xres 1280 -yres 720 -quickstart -noshellmap -multiInstance -noFPSLimit
+# -msaa 0 -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2 -takeover
+# -seed 1 -maxframes 1200 -particlecap 150000
+# -scenario particles100k -camera 760 850 -logPrefix p100k_
+#
+# then grep the log for HEADLESS PARTICLECOST. Its two "not drawn" figures say how much of the scene
+# the renderer's own ceilings threw away: the sorting pool's 4096 nodes, and 512 particles a system.
+# Before the pool was flushed in batches, 250 systems here had 88,109 polygons a frame refused.
+#
+# <frame> particles <slot> <particle system> <count> <x> <y> [spacing]
+
+30 particles 0 CINE_JetLenzflareExhaust 370 760 850 25
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
index 0fc8a27e3..06dd84ecc 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
@@ -42,6 +42,7 @@
#include "WWMath/Matrix3D.h" ///< @todo Replace with our own matrix library
#include "Common/STLTypedefs.h"
+#include <vector>
/// @todo Once the client framerate is decoupled, the frame counters within will have to become time-based
@@ -162,6 +163,8 @@ protected:
};
+struct ParticleUpdateContext;
+
/**
* An individual particle created by a ParticleSystem.
* NOTE: Particles cannot exist without a parent particle system.
@@ -176,10 +179,9 @@ public:
Particle( ParticleSystem *system, const ParticleInfo *data );
- inline Bool update( void ); ///< update this particle's behavior - return false if dead
+ inline Bool update( const ParticleUpdateContext &context ); ///< update this particle's behavior - return false if dead
void doWindMotion( void ); ///< do wind motion (if present) from particle system
- void applyForce( const Coord3D *force ); ///< add the given acceleration
inline const Coord3D *getPosition( void ) { return &m_pos; }
inline Real getSize( void ) { return m_size; }
@@ -188,9 +190,9 @@ public:
inline const RGBColor *getColor( void ) { return &m_color; }
inline void setColor( RGBColor *color ) { m_color = *color; }
- inline Bool isInvisible( void ); ///< return true if this particle is invisible
- inline Bool isCulled (void) {return m_isCulled;} ///< return true if the particle falls off the edge of the screen
- inline void setIsCulled (Bool enable) { m_isCulled = enable;} ///< set particle to not visible because it's outside view frustum
+ inline Bool isInvisible( const ParticleUpdateContext &context ); ///< return true if this particle is invisible
+ inline Bool diesThisUpdate (void) const { return m_diesThisUpdate; } ///< marked dead by ParticleSystem::updateParticlesMark, not yet removed
+ inline void setDiesThisUpdate (Bool dies) { m_diesThisUpdate = dies; }
void controlParticleSystem( ParticleSystem *sys ) { m_systemUnderControl = sys; }
void detachControlledParticleSystem( void ) { m_systemUnderControl = NULL; }
@@ -237,7 +239,7 @@ protected:
Int m_colorTargetKey; ///< next index into key array
- Bool m_isCulled; ///< status of particle relative to screen bounds
+ Bool m_diesThisUpdate; ///< set on the job pool, read when the dead are removed; never saved
public:
Bool m_inSystemList;
Bool m_inOverallList;
@@ -559,6 +561,23 @@ public:
};
+/**
+ * What every particle of one system reads during one update, looked up once for the system. The
+ * particles used to ask their system for each of these, and the client for the frame twice, once
+ * a particle: with a hundred thousand of them Particle::update was 13% of the frame's samples.
+ */
+struct ParticleUpdateContext
+{
+ Coord3D driftVelocity;
+ Real gravity;
+ UnsignedInt clientFrame;
+ ParticleSystemInfo::ParticleShaderType shaderType;
+ ParticleSystemInfo::WindMotion windMotion;
+ Bool groundCollision; ///< the system asked for it and there is terrain to hit
+ Real groundBounce;
+ Real groundFriction;
+};
+
/**
* A ParticleSystemTemplate, used by the ParticleSystemManager to instantiate ParticleSystems.
@@ -649,6 +668,14 @@ public:
void attachToObject( const Object *obj ); ///< attach this particle system to an Object
virtual Bool update( Int localPlayerIndex ); ///< update this particle system, return false if dead
+
+ /// update() in three parts, for a system no other system reads or writes, so the manager can run
+ /// the middle one on the job pool: the emission serially in list order, the particles anywhere,
+ /// then the dead particles, the ground blob and the lifetime serially in list order again.
+ Bool isUpdateIndependent( void ) const;
+ Bool updateEmission( Int localPlayerIndex, Bool *keepSystem ); ///< FALSE when the update ended before the particles; *keepSystem is then the answer
+ void updateParticlesMark( void ); ///< job-safe: integrate every particle and mark the ones that die
+ Bool reapAndFinishUpdate( void ); ///< remove the marked particles and finish; return false if the system is done
void updateWindMotion( void ); ///< update wind motion
void setControlParticle( Particle *p ); ///< set control particle
@@ -769,6 +796,13 @@ protected:
void updateGroundShadow( const ParticleShadowBlob *blob );
void releaseGroundShadow( void ); ///< give the ground blob back, if we have one
+ void makeUpdateContext( ParticleUpdateContext *context ) const;
+ Bool finishUpdate( const ParticleShadowBlob *blob ); ///< the ground blob and the lifetime, after the particles
+
+ ParticleShadowBlob m_pendingShadowBlob; ///< the survivors' footprint, gathered by updateParticlesMark
+ Bool m_pendingCastsGroundShadow; ///< decided by updateEmission, where update() always decided it
+ UnsignedInt m_pendingDeaths; ///< particles updateParticlesMark marked; the reap stops once it has removed them
+
protected:
Particle * m_systemParticlesHead;
Particle * m_systemParticlesTail;
@@ -932,6 +966,7 @@ protected:
Int m_onScreenParticleCount; ///< number of particles displayed on screen per frame
UnsignedInt m_lastLogicFrameUpdate;
Int m_localPlayerIndex; ///<used to tell particle systems which particles can be skipped due to player shroud status
+ std::vector<ParticleSystem *> m_independentUpdates; ///< this update's systems whose particles go to the job pool; kept so it does not reallocate
private:
TemplateMap m_templateMap; ///< a hash map of all particle system templates
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
index 6c05f2bf7..1e6f26bcb 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
@@ -63,7 +63,8 @@ enum ScenarioActionType
SCENARIO_ACTION_ATTACKMOVE, ///< attackmove <slot> <selector> <position>
SCENARIO_ACTION_ATTACK, ///< attack <slot> <selector> <targetSlot> <targetSelector>
SCENARIO_ACTION_STOP, ///< stop <slot> <selector>
- SCENARIO_ACTION_ARRIVE ///< arrive <slot> <selector> <position> [radius]
+ SCENARIO_ACTION_ARRIVE, ///< arrive <slot> <selector> <position> [radius]
+ SCENARIO_ACTION_PARTICLES ///< particles <slot> <systemTemplate> <count> <position> [spacing]; slot is read and ignored
};
/// ScenarioAction::atStart when the position is plain numbers
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index 483e5c6af..6b5aece50 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -1236,6 +1236,28 @@ extern Real TheUIPostDrawMS; ///< ...of which the overlays and the HUD strips
extern Real TheWindowRepaintMS; ///< ...and the window system's repaint
extern Real TheStripGatherMS; ///< ...of the overlays, the production strip's sweep
extern Real TheStripDrawMS; ///< ...and the production strip's own drawing
+extern Real TheParticleUpdateMS; ///< GameClient.cpp: the three places particles cost
+extern Real TheParticleFillMS;
+extern Real TheTranslucentMS;
+extern UnsignedInt TheTranslucentDraws;
+extern UnsignedInt TheSortingPolygonsRefused;
+extern UnsignedInt TheParticlesPastGroupLimit;
+
+/** Particle cost summed over an unattended run, per drawn frame, for HEADLESS PARTICLECOST. */
+struct ParticleCostTotals
+{
+ Int m_passes;
+ double m_updateMS;
+ double m_fillMS;
+ double m_flushMS;
+ double m_draws;
+ double m_particles;
+ double m_onScreen;
+ double m_refusedPolygons;
+ double m_pastGroupLimit;
+ UnsignedInt m_peakParticles;
+};
+static ParticleCostTotals theParticleCost;
#endif
@@ -1399,6 +1421,9 @@ static void startFrameTimeStats( void )
theFrameTimes.reset();
theLogicTimes.reset();
theFrameTimesStarted = TRUE;
+#ifdef DEBUG_LOGGING
+ memset( &theParticleCost, 0, sizeof(theParticleCost) );
+#endif
}
static void reportFrameTimeStats( void )
@@ -1437,6 +1462,19 @@ static void reportFrameTimeStats( void )
lodName));
}
+#ifdef DEBUG_LOGGING
+ if( theParticleCost.m_passes > 0 )
+ {
+ const double passes = (double)theParticleCost.m_passes;
+ DEBUG_LOG(("HEADLESS PARTICLECOST: per drawn frame | update %.3f fill %.3f translucent flush %.3f ms | %.1f translucent draws | %.0f particles, %.0f on screen, peak %u | not drawn: %.0f polygons refused by the sorting pool, %.0f particles past the per-system limit\n",
+ theParticleCost.m_updateMS / passes, theParticleCost.m_fillMS / passes,
+ theParticleCost.m_flushMS / passes, theParticleCost.m_draws / passes,
+ theParticleCost.m_particles / passes, theParticleCost.m_onScreen / passes,
+ theParticleCost.m_peakParticles,
+ theParticleCost.m_refusedPolygons / passes, theParticleCost.m_pastGroupLimit / passes));
+ }
+#endif
+
if( theLogicTimes.count() > 0 )
{
DEBUG_LOG(("HEADLESS LOGICTIME: %d ticks | mean %.2f p50 %.2f p95 %.2f p99 %.2f p99.9 %.2f worst %.2f ms (frame %d) | over 33.3ms %d\n",
@@ -2052,6 +2090,8 @@ void GameEngine::update( void )
Int logicTicks = 0;
TheClientDrawMS = TheSceneDrawMS = TheUIDrawMS = TheUIPostDrawMS = TheWindowRepaintMS = 0.0f;
TheStripGatherMS = TheStripDrawMS = 0.0f;
+ TheParticleUpdateMS = TheParticleFillMS = TheTranslucentMS = 0.0f;
+ TheTranslucentDraws = TheSortingPolygonsRefused = TheParticlesPastGroupLimit = 0;
QueryPerformanceCounter( (LARGE_INTEGER *)&tClientStart );
#endif
@@ -2219,6 +2259,21 @@ void GameEngine::update( void )
fpsWinTotal += TheWindowRepaintMS;
fpsStripGatherTotal += TheStripGatherMS;
fpsStripDrawTotal += TheStripDrawMS;
+ if( theFrameTimesStarted && TheParticleSystemManager )
+ {
+ const UnsignedInt particles = TheParticleSystemManager->getParticleCount();
+ ++theParticleCost.m_passes;
+ theParticleCost.m_updateMS += TheParticleUpdateMS;
+ theParticleCost.m_fillMS += TheParticleFillMS;
+ theParticleCost.m_flushMS += TheTranslucentMS - TheParticleFillMS;
+ theParticleCost.m_draws += TheTranslucentDraws;
+ theParticleCost.m_refusedPolygons += TheSortingPolygonsRefused;
+ theParticleCost.m_pastGroupLimit += TheParticlesPastGroupLimit;
+ theParticleCost.m_particles += particles;
+ theParticleCost.m_onScreen += TheParticleSystemManager->getOnScreenParticleCount();
+ if( particles > theParticleCost.m_peakParticles )
+ theParticleCost.m_peakParticles = particles;
+ }
if( TheClientDrawMS > fpsDrawMax ) fpsDrawMax = TheClientDrawMS;
fpsLogicTotal += logicMS;
fpsLogicTicks += logicTicks;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp
index fd3591f96..4a74751a4 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp
@@ -119,6 +119,18 @@ Real TheWindowRepaintMS = 0.0f; ///< TheWindowManager->winRepaint() - the contro
//
Real TheStripGatherMS = 0.0f; ///< InGameUI::drawProductionStrip() - reading the queues
Real TheStripDrawMS = 0.0f; ///< InGameUI::drawProductionStrip() - drawing the rows
+//
+// Particles cost in three places that have nothing in common: the update that ages and emits them
+// once a logic frame, the fill that turns each system into quads, and the translucent flush that
+// sorts those quads with every other see-through polygon and draws them. GameEngine adds these up
+// over an unattended run and prints HEADLESS PARTICLECOST.
+//
+Real TheParticleUpdateMS = 0.0f; ///< ParticleSystemManager::update()
+Real TheParticleFillMS = 0.0f; ///< W3DParticleSystemManager::doParticles(), the system loop alone
+Real TheTranslucentMS = 0.0f; ///< DoParticles() and SortingRendererClass::Flush() together, fill included
+UnsignedInt TheTranslucentDraws = 0; ///< draw calls made by the fill and the flush
+UnsignedInt TheSortingPolygonsRefused = 0; ///< polygons the sorting pool had no room for, so never drawn
+UnsignedInt TheParticlesPastGroupLimit = 0; ///< on-screen particles doParticles cut at MAX_POINTS_PER_GROUP a system
#endif
//-------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
index 4c97a231c..99c631aa4 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
@@ -34,6 +34,7 @@
#include "Common/GameState.h"
#include "Common/INI.h"
#include "Common/PerfTimer.h"
+#include "Common/JobSystem.h"
#include "Common/ThingFactory.h"
#include "Common/GameLOD.h"
#include "Common/Xfer.h"
@@ -258,7 +259,7 @@ Particle::Particle( ParticleSystem *system, const ParticleInfo *info )
{
m_system = system;
- m_isCulled = FALSE;
+ m_diesThisUpdate = FALSE;
m_accel.x = 0.0f;
m_accel.y = 0.0f;
m_accel.z = 0.0f;
@@ -345,16 +346,6 @@ Particle::~Particle()
//DEBUG_ASSERTLOG(!(totalParticleCount % 100 == 0), ( "TotalParticleCount = %d\n", m_totalParticleCount ));
}
-// ------------------------------------------------------------------------------------------------
-/** Add the given acceleration */
-// ------------------------------------------------------------------------------------------------
-void Particle::applyForce( const Coord3D *force )
-{
- m_accel.x += force->x;
- m_accel.y += force->y;
- m_accel.z += force->z;
-}
-
// ------------------------------------------------------------------------------------------------
/** The soft blob a whole particle system drops on the terrain. See ParticleSys.h - free of
* ParticleSystem so the whole decision is testable without a renderer. */
@@ -549,8 +540,12 @@ Bool particleGroundBounce( Coord3D *pos, Coord3D *vel, Real groundZ,
// ------------------------------------------------------------------------------------------------
/** Update the behavior of an individual particle */
// ------------------------------------------------------------------------------------------------
-Bool Particle::update( void )
+Bool Particle::update( const ParticleUpdateContext &context )
{
+ // gravity goes into the acceleration, which is zero here, so the sum is exactly the gravity
+ if (context.gravity != 0.0f)
+ m_accel.z += context.gravity;
+
// integrate acceleration into velocity
m_vel.x += m_accel.x;
m_vel.y += m_accel.y;
@@ -561,13 +556,13 @@ Bool Particle::update( void )
m_vel.z *= m_velDamping;
// integrate velocity into position
- const Coord3D *driftVel = m_system->getDriftVelocity();
+ const Coord3D *driftVel = &context.driftVelocity;
m_pos.x += m_vel.x + driftVel->x;
m_pos.y += m_vel.y + driftVel->y;
m_pos.z += m_vel.z + driftVel->z;
// integrate the wind (if specified) into position
- ParticleSystemInfo::WindMotion windMotion = m_system->getWindMotion();
+ ParticleSystemInfo::WindMotion windMotion = context.windMotion;
// see if we should even do anything
if( windMotion != ParticleSystemInfo::WIND_MOTION_NOT_USED )
@@ -576,13 +571,13 @@ Bool Particle::update( void )
// hit the ground, if this system asked to. Only while descending, so the terrain is not
// sampled for every rising smoke puff in the scene.
// ponytail: terrain heightmap only - buildings, bridges and the water surface are not consulted
- if( m_system->isGroundCollision() && TheTerrainLogic != NULL
+ if( context.groundCollision
&& (m_vel.z + driftVel->z) < 0.0f )
{
Coord3D groundNormal;
const Real groundZ = TheTerrainLogic->getGroundHeight( m_pos.x, m_pos.y, &groundNormal );
particleGroundBounce( &m_pos, &m_vel, groundZ, &groundNormal,
- m_system->getGroundBounce(), m_system->getGroundFriction() );
+ context.groundBounce, context.groundFriction );
}
// update orientation
@@ -608,13 +603,13 @@ Bool Particle::update( void )
// Update alpha (if used)
//
- if (m_system->getShaderType() != ParticleSystemInfo::ADDITIVE)
+ if (context.shaderType != ParticleSystemInfo::ADDITIVE)
{
m_alpha += m_alphaRate;
if (m_alphaTargetKey < MAX_KEYFRAMES && m_alphaKey[ m_alphaTargetKey ].frame)
{
- if (TheGameClient->getFrame() - m_createTimestamp >= m_alphaKey[ m_alphaTargetKey ].frame)
+ if (context.clientFrame - m_createTimestamp >= m_alphaKey[ m_alphaTargetKey ].frame)
{
m_alpha = m_alphaKey[ m_alphaTargetKey ].value;
m_alphaTargetKey++;
@@ -640,7 +635,7 @@ Bool Particle::update( void )
if (m_colorTargetKey < MAX_KEYFRAMES && m_colorKey[ m_colorTargetKey ].frame)
{
- if (TheGameClient->getFrame() - m_createTimestamp >= m_colorKey[ m_colorTargetKey ].frame)
+ if (context.clientFrame - m_createTimestamp >= m_colorKey[ m_colorTargetKey ].frame)
{
// can't set, because of colorscale
// m_color = m_colorKey[ m_colorTargetKey ].color;
@@ -686,7 +681,7 @@ Bool Particle::update( void )
DEBUG_ASSERTCRASH( m_lifetimeLeft, ( "A particle has an infinite lifetime..." ));
// if we've gone totally invisible, destroy ourselves
- if (isInvisible())
+ if (isInvisible( context ))
return false;
return true;
}
@@ -784,9 +779,9 @@ ParticlePriorityType Particle::getPriority( void )
// ------------------------------------------------------------------------------------------------
/** Return true if this particle is invisible */
// ------------------------------------------------------------------------------------------------
-Bool Particle::isInvisible( void )
+Bool Particle::isInvisible( const ParticleUpdateContext &context )
{
- switch (m_system->getShaderType())
+ switch (context.shaderType)
{
case ParticleSystemInfo::ADDITIVE:
// if color is black, this particle is invisible
@@ -2086,10 +2081,13 @@ const ParticleInfo *ParticleSystem::generateParticleInfo( Int particleNum, Int p
// ------------------------------------------------------------------------------------------------
/** Update this particle system, potentially generating new particles */
// ------------------------------------------------------------------------------------------------
-Bool ParticleSystem::update( Int localPlayerIndex )
+Bool ParticleSystem::updateEmission( Int localPlayerIndex, Bool *keepSystem )
{
if (TheGlobalData->m_useFX == FALSE)
+ {
+ *keepSystem = false;
return false;
+ }
// do initial delay ... note, this currently delays the lifetime
if (m_delayLeft)
@@ -2101,7 +2099,8 @@ Bool ParticleSystem::update( Int localPlayerIndex )
if (m_delayLeft == 0)
m_startTimestamp = TheGameClient->getFrame();
- return true;
+ *keepSystem = true;
+ return false;
}
// update the wind motion
@@ -2288,36 +2287,55 @@ Bool ParticleSystem::update( Int localPlayerIndex )
} // end if system lifetime check
} // end if is destroyed
- //
- // Update all particles in the system
- //
- Bool castsGroundShadow = shouldCastGroundShadow();
+ // decided here, after the transform and the burst, where update() always decided it
+ m_pendingCastsGroundShadow = shouldCastGroundShadow();
+ return true;
+}
+
+// ------------------------------------------------------------------------------------------------
+/** What every particle of this system reads during this update. */
+// ------------------------------------------------------------------------------------------------
+void ParticleSystem::makeUpdateContext( ParticleUpdateContext *context ) const
+{
+ context->driftVelocity = m_driftVelocity;
+ context->gravity = m_gravity;
+ context->clientFrame = TheGameClient->getFrame();
+ context->shaderType = m_shaderType;
+ context->windMotion = m_windMotion;
+ context->groundCollision = m_groundCollision && TheTerrainLogic != NULL;
+ context->groundBounce = m_groundBounce;
+ context->groundFriction = m_groundFriction;
+}
+
+// ------------------------------------------------------------------------------------------------
+/** Update this particle system in one pass, potentially generating new particles. The manager
+ * takes this path for a system linked to other systems, because what its particles do - die,
+ * move, emit into a slave - reaches those systems within the same frame. */
+// ------------------------------------------------------------------------------------------------
+Bool ParticleSystem::update( Int localPlayerIndex )
+{
+ Bool keepSystem = true;
+ if (!updateEmission( localPlayerIndex, &keepSystem ))
+ return keepSystem;
+
ParticleShadowBlob shadowBlob;
particleShadowBlobReset( &shadowBlob );
+ ParticleUpdateContext context;
+ makeUpdateContext( &context );
+
Particle *p = m_systemParticlesHead;
Particle *oldParticle;
while (p)
{
-
- // apply 'gravity' force
- if (m_gravity != 0.0f)
- {
- Coord3D force;
- force.x = 0.0f;
- force.y = 0.0f;
- force.z = m_gravity;
- p->applyForce( &force );
- }
-
- if (p->update() == false)
+ if (p->update( context ) == false)
{
oldParticle = p;
p = p->m_systemNext;
oldParticle->deleteInstance();
} else {
// one decal stands in for the whole cloud, so measure the survivors as we pass them
- if (castsGroundShadow)
+ if (m_pendingCastsGroundShadow)
{
const Coord3D *ppos = p->getPosition();
particleShadowBlobAdd( &shadowBlob, ppos->x, ppos->y, p->getSize(), p->getAlpha() );
@@ -2326,8 +2344,81 @@ Bool ParticleSystem::update( Int localPlayerIndex )
}
}
- if (castsGroundShadow)
- updateGroundShadow( &shadowBlob );
+ return finishUpdate( &shadowBlob );
+}
+
+// ------------------------------------------------------------------------------------------------
+/** Nothing else reads this system's particles and it writes into no other system: it is not
+ * steered by a particle, its particles steer nothing (an attached system is only ever made from
+ * the template name), and it has no master and no slave. Such a system's particles can be
+ * integrated at the same time as any other's. A system gains a link only when it is created, so
+ * the answer cannot change between the emission and the particles. */
+// ------------------------------------------------------------------------------------------------
+Bool ParticleSystem::isUpdateIndependent( void ) const
+{
+ return m_controlParticle == NULL && m_attachedSystemName.isEmpty()
+ && m_slaveSystem == NULL && m_masterSystem == NULL;
+}
+
+// ------------------------------------------------------------------------------------------------
+/** The particles of update(), without removing the dead: each one is marked instead, so this reads
+ * and writes nothing but this system's particles and its pending blob. No allocation, no random
+ * draws - the job pool's rules. */
+// ------------------------------------------------------------------------------------------------
+void ParticleSystem::updateParticlesMark( void )
+{
+ ParticleUpdateContext context;
+ makeUpdateContext( &context );
+ particleShadowBlobReset( &m_pendingShadowBlob );
+ m_pendingDeaths = 0;
+
+ for (Particle *p = m_systemParticlesHead; p; p = p->m_systemNext)
+ {
+ const Bool alive = p->update( context );
+ p->setDiesThisUpdate( !alive );
+ if (!alive)
+ ++m_pendingDeaths;
+ // one decal stands in for the whole cloud, so measure the survivors as we pass them
+ if (alive && m_pendingCastsGroundShadow)
+ {
+ const Coord3D *ppos = p->getPosition();
+ particleShadowBlobAdd( &m_pendingShadowBlob, ppos->x, ppos->y, p->getSize(), p->getAlpha() );
+ }
+ }
+}
+
+// ------------------------------------------------------------------------------------------------
+/** Remove what updateParticlesMark marked, in list order, and finish the update. */
+// ------------------------------------------------------------------------------------------------
+Bool ParticleSystem::reapAndFinishUpdate( void )
+{
+ // Particles are appended as they are born and most die of age, so the dead are nearly always at
+ // the head of the list. Walking the whole list a second time after the marking pass cost more
+ // than the marking pass saved on a single core; stopping once every marked particle is gone does
+ // not. Everything past that point was marked alive in the same pass.
+ UnsignedInt remaining = m_pendingDeaths;
+ Particle *p = m_systemParticlesHead;
+ while (p && remaining)
+ {
+ Particle *next = p->m_systemNext;
+ if (p->diesThisUpdate())
+ {
+ p->deleteInstance();
+ --remaining;
+ }
+ p = next;
+ }
+
+ return finishUpdate( &m_pendingShadowBlob );
+}
+
+// ------------------------------------------------------------------------------------------------
+/** The ground blob and the system's lifetime, once its particles are done. */
+// ------------------------------------------------------------------------------------------------
+Bool ParticleSystem::finishUpdate( const ParticleShadowBlob *blob )
+{
+ if (m_pendingCastsGroundShadow)
+ updateGroundShadow( blob );
else
releaseGroundShadow();
@@ -3362,6 +3453,16 @@ void ParticleSystemManager::reset( void )
// ------------------------------------------------------------------------------------------------
/** Update all particle systems */
// ------------------------------------------------------------------------------------------------
+/// systems a pool thread claims at once; a system is a few hundred particles at most
+static const Int PARTICLE_SYSTEMS_PER_CLAIM = 4;
+
+/** One independent system's particles, on the job pool. */
+static void markSystemParticles( Int index, void *context )
+{
+ ParticleSystem **systems = (ParticleSystem **)context;
+ systems[ index ]->updateParticlesMark();
+}
+
DECLARE_PERF_TIMER(ParticleSystemManager)
void ParticleSystemManager::update( void )
{
@@ -3377,23 +3478,57 @@ void ParticleSystemManager::update( void )
m_groundShadowCount = 0;
+ // Three passes. In list order: a system linked to others updates whole, as it always did, and
+ // every other system emits. On the job pool: those other systems' particles. In list order
+ // again: their dead particles, ground blobs and lifetimes. The emissions are the only part that
+ // draws on the client's random stream and they still draw in list order, so every new particle
+ // comes out as it did. What moved is when a dying particle leaves the manager's count: after all
+ // the emissions rather than before the next one, which only matters at the particle cap. With a
+ // hundred thousand particles the particles were most of the update.
+ m_independentUpdates.clear();
for(ParticleSystemListIt it = m_allParticleSystemList.begin(); it != m_allParticleSystemList.end();)
{
sys = (*it);
+ ++it;
if (!sys) {
continue;
}
- if (sys->update(m_localPlayerIndex) == false)
+ Bool keepSystem = true;
+ if (sys->isUpdateIndependent())
{
- ++it;
- sys->deleteInstance();
- } else {
- if (sys->hasGroundShadow())
- ++m_groundShadowCount;
- ++it;
+ if (sys->updateEmission(m_localPlayerIndex, &keepSystem))
+ {
+ m_independentUpdates.push_back( sys );
+ continue;
+ }
+ }
+ else
+ {
+ keepSystem = sys->update(m_localPlayerIndex);
}
+
+ if (keepSystem == false)
+ sys->deleteInstance();
+ else if (sys->hasGroundShadow())
+ ++m_groundShadowCount;
+ }
+
+ if (!m_independentUpdates.empty())
+ {
+ JobSystem::parallel_for( (Int)m_independentUpdates.size(), PARTICLE_SYSTEMS_PER_CLAIM,
+ markSystemParticles, &m_independentUpdates[ 0 ] );
+ }
+
+ for (size_t i = 0; i < m_independentUpdates.size(); ++i)
+ {
+ sys = m_independentUpdates[ i ];
+ if (sys->reapAndFinishUpdate() == false)
+ sys->deleteInstance();
+ else if (sys->hasGroundShadow())
+ ++m_groundShadowCount;
}
+ m_independentUpdates.clear();
// The one number that says what a particle switch actually did, and the only way to compare two
// runs at all: two launches of the same seed and the same scenario do not produce the same
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
index 3df9053e0..8c8b7bebd 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
@@ -42,6 +42,7 @@
#include "GameLogic/Object.h"
#include "GameLogic/ScenarioDrill.h"
#include "GameLogic/TerrainLogic.h"
+#include "GameClient/ParticleSys.h"
#include <algorithm>
#include <vector>
@@ -162,6 +163,8 @@ static Bool parseActionType( const AsciiString &token, ScenarioActionType *actio
*action = SCENARIO_ACTION_STOP;
else if (token == "arrive")
*action = SCENARIO_ACTION_ARRIVE;
+ else if (token == "particles")
+ *action = SCENARIO_ACTION_PARTICLES;
else
return FALSE;
@@ -234,6 +237,7 @@ static Int tokensNeededFor( ScenarioActionType action )
switch (action)
{
case SCENARIO_ACTION_SPAWN: return SCENARIO_TOKENS_SPAWN;
+ case SCENARIO_ACTION_PARTICLES: return SCENARIO_TOKENS_SPAWN;
case SCENARIO_ACTION_MOVE: return SCENARIO_TOKENS_MOVE;
case SCENARIO_ACTION_ATTACKMOVE: return SCENARIO_TOKENS_MOVE;
case SCENARIO_ACTION_ATTACK: return SCENARIO_TOKENS_ATTACK;
@@ -285,6 +289,7 @@ ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *a
switch (actionType)
{
case SCENARIO_ACTION_SPAWN:
+ case SCENARIO_ACTION_PARTICLES:
{
if (!parseWholeNumber( tokens[ 4 ], &action->count ) || action->count < 1)
return SCENARIO_PARSE_BAD_COUNT;
@@ -613,6 +618,47 @@ static Bool executeSpawn( const ScenarioAction &action, Player *player, const Co
return made > 0;
}
+/** Particle systems standing on their own, in the same square block spawn lays units out in. No
+ unit carries an effect that holds more than a few hundred particles, so a scene with a hundred
+ thousand of them cannot be got out of an army; it is asked for here instead. The systems are
+ client state and draw only on the client's random stream, so they change nothing a CRC sees. */
+static Bool executeParticles( const ScenarioAction &action, const Coord3D &centre )
+{
+ const ParticleSystemTemplate *tmpl = TheParticleSystemManager->findTemplate( action.selector );
+ if (tmpl == NULL)
+ {
+ DEBUG_LOG(("SCENARIO: frame %d particles: no particle system named '%s'\n",
+ action.frame, action.selector.str()));
+ return FALSE;
+ }
+
+ Int columns = 1;
+ while (columns * columns < action.count)
+ ++columns;
+ const Int rows = (action.count + columns - 1) / columns;
+ const Real halfWidth = (columns - 1) * action.spacing * 0.5f;
+ const Real halfHeight = (rows - 1) * action.spacing * 0.5f;
+
+ Int made = 0;
+ for( Int i = 0; i < action.count; ++i )
+ {
+ ParticleSystem *system = TheParticleSystemManager->createParticleSystem( tmpl );
+ if (system == NULL)
+ continue;
+
+ Coord3D pos;
+ pos.x = centre.x + (i % columns) * action.spacing - halfWidth;
+ pos.y = centre.y + (i / columns) * action.spacing - halfHeight;
+ pos.z = TheTerrainLogic->getGroundHeight( pos.x, pos.y );
+ system->setPosition( &pos );
+ ++made;
+ }
+
+ DEBUG_LOG(("SCENARIO: frame %d particles '%s' %d of %d at (%.0f,%.0f)\n",
+ action.frame, action.selector.str(), made, action.count, centre.x, centre.y));
+ return made > 0;
+}
+
/** Watch every unit of this seat that matches the selector as they stand now, and note the frame
each one first comes within the radius of the target. The watch starts on the line's own frame,
so a file puts it on the frame of the order it is timing. */
@@ -771,6 +817,7 @@ static Bool executeOrder( const ScenarioAction &action, Player *player, const Co
case SCENARIO_ACTION_SPAWN:
case SCENARIO_ACTION_ARRIVE:
+ case SCENARIO_ACTION_PARTICLES:
ordered = FALSE; // handled before the group is built
break;
}
@@ -795,6 +842,9 @@ Bool ScenarioDrill_execute( const ScenarioAction &action )
if (action.action == SCENARIO_ACTION_SPAWN)
return executeSpawn( action, player, position );
+ if (action.action == SCENARIO_ACTION_PARTICLES)
+ return executeParticles( action, position );
+
if (action.action == SCENARIO_ACTION_ARRIVE)
return executeArrive( action, player, position );
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
index b8a6d1e7b..7c4cddb3a 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
@@ -36,6 +36,8 @@
#include "WW3D2/RInfo.h"
#include "WWLib/BitType.h"
+#include <vector>
+
//=============================================================================
/** W3D implementation of the game display which is responsible for creating
* all interaction with the screen and updating the display
@@ -62,6 +64,24 @@ private:
ShareBufferClass<float> *m_sizeBuffer; ///< array of particle sizes
ShareBufferClass<uint8> *m_angleBuffer; ///< array of particle orientations
Bool m_readyToRender; ///< if true, it is OK to render
+
+public:
+ /// One sorted billboard system's share of a frame's fill: reserved on the render thread, written by
+ /// one job, inserted into the sorting pool on the render thread again, in system list order.
+ struct BillboardFill
+ {
+ ParticleSystem * system;
+ PointGroupClass::SortingBillboardRange range;
+ TextureClass * texture;
+ ShaderClass shader;
+ Int capacity; ///< quads reserved: the system's particles, at most MAX_POINTS_PER_GROUP
+ UnsignedInt fieldIncrement; ///< 1 if every drawn particle counts against the field budget
+ Int drawn; ///< written by the job
+ UnsignedInt pastLimit; ///< written by the job: on-screen particles past capacity
+ };
+
+private:
+ std::vector<BillboardFill> m_billboardFills; ///< kept across frames so the fill does not allocate
};
#endif // end __W3DParticleSys_H_
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
index b012ab709..bd56f5f6c 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp
@@ -50,6 +50,7 @@ static void drawFramerateBar(void);
#include "ffshadercache.h"
#include "dx11runtime.h"
#include "Common/PerfTimer.h"
+#include "Common/JobSystem.h"
#include "Common/FileSystem.h"
#include "Common/LocalFileSystem.h"
#include "Common/Player.h"
@@ -1031,6 +1032,10 @@ void W3DDisplay::init( void )
if (WW3D::Init( ApplicationHWnd ) != WW3D_ERROR_OK)
throw ERROR_INVALID_D3D; //failed to initialize. User probably doesn't have DX 8.1
+ // The sorting pool's depth pass and batch copy split across the job pool. WW3D2 cannot see it,
+ // so it is handed over here; parallel_for runs inline when the pool has no workers.
+ SortingRendererClass::Set_Parallel_For( JobSystem::parallel_for );
+
WW3D::Set_Prelit_Mode( WW3D::PRELIT_MODE_LIGHTMAP_MULTI_PASS );
WW3D::Set_Collision_Box_Display_Mask(0x00); ///<set to 0xff to make collision boxes visible
WW3D::Enable_Static_Sort_Lists(true);
@@ -2058,6 +2063,7 @@ static void captureVideoFrame(void);
//
extern Real TheSceneDrawMS;
extern Real TheUIDrawMS;
+extern Real TheParticleUpdateMS;
static Real w3dElapsedMS( const Int64 &from, const Int64 &to )
{
@@ -2291,6 +2297,10 @@ AGAIN:
//trying to refresh the visible terrain geometry.
// if(TheGlobalData->m_loadScreenRender != TRUE)
updateViews();
+#ifdef DEBUG_LOGGING
+ Int64 tParticleStart, tParticleEnd;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tParticleStart );
+#endif
TheParticleSystemManager->update();//LORENZEN AND WILCZYNSKI MOVED THIS FROM ITS NATIVE POSITION, ABOVE
//FOR THE PURPOSE OF LETTING THE PARTICLE SYSTEM LOOK UP THE RENDER OBJECT"S
//TRANSFORM MATRIX, WHILE IT IS STILL VALID (HAVING DONE ITS CLIENT TRANSFORMS
@@ -2300,6 +2310,10 @@ AGAIN:
//REVOLUTIONARY!
//-LORENZEN
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tParticleEnd );
+ TheParticleUpdateMS = w3dElapsedMS( tParticleStart, tParticleEnd );
+#endif
if (TheWaterRenderObj && TheGlobalData->m_waterType == 2)
TheWaterRenderObj->updateRenderTargetTextures(primaryW3DView->get3DCamera()); //do a render into each texture
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
index 70f4667f0..99be25ac1 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
@@ -35,6 +35,8 @@
#include "W3DDevice/GameClient/W3DSmudge.h"
#include "W3DDevice/GameClient/W3DSnow.h"
#include "WW3D2/Camera.h"
+#include "WW3D2/dx8wrapper.h"
+#include "Common/JobSystem.h"
#ifdef _INTERNAL
// for occasional debugging...
@@ -50,6 +52,84 @@
#include "Common/QuickTrig.h"
+
+#ifdef DEBUG_LOGGING
+extern Real TheParticleFillMS;
+extern UnsignedInt TheParticlesPastGroupLimit;
+#endif
+
+/** The preset a particle shader type draws with, and whether it names one at all. An invalid type
+ * leaves the point group's previous shader in place on the old path, so it does not take the
+ * direct one. */
+static Bool particlePresetShader( ParticleSystemInfo::ParticleShaderType type, ShaderClass *shader )
+{
+ switch( type )
+ {
+ case ParticleSystemInfo::ADDITIVE: *shader = ShaderClass::_PresetAdditiveSpriteShader; return TRUE;
+ case ParticleSystemInfo::ALPHA: *shader = ShaderClass::_PresetAlphaSpriteShader; return TRUE;
+ case ParticleSystemInfo::ALPHA_TEST: *shader = ShaderClass::_PresetATestSpriteShader; return TRUE;
+ case ParticleSystemInfo::MULTIPLY: *shader = ShaderClass::_PresetMultiplicativeSpriteShader; return TRUE;
+ }
+ return FALSE;
+}
+
+/** What every job of one frame's billboard fill reads. */
+struct BillboardFillJob
+{
+ W3DParticleSystemManager::BillboardFill * fills;
+ Matrix4x4 view;
+ Real centerX, centerY, centerZ;
+ Real extentX, extentY, extentZ;
+};
+
+/// systems a pool thread claims at once; a system is a few hundred particles, so one claim a system
+/// would spend more on the interlocked claim than the work is worth
+static const Int BILLBOARD_FILLS_PER_CLAIM = 4;
+
+/** One sorted billboard system's quads, written into the range reserved for it. Reads the system's
+ * particles and writes only that range and that fill's counts: no allocation, no device calls,
+ * nothing another job touches. The cull and the 512-a-system cut are the ones the serial loop
+ * below applies to every other system. */
+static void fillBillboards( Int index, void *context )
+{
+ BillboardFillJob *job = (BillboardFillJob *)context;
+ W3DParticleSystemManager::BillboardFill &fill = job->fills[ index ];
+ VertexFormatXYZNDUV2 *quad = fill.range.Vertices;
+ Int drawn = 0;
+
+ for (Particle *p = fill.system->getFirstParticle(); p; p = p->m_systemNext)
+ {
+ const Coord3D *pos = p->getPosition();
+ const Real psize = p->getSize();
+
+ //Cull particle to edges of screen and terrain.
+ if (WWMath::Fabs(pos->x - job->centerX) > (job->extentX + psize))
+ continue;
+
+ if (WWMath::Fabs(pos->y - job->centerY) > (job->extentY + psize))
+ continue;
+
+ if (WWMath::Fabs(pos->z - job->centerZ) > (job->extentZ + psize))
+ continue;
+
+ const RGBColor *color = p->getColor();
+ const unsigned packed = DX8Wrapper::Convert_Color_Clamp(
+ Vector4( color->red, color->green, color->blue, p->getAlpha() ) );
+ const uint8 orientation = (uint8)(p->getAngle() * 255.0f / (2.0f * PI));
+ PointGroupClass::Write_Billboard( quad, job->view, Vector3( pos->x, pos->y, pos->z ), psize,
+ orientation, packed );
+ quad += 4;
+
+ if (++drawn == fill.capacity)
+ {
+ fill.pastLimit = fill.system->getParticleCount() - drawn;
+ break;
+ }
+ }
+
+ fill.drawn = drawn;
+}
+
W3DParticleSystemManager::W3DParticleSystemManager()
{
m_pointGroup = NULL;
@@ -151,7 +231,59 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
if (TheSmudgeManager)
set=TheSmudgeManager->addSmudgeSet(); //global smudge set through which all smudges are rendered.
+#ifdef DEBUG_LOGGING
+ Int64 tFillStart, tFillEnd;
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tFillStart );
+#endif
+
ParticleSystemManager::ParticleSystemList &particleSysList = TheParticleSystemManager->getAllParticleSystems();
+
+ // Sorted billboards - most smoke, fire and dust - are written on the job pool. With a hundred
+ // thousand particles, walking them one system after another was a quarter of the frame. Their
+ // room in the sorting array is reserved here in list order, and the loop below inserts each one
+ // into the sorting pool at its place in the same order, so the pool sees them as it always did.
+ // Smudges, which draw on the client's random stream, streaks, volume particles, ground-aligned and
+ // alpha-tested systems stay in that loop as they were.
+ m_billboardFills.clear();
+ for( ParticleSystemManager::ParticleSystemListIt it = particleSysList.begin(); it != particleSysList.end(); ++it)
+ {
+ ParticleSystem *sys = (*it);
+ if (!sys || sys->isUsingDrawables())
+ continue;
+ if (*((DWORD *)sys->getParticleTypeName().str()) == 0x44554D53)
+ continue;
+
+ BillboardFill fill;
+ if (sys->isUsingStreak() || !sys->shouldBillboard() || sys->getVolumeParticleDepth() > 1
+ || !particlePresetShader( sys->getShaderType(), &fill.shader )
+ || !PointGroupClass::Would_Sort_Billboards( fill.shader ))
+ continue;
+
+ const Int particles = (Int)sys->getParticleCount();
+ if (particles == 0)
+ continue;
+
+ fill.system = sys;
+ fill.capacity = (particles < (Int)MAX_POINTS_PER_GROUP) ? particles : (Int)MAX_POINTS_PER_GROUP;
+ fill.fieldIncrement = ( sys->getPriority() == AREA_EFFECT && sys->m_isGroundAligned != FALSE ) ? 1 : 0;
+ fill.drawn = 0;
+ fill.pastLimit = 0;
+ fill.texture = W3DDisplay::m_assetManager->Get_Texture( sys->getParticleTypeName().str() );
+ PointGroupClass::Reserve_Sorted_Billboards( fill.capacity, &fill.range );
+ m_billboardFills.push_back( fill );
+ }
+
+ BillboardFillJob fillJob;
+ fillJob.fills = m_billboardFills.empty() ? NULL : &m_billboardFills[ 0 ];
+ DX8Wrapper::Get_Transform( D3DTS_VIEW, fillJob.view );
+ fillJob.centerX = bcX;
+ fillJob.centerY = bcY;
+ fillJob.centerZ = bcZ;
+ fillJob.extentX = beX;
+ fillJob.extentY = beY;
+ fillJob.extentZ = beZ;
+ JobSystem::parallel_for( (Int)m_billboardFills.size(), BILLBOARD_FILLS_PER_CLAIM, fillBillboards, &fillJob );
+ size_t nextFill = 0;
for( ParticleSystemManager::ParticleSystemListIt it = particleSysList.begin(); it != particleSysList.end(); ++it)
{
ParticleSystem *sys = (*it);
@@ -199,6 +331,19 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
continue;
}
+ if (nextFill < m_billboardFills.size() && m_billboardFills[ nextFill ].system == sys)
+ {
+ BillboardFill &fill = m_billboardFills[ nextFill++ ];
+ PointGroupClass::Insert_Sorted_Billboards( &fill.range, fill.drawn, fill.texture, fill.shader );
+ fill.texture->Release_Ref(); // the draw state took its own reference
+ m_fieldParticleCount += fill.fieldIncrement * fill.drawn;
+ m_onScreenParticleCount += fill.drawn;
+#ifdef DEBUG_LOGGING
+ TheParticlesPastGroupLimit += fill.pastLimit;
+#endif
+ continue;
+ }
+
/// @todo lorenzen sez: declare these outside the sys loop, and put some in registers
// initialize them here still, of course
// build W3D particle buffer
@@ -210,6 +355,10 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
const Coord3D *pos;
const RGBColor *color;
Real psize;
+ // the same answer for every particle of the system, so asked once rather than once a particle
+ const UnsignedInt fieldParticleIncrement =
+ ( sys->getPriority() == AREA_EFFECT && sys->m_isGroundAligned != FALSE ) ? 1 : 0;
+
@@ -229,7 +378,7 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
if (WWMath::Fabs(pos->z - bcZ) > (beZ + psize))
continue;
- m_fieldParticleCount += ( sys->getPriority() == AREA_EFFECT && sys->m_isGroundAligned != FALSE );
+ m_fieldParticleCount += fieldParticleIncrement;
//@todo lorenzen sez: use pointer arithmetic for these arrays
personalities[count] = p->getPersonality();
@@ -249,13 +398,19 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
angleArray[count] = (uint8)(p->getAngle() * 255.0f / (2.0f * PI));
if (++count == MAX_POINTS_PER_GROUP)
+ {
+#ifdef DEBUG_LOGGING
+ TheParticlesPastGroupLimit += sys->getParticleCount() - count;
+#endif
break;
+ }
}
if ( count == 0 )
continue; //this system has no particles to render
TextureClass *texture = W3DDisplay::m_assetManager->Get_Texture( sys->getParticleTypeName().str() );
+
if ( m_streakLine && sys->isUsingStreak() && (count >= 2) )
{
@@ -377,6 +532,16 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
/// @todo lorenzen sez: this should be debug only:
TheParticleSystemManager->setOnScreenParticleCount(m_onScreenParticleCount);
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tFillEnd );
+ {
+ Int64 freq;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq > 0 )
+ TheParticleFillMS += (Real)((double)(tFillEnd - tFillStart) * 1000.0 / (double)freq);
+ }
+#endif
+
//Draw any particles belonging to weather effects
if (TheSnowManager)
((W3DSnowManager *)TheSnowManager)->render(rinfo);
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
index a0b85b728..c91baca6f 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
@@ -850,6 +850,21 @@ void RTS3DScene::renderOneObject(RenderInfoClass &rinfo, RenderObjClass *robj, I
DECLARE_PERF_TIMER(translucentRender)
+#ifdef DEBUG_LOGGING
+extern Real TheTranslucentMS;
+extern UnsignedInt TheTranslucentDraws;
+extern UnsignedInt TheSortingPolygonsRefused;
+
+static Real sceneElapsedMS( const Int64 &from, const Int64 &to )
+{
+ Int64 freq;
+ QueryPerformanceFrequency( (LARGE_INTEGER *)&freq );
+ if( freq < 1 )
+ return 0.0f;
+ return (Real)((double)(to - from) * 1000.0 / (double)freq);
+}
+#endif
+
/**Draw everything that was submitted from this scene*/
void RTS3DScene::Flush(RenderInfoClass & rinfo)
{
@@ -882,12 +897,27 @@ void RTS3DScene::Flush(RenderInfoClass & rinfo)
{
USE_PERF_TIMER(translucentRender)
+#ifdef DEBUG_LOGGING
+ // Timed as one block: the heat smudges at the end of DoParticles flush the sorting pool
+ // themselves, so the line between building the quads and drawing them is not here.
+ // doParticles times its own system loop into TheParticleFillMS.
+ Int64 tTranslucentStart, tTranslucentEnd;
+ const unsigned drawsBefore = DX8Wrapper::Get_Draw_Calls();
+ const unsigned refusedBefore = SortingRendererClass::Get_Refused_Polygon_Count();
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tTranslucentStart );
+#endif
//don't draw transparent in this mode because they interfere with destination alpha
if (m_customPassMode == SCENE_PASS_DEFAULT && Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE)
DoParticles(rinfo); //queue up particles for rendering.
SortingRendererClass::Flush(); //draw sorted translucent polys like particles.
+#ifdef DEBUG_LOGGING
+ QueryPerformanceCounter( (LARGE_INTEGER *)&tTranslucentEnd );
+ TheTranslucentMS += sceneElapsedMS( tTranslucentStart, tTranslucentEnd );
+ TheTranslucentDraws += DX8Wrapper::Get_Draw_Calls() - drawsBefore;
+ TheSortingPolygonsRefused += SortingRendererClass::Get_Refused_Polygon_Count() - refusedBefore;
+#endif
}
TheDX8MeshRenderer.Clear_Pending_Delete_Lists();
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index 3e40f44a1..67804e5bf 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -201,7 +201,10 @@ DX11BackendClass::DX11BackendClass()
, ForeignPixelShader(false)
, ForeignVertexShader(false)
{
- memset(&Memo, 0, sizeof(Memo));
+ memset(Memos, 0, sizeof(Memos));
+ LastMemo = 0;
+ NextMemo = 0;
+ Forget_Last_State_Objects();
memset(&HeldVertexConstants, 0, sizeof(HeldVertexConstants));
memset(&HeldPixelConstants, 0, sizeof(HeldPixelConstants));
memset(HeldEngineConstants, 0, sizeof(HeldEngineConstants));
@@ -275,8 +278,13 @@ bool DX11BackendClass::Initialise(DX11DeviceClass * device)
void DX11BackendClass::Release_Cached()
{
- // The memo holds a copy of one of these pipelines, so it goes first.
- Memo.Valid = false;
+ // The memos hold copies of these pipelines and state objects, so they go first.
+ for (unsigned entry = 0; entry < RESOLVE_MEMO_ENTRIES; ++entry) {
+ Memos[entry].Valid = false;
+ }
+ LastMemo = 0;
+ NextMemo = 0;
+ Forget_Last_State_Objects();
for (std::map<std::string, Pipeline>::iterator entry = Pipelines.begin();
entry != Pipelines.end(); ++entry) {
@@ -909,19 +917,24 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
return false;
}
- // Nothing below this line runs for a draw that asks for the pipeline the last one did, which is
- // most of them: the renderer walks its texture categories, so a category's meshes arrive in a
- // row with the same material and the same stage state. See ResolveMemo in the header for what
- // building the key costs and why memcmp is safe here.
- if (Memo.Valid
- && Memo.Format == VertexFormat
- && Memo.VertexProgram == VertexProgram
- && Memo.PixelProgram == PixelProgram
- && memcmp(&Memo.Vertex, &vertex_description, sizeof(vertex_description)) == 0
- && memcmp(&Memo.Combiner, &combiner_description, sizeof(combiner_description)) == 0) {
- pipeline = Memo.Resolved;
- ++Memo.Use->Draws;
- return true;
+ // Nothing below this line runs for a draw that asks for a pipeline one of the last few draws
+ // did, which is nearly all of them: the renderer walks its texture categories, so a category's
+ // meshes arrive in a row, and sorted particles go back and forth between a few pipelines. See
+ // ResolveMemo in the header for what building the key costs and why memcmp is safe here.
+ for (unsigned probe = 0; probe < RESOLVE_MEMO_ENTRIES; ++probe) {
+ const unsigned entry = (LastMemo + probe) % RESOLVE_MEMO_ENTRIES;
+ ResolveMemo & memo = Memos[entry];
+ if (memo.Valid
+ && memo.Format == VertexFormat
+ && memo.VertexProgram == VertexProgram
+ && memo.PixelProgram == PixelProgram
+ && memcmp(&memo.Vertex, &vertex_description, sizeof(vertex_description)) == 0
+ && memcmp(&memo.Combiner, &combiner_description, sizeof(combiner_description)) == 0) {
+ pipeline = memo.Resolved;
+ ++memo.Use->Draws;
+ LastMemo = entry;
+ return true;
+ }
}
char format[32];
@@ -1030,14 +1043,17 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)
void DX11BackendClass::Remember_Resolution(const std::string & key, const Pipeline & resolved,
const VertexPipelineDescription & vertex, const CombinerDescription & combiner)
{
- Memo.Valid = true;
- Memo.Vertex = vertex;
- Memo.Combiner = combiner;
- Memo.Format = VertexFormat;
- Memo.VertexProgram = VertexProgram;
- Memo.PixelProgram = PixelProgram;
- Memo.Resolved = resolved;
- Memo.Use = Record_Use(key);
+ ResolveMemo & memo = Memos[NextMemo];
+ memo.Valid = true;
+ memo.Vertex = vertex;
+ memo.Combiner = combiner;
+ memo.Format = VertexFormat;
+ memo.VertexProgram = VertexProgram;
+ memo.PixelProgram = PixelProgram;
+ memo.Resolved = resolved;
+ memo.Use = Record_Use(key);
+ LastMemo = NextMemo;
+ NextMemo = (NextMemo + 1) % RESOLVE_MEMO_ENTRIES;
}
DX11BackendClass::PipelineUse * DX11BackendClass::Record_Use(const std::string & key)
@@ -1197,14 +1213,32 @@ void DX11BackendClass::Upload_Constants()
}
}
+void DX11BackendClass::Forget_Last_State_Objects()
+{
+ memset(&LastBlendDescription, 0, sizeof(LastBlendDescription));
+ memset(&LastDepthStencilDescription, 0, sizeof(LastDepthStencilDescription));
+ memset(&LastRasterizerDescription, 0, sizeof(LastRasterizerDescription));
+ memset(LastSamplerDescriptions, 0, sizeof(LastSamplerDescriptions));
+ LastBlendState = NULL;
+ LastDepthStencilState = NULL;
+ LastRasterizerState = NULL;
+ memset(LastSamplerStates, 0, sizeof(LastSamplerStates));
+}
+
ID3D11BlendState * DX11BackendClass::Blend_State()
{
D3D11_BLEND_DESC description;
RenderStates.Build_Blend_Description(description);
+ if (LastBlendState != NULL
+ && memcmp(&LastBlendDescription, &description, sizeof(description)) == 0) {
+ return LastBlendState;
+ }
const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
std::map<std::string, ID3D11BlendState *>::const_iterator existing = BlendStates.find(key);
if (existing != BlendStates.end()) {
+ LastBlendDescription = description;
+ LastBlendState = existing->second;
return existing->second;
}
@@ -1217,6 +1251,8 @@ ID3D11BlendState * DX11BackendClass::Blend_State()
return NULL;
}
BlendStates[key] = state;
+ LastBlendDescription = description;
+ LastBlendState = state;
return state;
}
@@ -1224,11 +1260,17 @@ ID3D11DepthStencilState * DX11BackendClass::Depth_Stencil_State()
{
D3D11_DEPTH_STENCIL_DESC description;
RenderStates.Build_Depth_Stencil_Description(description);
+ if (LastDepthStencilState != NULL
+ && memcmp(&LastDepthStencilDescription, &description, sizeof(description)) == 0) {
+ return LastDepthStencilState;
+ }
const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
std::map<std::string, ID3D11DepthStencilState *>::const_iterator existing
= DepthStencilStates.find(key);
if (existing != DepthStencilStates.end()) {
+ LastDepthStencilDescription = description;
+ LastDepthStencilState = existing->second;
return existing->second;
}
@@ -1238,6 +1280,8 @@ ID3D11DepthStencilState * DX11BackendClass::Depth_Stencil_State()
return NULL;
}
DepthStencilStates[key] = state;
+ LastDepthStencilDescription = description;
+ LastDepthStencilState = state;
return state;
}
@@ -1245,11 +1289,17 @@ ID3D11RasterizerState * DX11BackendClass::Rasterizer_State()
{
D3D11_RASTERIZER_DESC description;
RenderStates.Build_Rasterizer_Description(description);
+ if (LastRasterizerState != NULL
+ && memcmp(&LastRasterizerDescription, &description, sizeof(description)) == 0) {
+ return LastRasterizerState;
+ }
const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
std::map<std::string, ID3D11RasterizerState *>::const_iterator existing
= RasterizerStates.find(key);
if (existing != RasterizerStates.end()) {
+ LastRasterizerDescription = description;
+ LastRasterizerState = existing->second;
return existing->second;
}
@@ -1259,6 +1309,8 @@ ID3D11RasterizerState * DX11BackendClass::Rasterizer_State()
return NULL;
}
RasterizerStates[key] = state;
+ LastRasterizerDescription = description;
+ LastRasterizerState = state;
return state;
}
@@ -1266,10 +1318,16 @@ ID3D11SamplerState * DX11BackendClass::Sampler_State(unsigned sampler)
{
D3D11_SAMPLER_DESC description;
Samplers[sampler].Build_Sampler_Description(description);
+ if (LastSamplerStates[sampler] != NULL
+ && memcmp(&LastSamplerDescriptions[sampler], &description, sizeof(description)) == 0) {
+ return LastSamplerStates[sampler];
+ }
const std::string key(reinterpret_cast<const char *>(&description), sizeof(description));
std::map<std::string, ID3D11SamplerState *>::const_iterator existing = SamplerStates.find(key);
if (existing != SamplerStates.end()) {
+ LastSamplerDescriptions[sampler] = description;
+ LastSamplerStates[sampler] = existing->second;
return existing->second;
}
@@ -1279,6 +1337,8 @@ ID3D11SamplerState * DX11BackendClass::Sampler_State(unsigned sampler)
return NULL;
}
SamplerStates[key] = state;
+ LastSamplerDescriptions[sampler] = description;
+ LastSamplerStates[sampler] = state;
return state;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index be7355b28..c90cd4d06 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -365,13 +365,16 @@ private:
std::string ReportLine;
PipelineUse * Record_Use(const std::string & key);
- // The last pipeline Resolve worked out, and the state it was worked out from.
+ // The pipelines Resolve worked out most recently, and the state each was worked out from.
//
// Resolve runs once a draw and its key costs about twenty snprintf calls, a handful of string
// appends and two lookups in a map keyed by that string. Sampling a burning column at 1280x720
// put a eighth of the whole frame inside the C runtime's integer formatter. The renderer
// batches by texture and material, so consecutive draws ask for the same pipeline far more
- // often than not, and a draw that matches this skips the key entirely.
+ // often than not, and a draw that matches skips the key entirely. One remembered pipeline was
+ // enough for that; a sorted particle frame goes back and forth between a few pipelines draw after
+ // draw, and with a hundred thousand particles the formatter was back at seven percent of the
+ // frame. So a handful are kept, the one used last checked first and the oldest written over.
//
// The descriptions are compared with memcmp, which is safe because Build_Vertex_Description and
// Build_Combiner_Description both memset before they fill: no padding byte is ever undefined.
@@ -388,7 +391,10 @@ private:
Pipeline Resolved;
PipelineUse * Use;
};
- ResolveMemo Memo;
+ enum { RESOLVE_MEMO_ENTRIES = 8 };
+ ResolveMemo Memos[RESOLVE_MEMO_ENTRIES];
+ unsigned LastMemo; ///< the entry the last hit or write used; checked first
+ unsigned NextMemo; ///< the entry the next miss writes over
void Remember_Resolution(const std::string & key, const Pipeline & resolved,
const VertexPipelineDescription & vertex, const CombinerDescription & combiner);
@@ -416,6 +422,23 @@ private:
std::map<std::string, ID3D11RasterizerState *> RasterizerStates;
std::map<std::string, ID3D11SamplerState *> SamplerStates;
+ // The last description each kind of state object was looked up by, and the object it got.
+ //
+ // The maps above are keyed by a description's bytes in a std::string, and every description is
+ // longer than the string's own small buffer, so each lookup allocated and freed. Bind_State_Objects
+ // makes seven of them a draw, and a particle-heavy frame is several hundred draws whose states
+ // change far less often than that. memcmp is safe for the ResolveMemo's reason: every
+ // Build_*_Description memsets first. A null object means no memo; Release_Cached nulls them all.
+ D3D11_BLEND_DESC LastBlendDescription;
+ ID3D11BlendState * LastBlendState;
+ D3D11_DEPTH_STENCIL_DESC LastDepthStencilDescription;
+ ID3D11DepthStencilState * LastDepthStencilState;
+ D3D11_RASTERIZER_DESC LastRasterizerDescription;
+ ID3D11RasterizerState * LastRasterizerState;
+ D3D11_SAMPLER_DESC LastSamplerDescriptions[DX11_BACKEND_TEXTURE_STAGES];
+ ID3D11SamplerState * LastSamplerStates[DX11_BACKEND_TEXTURE_STAGES];
+ void Forget_Last_State_Objects();
+
unsigned PipelinesBuilt;
unsigned long long DrawsMade;
unsigned long long DrawsRefused;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
index 7f2cee810..5801a9563 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.cpp
@@ -81,6 +81,21 @@ void DX11BufferTwinClass::Upload(unsigned byte_offset, unsigned byte_count, bool
Context->UpdateSubresource(D3D11Buffer, 0, &box, Mirror_Bytes + byte_offset, 0, 0);
}
+unsigned char * DX11BufferTwinClass::Map_Write(bool discard)
+{
+ const D3D11_MAP map_type = discard ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE;
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (FAILED(Context->Map(D3D11Buffer, 0, map_type, 0, &mapped))) {
+ return NULL;
+ }
+ return (unsigned char *)mapped.pData;
+}
+
+void DX11BufferTwinClass::Unmap()
+{
+ Context->Unmap(D3D11Buffer, 0);
+}
+
static DX11BufferTwinClass * create(ID3D11Device * device, ID3D11DeviceContext * context,
unsigned byte_count, bool dynamic, bool index_buffer)
{
@@ -117,12 +132,14 @@ DX11BufferLockClass::DX11BufferLockClass()
D3D9Memory(NULL),
ByteOffset(0),
ByteCount(0),
- Discard(false)
+ Discard(false),
+ CopyToD3D9(true),
+ Mapped(false)
{
}
void * DX11BufferLockClass::Begin(DX11BufferTwinClass * twin, void * d3d9_memory,
- unsigned byte_offset, unsigned byte_count, unsigned lock_flags)
+ unsigned byte_offset, unsigned byte_count, unsigned lock_flags, bool copy_to_d3d9)
{
Twin = twin;
if (Twin == NULL) {
@@ -133,6 +150,20 @@ void * DX11BufferLockClass::Begin(DX11BufferTwinClass * twin, void * d3d9_memory
ByteOffset = byte_offset;
ByteCount = byte_count == 0 ? Twin->Byte_Count() - byte_offset : byte_count;
Discard = (lock_flags & D3DLOCK_DISCARD) != 0;
+ CopyToD3D9 = copy_to_d3d9;
+ Mapped = false;
+
+ // Nothing reads the D3D9 copy and a dynamic buffer is written again every frame, so the write
+ // can land straight in the mapped D3D11 buffer: no mirror to fill, no copy out of it on End. The
+ // mirror goes stale for this range, which costs nothing, because an upload only ever copies the
+ // range its own lock wrote.
+ if (!copy_to_d3d9 && Twin->Is_Dynamic()) {
+ unsigned char * mapped = Twin->Map_Write(Discard);
+ if (mapped != NULL) {
+ Mapped = true;
+ return mapped + ByteOffset;
+ }
+ }
return Twin->Mirror() + ByteOffset;
}
@@ -143,7 +174,16 @@ void DX11BufferLockClass::End()
return;
}
- memcpy(D3D9Memory, Twin->Mirror() + ByteOffset, ByteCount);
+ if (Mapped) {
+ Twin->Unmap();
+ Mapped = false;
+ Twin = NULL;
+ return;
+ }
+
+ if (CopyToD3D9) {
+ memcpy(D3D9Memory, Twin->Mirror() + ByteOffset, ByteCount);
+ }
Twin->Upload(ByteOffset, ByteCount, Discard);
Twin = NULL;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
index 98275734b..96dce01db 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11twin.h
@@ -51,6 +51,12 @@ public:
unsigned char * Mirror() const { return Mirror_Bytes; }
unsigned Byte_Count() const { return Byte_Total; }
ID3D11Buffer * Buffer() const { return D3D11Buffer; }
+ bool Is_Dynamic() const { return Dynamic; }
+
+ // A dynamic buffer mapped for writing with D3D9's own DISCARD or NOOVERWRITE, the way Upload
+ // maps it; null when the device refuses. The caller writes straight into it, then calls Unmap.
+ unsigned char * Map_Write(bool discard);
+ void Unmap();
// Copy one range of the mirror into the D3D11 buffer. A count of zero means to the end, which
// is what D3D9's own lock means by it.
@@ -94,8 +100,14 @@ public:
// lock_flags is the D3DLOCK_* set the caller handed Direct3D 9, so the upload can be written
// the same way the D3D9 lock was.
+ //
+ // copy_to_d3d9 false leaves the D3D9 memory as it was. A dynamic buffer passes it while
+ // Direct3D 11 presents: Direct3D 9 skips its indexed draws then and nothing reads a D3D9 buffer
+ // back, and a dynamic buffer is written again every frame, so the copy was a second memcpy of
+ // every particle vertex for a device that never looks at it. A dynamic twin locked that way is
+ // also written straight into the mapped D3D11 buffer, with no mirror to fill and copy out of.
void * Begin(DX11BufferTwinClass * twin, void * d3d9_memory, unsigned byte_offset,
- unsigned byte_count, unsigned lock_flags);
+ unsigned byte_count, unsigned lock_flags, bool copy_to_d3d9 = true);
void End();
private:
@@ -104,6 +116,8 @@ private:
unsigned ByteOffset;
unsigned ByteCount;
bool Discard;
+ bool CopyToD3D9;
+ bool Mapped; // Begin handed out the mapped D3D11 buffer itself, so End only unmaps
};
#endif // DX11TWIN_H
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp
index 65ddae30c..1146aef67 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8indexbuffer.cpp
@@ -51,6 +51,13 @@
static bool _DynamicSortingIndexArrayInUse=false;
static SortingIndexBufferClass* _DynamicSortingIndexArray;
static unsigned short _DynamicSortingIndexArraySize=0;
+
+// Full sorting index arrays, handed out again once the flush has let go of them. The vertex
+// arrays in dx8vertexbuffer.cpp say why: operator new[] zeroes what it allocates, and replacing a
+// full array with a freshly sized one every few particle systems was a tenth of a busy frame.
+static const unsigned short SORTING_INDEX_ARRAY_SIZE=65535;
+static const int MAX_RETIRED_SORTING_INDEX_ARRAYS=16;
+static SortingIndexBufferClass* _RetiredSortingIndexArrays[MAX_RETIRED_SORTING_INDEX_ARRAYS];
static unsigned short _DynamicSortingIndexArrayOffset=0;
static bool _DynamicDX8IndexBufferInUse=false;
@@ -453,6 +460,9 @@ void DynamicIBAccessClass::_Deinit()
WWASSERT ((_DynamicSortingIndexArray == NULL) || (_DynamicSortingIndexArray->Num_Refs() == 1));
REF_PTR_RELEASE(_DynamicSortingIndexArray);
+ for (int i=0;i<MAX_RETIRED_SORTING_INDEX_ARRAYS;++i) {
+ REF_PTR_RELEASE(_RetiredSortingIndexArrays[i]);
+ }
_DynamicSortingIndexArrayInUse=false;
_DynamicSortingIndexArraySize=0;
_DynamicSortingIndexArrayOffset=0;
@@ -487,7 +497,8 @@ DynamicIBAccessClass::WriteLockClass::WriteLockClass(DynamicIBAccessClass* ib_ac
Indices,
DynamicIBAccess->IndexBufferOffset*sizeof(WORD),
DynamicIBAccess->Get_Index_Count()*sizeof(WORD),
- !DynamicIBAccess->IndexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE);
+ !DynamicIBAccess->IndexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE,
+ !Direct3D11_Present_Is_Enabled());
if (mirror) Indices=(unsigned short*)mirror;
}
break;
@@ -569,14 +580,32 @@ void DynamicIBAccessClass::Allocate_Sorting_Dynamic_Buffer()
unsigned new_index_count=_DynamicSortingIndexArrayOffset+IndexCount;
WWASSERT(new_index_count<65536);
- if (new_index_count>_DynamicSortingIndexArraySize) {
- REF_PTR_RELEASE(_DynamicSortingIndexArray);
- _DynamicSortingIndexArraySize=new_index_count;
- if (_DynamicSortingIndexArraySize<DEFAULT_IB_SIZE) _DynamicSortingIndexArraySize=DEFAULT_IB_SIZE;
+ if (_DynamicSortingIndexArray && new_index_count>_DynamicSortingIndexArraySize) {
+ int slot=0;
+ while (slot<MAX_RETIRED_SORTING_INDEX_ARRAYS && _RetiredSortingIndexArrays[slot]) {
+ ++slot;
+ }
+ if (slot<MAX_RETIRED_SORTING_INDEX_ARRAYS) {
+ _RetiredSortingIndexArrays[slot]=_DynamicSortingIndexArray;
+ _DynamicSortingIndexArray=NULL;
+ }
+ else {
+ REF_PTR_RELEASE(_DynamicSortingIndexArray);
+ }
}
if (!_DynamicSortingIndexArray) {
- _DynamicSortingIndexArray=NEW_REF(SortingIndexBufferClass,(_DynamicSortingIndexArraySize));
+ for (int i=0;i<MAX_RETIRED_SORTING_INDEX_ARRAYS;++i) {
+ if (_RetiredSortingIndexArrays[i] && _RetiredSortingIndexArrays[i]->Num_Refs()==1) {
+ _DynamicSortingIndexArray=_RetiredSortingIndexArrays[i];
+ _RetiredSortingIndexArrays[i]=NULL;
+ break;
+ }
+ }
+ if (!_DynamicSortingIndexArray) {
+ _DynamicSortingIndexArray=NEW_REF(SortingIndexBufferClass,(SORTING_INDEX_ARRAY_SIZE));
+ }
+ _DynamicSortingIndexArraySize=SORTING_INDEX_ARRAY_SIZE;
_DynamicSortingIndexArrayOffset=0;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp
index 72e10576f..86590f702 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.cpp
@@ -54,6 +54,15 @@ static bool _DynamicSortingVertexArrayInUse=false;
//static VertexFormatXYZNDUV2* _DynamicSortingVertexArray=NULL;
static SortingVertexBufferClass* _DynamicSortingVertexArray=NULL;
static unsigned short _DynamicSortingVertexArraySize=0;
+
+// Sorting arrays that filled up. A full array used to be released and replaced by one sized to the
+// request that overflowed it, so a frame with more sorted vertices than one array holds made a new
+// array every few particle systems - and global operator new[] zeroes every byte it hands out, which
+// put memset at a tenth of a hundred-thousand-particle frame. A full array waits here instead, and
+// once the flush has let go of it (this list is its only holder) it is handed out again.
+static const unsigned short SORTING_VERTEX_ARRAY_SIZE=65535;
+static const int MAX_RETIRED_SORTING_VERTEX_ARRAYS=16;
+static SortingVertexBufferClass* _RetiredSortingVertexArrays[MAX_RETIRED_SORTING_VERTEX_ARRAYS];
static unsigned short _DynamicSortingVertexArrayOffset=0;
static bool _DynamicDX8VertexBufferInUse=false;
@@ -808,6 +817,9 @@ void DynamicVBAccessClass::_Deinit()
WWASSERT ((_DynamicSortingVertexArray == NULL) || (_DynamicSortingVertexArray->Num_Refs() == 1));
REF_PTR_RELEASE(_DynamicSortingVertexArray);
+ for (int i=0;i<MAX_RETIRED_SORTING_VERTEX_ARRAYS;++i) {
+ REF_PTR_RELEASE(_RetiredSortingVertexArrays[i]);
+ }
WWASSERT(!_DynamicSortingVertexArrayInUse);
_DynamicSortingVertexArrayInUse=false;
_DynamicSortingVertexArraySize=0;
@@ -859,14 +871,32 @@ void DynamicVBAccessClass::Allocate_Sorting_Dynamic_Buffer()
unsigned new_vertex_count=_DynamicSortingVertexArrayOffset+VertexCount;
WWASSERT(new_vertex_count<65536);
- if (new_vertex_count>_DynamicSortingVertexArraySize) {
- REF_PTR_RELEASE(_DynamicSortingVertexArray);
- _DynamicSortingVertexArraySize=new_vertex_count;
- if (_DynamicSortingVertexArraySize<DEFAULT_VB_SIZE) _DynamicSortingVertexArraySize=DEFAULT_VB_SIZE;
+ if (_DynamicSortingVertexArray && new_vertex_count>_DynamicSortingVertexArraySize) {
+ int slot=0;
+ while (slot<MAX_RETIRED_SORTING_VERTEX_ARRAYS && _RetiredSortingVertexArrays[slot]) {
+ ++slot;
+ }
+ if (slot<MAX_RETIRED_SORTING_VERTEX_ARRAYS) {
+ _RetiredSortingVertexArrays[slot]=_DynamicSortingVertexArray;
+ _DynamicSortingVertexArray=NULL;
+ }
+ else {
+ REF_PTR_RELEASE(_DynamicSortingVertexArray);
+ }
}
if (!_DynamicSortingVertexArray) {
- _DynamicSortingVertexArray=NEW_REF(SortingVertexBufferClass,(_DynamicSortingVertexArraySize));
+ for (int i=0;i<MAX_RETIRED_SORTING_VERTEX_ARRAYS;++i) {
+ if (_RetiredSortingVertexArrays[i] && _RetiredSortingVertexArrays[i]->Num_Refs()==1) {
+ _DynamicSortingVertexArray=_RetiredSortingVertexArrays[i];
+ _RetiredSortingVertexArrays[i]=NULL;
+ break;
+ }
+ }
+ if (!_DynamicSortingVertexArray) {
+ _DynamicSortingVertexArray=NEW_REF(SortingVertexBufferClass,(SORTING_VERTEX_ARRAY_SIZE));
+ }
+ _DynamicSortingVertexArraySize=SORTING_VERTEX_ARRAY_SIZE;
_DynamicSortingVertexArrayOffset=0;
}
@@ -913,7 +943,8 @@ DynamicVBAccessClass::WriteLockClass::WriteLockClass(DynamicVBAccessClass* dynam
Vertices,
DynamicVBAccess->VertexBufferOffset*DynamicVBAccess->VertexBuffer->FVF_Info().Get_FVF_Size(),
DynamicVBAccess->Get_Vertex_Count()*DynamicVBAccess->VertexBuffer->FVF_Info().Get_FVF_Size(),
- !DynamicVBAccess->VertexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE);
+ !DynamicVBAccess->VertexBufferOffset ? D3DLOCK_DISCARD : D3DLOCK_NOOVERWRITE,
+ !Direct3D11_Present_Is_Enabled());
if (mirror) Vertices=(VertexFormatXYZNDUV2*)mirror;
}
break;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h
index 9f6fc1e71..c1b223af3 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8vertexbuffer.h
@@ -166,6 +166,8 @@ public:
const FVFInfoClass& FVF_Info() const { return FVFInfo; }
unsigned Get_Type() const { return Type; }
unsigned short Get_Vertex_Count() const { return VertexCount; }
+ VertexBufferClass* Peek_Vertex_Buffer() const { return VertexBuffer; } ///< the array or buffer the range lives in, no reference added
+ unsigned short Get_Vertex_Buffer_Offset() const { return VertexBufferOffset; }
// Call at the end of the execution, or at whatever time you wish to release
// the recycled dynamic vertex buffer.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
index a3820aca4..2ca108472 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
@@ -2238,6 +2238,30 @@ void DX8Wrapper::Set_Vertex_Buffer(const DynamicVBAccessClass& vba_)
render_state_changed|=INDEX_BUFFER_CHANGED; // vba_offset changes so index buffer needs to be reset as well.
}
+// ----------------------------------------------------------------------------
+//
+// Bind a range of a sorting vertex array that was reserved and written before, the way the dynamic
+// access above binds one it is holding. The particle fill reserves every system's range first,
+// writes them on the job pool, and only then binds each one to insert it into the sorting pool.
+//
+// ----------------------------------------------------------------------------
+
+void DX8Wrapper::Set_Sorting_Vertex_Range(VertexBufferClass* vb, unsigned short offset, unsigned short count)
+{
+ for (int i=1;i<MAX_VERTEX_STREAMS;++i) {
+ DX8Wrapper::Set_Vertex_Buffer(NULL, i);
+ }
+
+ if (render_state.vertex_buffers[0]) render_state.vertex_buffers[0]->Release_Engine_Ref();
+ render_state.vertex_buffer_types[0]=BUFFER_TYPE_DYNAMIC_SORTING;
+ render_state.vba_offset=offset;
+ render_state.vba_count=count;
+ REF_PTR_SET(render_state.vertex_buffers[0],vb);
+ render_state.vertex_buffers[0]->Add_Engine_Ref();
+ render_state_changed|=VERTEX_BUFFER_CHANGED;
+ render_state_changed|=INDEX_BUFFER_CHANGED; // vba_offset changes so index buffer needs to be reset as well.
+}
+
// ----------------------------------------------------------------------------
//
// Set index buffer using dynamic access object.
@@ -2376,7 +2400,10 @@ public:
explicit CombinerShaderBinding(IDirect3DDevice9 * device)
: Device(device), Bound(false)
{
- if (!CombinerShaders_Are_Enabled() || Device == NULL) {
+ // While Direct3D 11 presents, this device skips the indexed draw the shader would be bound
+ // for, and reading the stages back to format a cache key for it was a string build and a map
+ // lookup per draw for nothing.
+ if (!CombinerShaders_Are_Enabled() || Device == NULL || Direct3D11_Present_Is_Enabled()) {
return;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
index 593767b81..29c86b8d0 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
@@ -311,6 +311,8 @@ public:
static void Set_Vertex_Buffer(const VertexBufferClass* vb, unsigned stream=0);
static void Set_Vertex_Buffer(const DynamicVBAccessClass& vba);
+ /// A range of a sorting vertex array reserved earlier, bound the way a dynamic sorting access binds it
+ static void Set_Sorting_Vertex_Range(VertexBufferClass* vb, unsigned short offset, unsigned short count);
static void Set_Index_Buffer(const IndexBufferClass* ib,unsigned short index_base_offset);
static void Set_Index_Buffer(const DynamicIBAccessClass& iba,unsigned short index_base_offset);
static void Set_Index_Buffer_Index_Offset(unsigned offset);
@@ -484,6 +486,7 @@ public:
static unsigned Get_Last_Frame_Texture_Stage_State_Changes();
static unsigned Get_Last_Frame_DX8_Calls();
static unsigned Get_Last_Frame_Draw_Calls();
+ static unsigned Get_Draw_Calls() { return draw_calls; } ///< so far this frame, to count what one pass costs
static unsigned long Get_FrameCount(void);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp
index 4aa496467..ce3b5c054 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp
@@ -88,6 +88,7 @@
#include "dx8fvf.h"
#include "d3dx9math.h"
#include "sortingrenderer.h"
+#include <string.h>
// Upgraded to DX8 2/2/01 HY
@@ -959,7 +960,16 @@ void PointGroupClass::Render(RenderInfoClass &rinfo)
DynamicVBAccessClass::WriteLockClass Lock(&PointVerts);
int i;
unsigned char *vb=(unsigned char*)Lock.Get_Formatted_Vertex_Array();
- const FVFInfoClass& fvfinfo=PointVerts.FVF_Info();
+ const FVFInfoClass& fvfinfo=PointVerts.FVF_Info();
+
+ // Every vertex of a point carries that point's colour, so a colour equal to the vertex
+ // before it takes the bytes that vertex got. Convert_Color is x87 code that saves and
+ // restores the FPU control word on every call, and a hundred thousand particles is four
+ // hundred thousand vertices a frame.
+ const unsigned default_color=DX8Wrapper::Convert_Color_Clamp(
+ Vector4(DefaultPointColor[0],DefaultPointColor[1],DefaultPointColor[2],DefaultPointAlpha));
+ const Vector4* last_diffuse=NULL;
+ unsigned last_color=default_color;
for (i = current; i < current + delta; i++)
{
@@ -969,12 +979,15 @@ void PointGroupClass::Render(RenderInfoClass &rinfo)
// Copy Locations
*(Vector3*)(vb+fvfinfo.Get_Location_Offset())=VertexLoc[i];
if (current_diffuse) {
- unsigned color=DX8Wrapper::Convert_Color_Clamp(VertexDiffuse[i]);
- *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset())=color;
+ const Vector4* diffuse=&VertexDiffuse[i];
+ if (last_diffuse==NULL || memcmp(diffuse,last_diffuse,sizeof(Vector4))!=0) {
+ last_color=DX8Wrapper::Convert_Color_Clamp(*diffuse);
+ last_diffuse=diffuse;
+ }
+ *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset())=last_color;
}
else
- *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset())=
- DX8Wrapper::Convert_Color_Clamp(Vector4(DefaultPointColor[0],DefaultPointColor[1],DefaultPointColor[2],DefaultPointAlpha));
+ *(unsigned int*)(vb+fvfinfo.Get_Diffuse_Offset())=default_color;
*(Vector2*)(vb+fvfinfo.Get_Tex_Offset(0))=VertexUV[i];
vb+=fvfinfo.Get_FVF_Size();
}
@@ -985,7 +998,10 @@ void PointGroupClass::Render(RenderInfoClass &rinfo)
if ( sort )
{
- SortingRendererClass::Insert_Triangles (0, delta / verticesperprimitive, 0, delta);
+ if (PointMode == QUADS)
+ SortingRendererClass::Insert_Quads (delta / 4, 0, delta);
+ else
+ SortingRendererClass::Insert_Triangles (0, delta / verticesperprimitive, 0, delta);
}
else
{
@@ -1017,6 +1033,74 @@ void PointGroupClass::Render(RenderInfoClass &rinfo)
* HISTORY: *
* 11/17/1998 NH : Created. *
*========================================================================*/
+bool PointGroupClass::Would_Sort_Billboards(const ShaderClass &shader)
+{
+ return (shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO) &&
+ (shader.Get_Alpha_Test() == ShaderClass::ALPHATEST_DISABLE) &&
+ (WW3D::Is_Sorting_Enabled());
+}
+
+/**************************************************************************
+ * PointGroupClass::Reserve_Sorted_Billboards -- room for one system *
+ * *
+ * The particle fill writes every sorted billboard system on the job pool. *
+ * A sorting access can only be open one at a time and closing it moves *
+ * the array's offset past what it handed out, so each system's range is *
+ * opened, noted and closed here in turn; the reference taken keeps the *
+ * array from being recycled while the jobs write into it. *
+ *========================================================================*/
+void PointGroupClass::Reserve_Sorted_Billboards(int quads, SortingBillboardRange *range)
+{
+ WWASSERT(quads > 0 && quads*4 <= MAX_VB_SIZE);
+
+ DynamicVBAccessClass access(BUFFER_TYPE_DYNAMIC_SORTING, dynamic_fvf_type, (unsigned short)(quads*4));
+ DynamicVBAccessClass::WriteLockClass lock(&access);
+ range->Vertices=lock.Get_Formatted_Vertex_Array();
+ range->Offset=access.Get_Vertex_Buffer_Offset();
+ range->Array=NULL;
+ REF_PTR_SET(range->Array, access.Peek_Vertex_Buffer());
+}
+
+/**************************************************************************
+ * PointGroupClass::Insert_Sorted_Billboards -- into the sorting pool *
+ * *
+ * The same state Render sets for a billboarded QUADS group - cull off, *
+ * gradient modulate, identity world and view, the point material - and *
+ * the same Insert_Quads, from a range the jobs have already written. *
+ *========================================================================*/
+void PointGroupClass::Insert_Sorted_Billboards(SortingBillboardRange *range, int quads,
+ TextureClass *texture, const ShaderClass &shader)
+{
+ if (quads > 0)
+ {
+ WWASSERT(Would_Sort_Billboards(shader));
+
+ ShaderClass point_shader(shader);
+ point_shader.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE);
+ point_shader.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE);
+ point_shader.Set_Texturing(texture ? ShaderClass::TEXTURING_ENABLE : ShaderClass::TEXTURING_DISABLE);
+
+ Matrix4x4 view;
+ DX8Wrapper::Get_Transform(D3DTS_VIEW,view);
+
+ Matrix4x4 identity(true);
+ DX8Wrapper::Set_Transform(D3DTS_WORLD,identity);
+ DX8Wrapper::Set_Transform(D3DTS_VIEW,identity);
+ DX8Wrapper::Set_Material(PointMaterial);
+ DX8Wrapper::Set_Shader(point_shader);
+ DX8Wrapper::Set_Texture(0,texture);
+
+ const unsigned short vertices=(unsigned short)(quads*4);
+ DX8Wrapper::Set_Index_Buffer(SortingQuads, 0);
+ DX8Wrapper::Set_Sorting_Vertex_Range(range->Array, range->Offset, vertices);
+ SortingRendererClass::Insert_Quads((unsigned short)quads, 0, vertices);
+
+ DX8Wrapper::Set_Transform(D3DTS_VIEW,view);
+ }
+
+ REF_PTR_RELEASE(range->Array);
+}
+
void PointGroupClass::Update_Arrays(
Vector3 *point_loc,
Vector4 *point_diffuse,
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h
index 72869ef2e..29731bd0e 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h
@@ -47,10 +47,13 @@
#include "vector3.h"
#include "vector2.h"
#include "vector.h"
+#include "matrix4.h"
+#include "dx8fvf.h"
class VertexMaterialClass;
class RenderInfoClass;
class TextureClass;
+class VertexBufferClass;
/*
** PointGroupClass -- a custom object for rendering
@@ -211,6 +214,52 @@ public:
static void _Init(void);
static void _Shutdown(void);
+ /// Would Render put billboards drawn with this shader into the sorting pool?
+ static bool Would_Sort_Billboards(const ShaderClass &shader);
+
+ /// Room for one particle system's sorted billboards, reserved in the sorting vertex array on the
+ /// render thread so the quads can be written into it from anywhere afterwards. Array holds a
+ /// reference, so the array cannot be recycled until Insert_Sorted_Billboards gives it back.
+ struct SortingBillboardRange
+ {
+ VertexBufferClass * Array;
+ VertexFormatXYZNDUV2 * Vertices;
+ unsigned short Offset;
+ };
+
+ /// Reserve four vertices a quad, at most MAX_VB_SIZE of them. Render thread only.
+ static void Reserve_Sorted_Billboards(int quads, SortingBillboardRange *range);
+
+ /// Bind a reserved range holding quads written by Write_Billboard and put it into the sorting
+ /// pool, with the state Render gives a billboarded QUADS group; then release the range. The
+ /// shader has to be one Would_Sort_Billboards accepts. Render thread only.
+ static void Insert_Sorted_Billboards(SortingBillboardRange *range, int quads,
+ TextureClass *texture, const ShaderClass &shader);
+
+ /// One billboard's four vertices: the transform, corner table and single-frame UVs Render uses
+ /// for a billboarded QUADS group with per-point sizes, orientations and colours, written the
+ /// same way so the vertices come out bit for bit the same. color is packed already
+ /// (DX8Wrapper::Convert_Color_Clamp). Touches nothing but its arguments and the static tables,
+ /// so any thread may call it.
+ static inline void Write_Billboard(VertexFormatXYZNDUV2 *quad, const Matrix4x4 &view,
+ const Vector3 &world, float size, unsigned char orientation, unsigned color)
+ {
+ const Vector4 result=view*world;
+ const Vector3 point(result.X,result.Y,result.Z);
+ const Vector3 *corners=_QuadVertexLocationOrientationTable[orientation];
+ const Vector2 *uv=_QuadVertexUVFrameTable[0];
+ for (int k=0;k<4;++k)
+ {
+ const Vector3 location=point + corners[k] * size;
+ quad[k].x=location.X;
+ quad[k].y=location.Y;
+ quad[k].z=location.Z;
+ quad[k].diffuse=color;
+ quad[k].u1=uv[k].X;
+ quad[k].v1=uv[k].Y;
+ }
+ }
+
private:
static Vector3 _TriVertexLocationOrientationTable[256][3];
static Vector3 _QuadVertexLocationOrientationTable[256][4];
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
index cd90432e5..355e82ff0 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
@@ -80,77 +80,51 @@ struct TempIndexStruct
float z;
};
-bool operator <(const TempIndexStruct &l, const TempIndexStruct &r) { return l.z < r.z; }
-bool operator <=(const TempIndexStruct &l, const TempIndexStruct &r) { return l.z <= r.z; }
-bool operator >(const TempIndexStruct &l, const TempIndexStruct &r) { return l.z > r.z; }
-bool operator >=(const TempIndexStruct &l, const TempIndexStruct &r) { return l.z >= r.z; }
-bool operator ==(const TempIndexStruct &l, const TempIndexStruct &r) { return l.z == r.z; }
// ----------------------------------------------------------------------------
-static
-void InsertionSort(TempIndexStruct *begin, TempIndexStruct *end)
+// The pool's entries in depth order, nearest last, as three passes of eleven bits over each depth's
+// sort key. The quicksort that was here was a fifth of a hundred-thousand-particle frame on its
+// own, two hundred thousand triangles compared several million times. This touches each entry four
+// times. It is stable, so entries at exactly the same depth keep the order they were pooled in; the
+// quicksort left those in whatever order partitioning did. Returns whichever of the two arrays
+// holds the result.
+
+static const unsigned DEPTH_RADIX_BITS=11;
+static const unsigned DEPTH_RADIX_BUCKETS=1<<DEPTH_RADIX_BITS;
+static const unsigned DEPTH_RADIX_PASSES=3;
+
+static TempIndexStruct* Sort_By_Depth(TempIndexStruct* items,TempIndexStruct* scratch,unsigned count)
{
- for (TempIndexStruct *iter = begin + 1; iter < end; ++iter) {
- TempIndexStruct val = iter[0];
- TempIndexStruct *insert = iter;
- while (insert != begin && insert[-1] > val) {
- insert[0] = insert[-1];
- insert -= 1;
+ static unsigned histogram[DEPTH_RADIX_PASSES][DEPTH_RADIX_BUCKETS];
+ memset(histogram,0,sizeof(histogram));
+ for (unsigned i=0;i<count;++i) {
+ const unsigned key=SortingRendererClass::_Depth_Sort_Key(items[i].z);
+ for (unsigned pass=0;pass<DEPTH_RADIX_PASSES;++pass) {
+ ++histogram[pass][(key>>(pass*DEPTH_RADIX_BITS))&(DEPTH_RADIX_BUCKETS-1)];
}
- insert[0] = val;
}
-}
-// ----------------------------------------------------------------------------
-static
-void Sort(TempIndexStruct *begin, TempIndexStruct *end)
-{
- const int diff = end - begin;
- if (diff <= 16) {
- // Insertion sort has less overhead for small arrays
- InsertionSort(begin, end);
- } else {
- // Choose the median of begin, mid, and (end - 1) as the partitioning element.
- // Rearrange so that *(begin + 1) <= *begin <= *(end - 1). These will be guard
- // elements.
- TempIndexStruct *mid = begin + diff/2;
- std::swap(mid[0], begin[1]);
- if (begin[1] > end[-1]) {
- std::swap(begin[1], end[-1]);
- }
- if (begin[0] > end[-1]) {
- std::swap(begin[0], end[-1]);
- } // end[-1] has the largest element
- if (begin[1] > begin[0]) {
- std::swap(begin[1], begin[0]);
- } // begin[0] has the middle element and begin[1] has the smallest element
-
- // *begin is now the partitioning element
- TempIndexStruct *begin1 = begin + 1; // TODO: Temp fix until I find out who is passing me NaN
- TempIndexStruct *end1 = end - 1; // TODO: Temp fix until I find out who is passing me NaN
- TempIndexStruct *left = begin + 1;
- TempIndexStruct *right = end - 1;
- for (;;) {
-#if 0 // TODO: Temp fix until I find out who is passing me NaN.
- do ++left; while (left[0] < begin[0]); // Scan up to find element >= than partition
- do --right; while (right[0] > begin[0]); // Scan down to find element <= than partition
-#else
- do ++left; while (left < end1 && left[0] < begin[0]); // Scan up to find element >= than partition
- do --right; while (right > begin1 && right[0] > begin[0]); // Scan down to find element <= than partition
-#endif
- if (right < left) break; // Pointers crossed. Partitioning completed.
- std::swap(left[0], right[0]); // Exchange elements.
+ TempIndexStruct* from=items;
+ TempIndexStruct* to=scratch;
+ for (unsigned pass=0;pass<DEPTH_RADIX_PASSES;++pass) {
+ unsigned* buckets=histogram[pass];
+ unsigned offset=0;
+ for (unsigned b=0;b<DEPTH_RADIX_BUCKETS;++b) {
+ const unsigned in_bucket=buckets[b];
+ buckets[b]=offset;
+ offset+=in_bucket;
}
- std::swap(begin[0], right[0]); // Insert partition element
- // Sort the smaller subarray first then the larger
- if (right - begin > end - (right + 1)) {
- Sort(right + 1, end);
- Sort(begin, right);
- } else {
- Sort(begin, right);
- Sort(right + 1, end);
+ const unsigned shift=pass*DEPTH_RADIX_BITS;
+ for (unsigned i=0;i<count;++i) {
+ const unsigned key=SortingRendererClass::_Depth_Sort_Key(from[i].z);
+ to[buckets[(key>>shift)&(DEPTH_RADIX_BUCKETS-1)]++]=from[i];
}
+
+ TempIndexStruct* swap=from;
+ from=to;
+ to=swap;
}
+ return from;
}
// ----------------------------------------------------------------------------
@@ -169,6 +143,7 @@ public:
unsigned short polygon_count; // Polygon count to process (3 indices = one polygon)
unsigned short min_vertex_index; // First index used in the vb
unsigned short vertex_count; // Number of vertices used in vb
+ bool quads; // four vertices a quad, in order from min_vertex_index; the ib is not read
};
static DLListClass<SortingNodeStruct> sorted_list;
@@ -197,6 +172,7 @@ static SortingNodeStruct* Get_Sorting_Struct()
// ----------------------------------------------------------------------------
static TempIndexStruct* temp_index_array;
+static TempIndexStruct* temp_sort_scratch_array; // the radix sort's second buffer, always the same size
static unsigned temp_index_array_count;
static TempIndexStruct* Get_Temp_Index_Array(unsigned count)
@@ -205,7 +181,9 @@ static TempIndexStruct* Get_Temp_Index_Array(unsigned count)
count = DEFAULT_SORTING_POLY_COUNT;
if (count>temp_index_array_count) {
delete[] temp_index_array;
+ delete[] temp_sort_scratch_array;
temp_index_array=W3DNEWARRAY TempIndexStruct[count];
+ temp_sort_scratch_array=W3DNEWARRAY TempIndexStruct[count];
temp_index_array_count=count;
}
return temp_index_array;
@@ -249,6 +227,7 @@ void SortingRendererClass::Insert_Triangles(
state->polygon_count=polygon_count;
state->min_vertex_index=min_vertex_index;
state->vertex_count=vertex_count;
+ state->quads=false;
SortingVertexBufferClass* vertex_buffer=static_cast<SortingVertexBufferClass*>(state->sorting_state.vertex_buffers[0]);
WWASSERT(vertex_buffer);
@@ -322,6 +301,46 @@ void SortingRendererClass::Insert_Triangles(
Insert_Triangles(sphere,start_index,polygon_count,min_vertex_index,vertex_count);
}
+// ----------------------------------------------------------------------------
+//
+// Insert quads laid out four vertices each, in order, from min_vertex_index in the vertex buffer
+// that is set. The pool sorts and writes a quad as one piece: a billboard's four corners share one
+// depth, so its two triangles always had the same key, and a quad is four vertices and six indices
+// where two loose triangles were six and six. No bounding information, like the call above.
+//
+// ----------------------------------------------------------------------------
+
+void SortingRendererClass::Insert_Quads(
+ unsigned short quad_count,
+ unsigned short min_vertex_index,
+ unsigned short vertex_count)
+{
+ const unsigned short polygon_count=quad_count*2;
+ if (!WW3D::Is_Sorting_Enabled()) {
+ DX8Wrapper::Draw_Triangles(0,polygon_count,min_vertex_index,vertex_count);
+ return;
+ }
+
+ DX8_RECORD_SORTING_RENDER(polygon_count,vertex_count);
+
+ SortingNodeStruct* state=Get_Sorting_Struct();
+ DX8Wrapper::Get_Render_State(state->sorting_state);
+
+ WWASSERT(
+ ((state->sorting_state.index_buffer_type==BUFFER_TYPE_SORTING || state->sorting_state.index_buffer_type==BUFFER_TYPE_DYNAMIC_SORTING) &&
+ (state->sorting_state.vertex_buffer_types[0]==BUFFER_TYPE_SORTING || state->sorting_state.vertex_buffer_types[0]==BUFFER_TYPE_DYNAMIC_SORTING)));
+ WWASSERT(vertex_count==quad_count*4);
+
+ state->bounding_sphere=SphereClass(Vector3(0.0f,0.0f,0.0f),0.0f);
+ state->start_index=0;
+ state->polygon_count=polygon_count;
+ state->min_vertex_index=min_vertex_index;
+ state->vertex_count=vertex_count;
+ state->quads=true;
+ state->transformed_center=Vector3(0.0f,0.0f,0.0f);
+ unsorted_list.Add_Tail(state);
+}
+
// ----------------------------------------------------------------------------
//
// Flush all sorting polygons.
@@ -343,38 +362,62 @@ void Release_Refs(SortingNodeStruct* state)
}
static unsigned overlapping_node_count;
-static unsigned overlapping_polygon_count;
-static unsigned overlapping_vertex_count;
+static unsigned overlapping_entry_count; // sort entries: a triangle each, or a quad each for a quad node
static const unsigned MAX_OVERLAPPING_NODES=4096;
-// 16 bit indices: 65535 is the last index a triangle can name, and three of them per polygon.
-static const unsigned MAX_SORTING_VERTICES=65535;
-static const unsigned MAX_SORTING_POLYGONS=65535/3;
+// One batch of the flush: a 16 bit index names 65535 vertices, and the index buffer holds 65535.
+static const unsigned MAX_BATCH_VERTICES=65535;
+static const unsigned MAX_BATCH_INDICES=65535;
+// A sort entry whose third index is this is a quad; its first index is the quad's first vertex.
+static const unsigned short QUAD_ENTRY=0xFFFF;
static SortingNodeStruct* overlapping_nodes[MAX_OVERLAPPING_NODES];
+// Where each pooled node's first vertex sits, worked out once in the sort pass for the copy pass.
+static VertexFormatXYZNDUV2* overlapping_node_vertices[MAX_OVERLAPPING_NODES];
+// Where each pooled node's sort entries begin, worked out in order before the nodes fill them in parallel.
+static unsigned overlapping_node_entry_offsets[MAX_OVERLAPPING_NODES];
+static unsigned refused_polygon_count;
+
+unsigned SortingRendererClass::Get_Refused_Polygon_Count()
+{
+ return refused_polygon_count;
+}
+
+static SortingRendererClass::ParallelForFunc parallel_for_hook=NULL;
+
+void SortingRendererClass::Set_Parallel_For(ParallelForFunc parallel_for)
+{
+ parallel_for_hook=parallel_for;
+}
+
+static void Run_Parallel(int count,int granularity,void (*work)(int,void*),void* context)
+{
+ if (count<=0) return;
+ if (parallel_for_hook) {
+ parallel_for_hook(count,granularity,work,context);
+ return;
+ }
+ for (int i=0;i<count;++i) {
+ work(i,context);
+ }
+}
+
+// nodes a thread claims at once in the depth pass; a particle node is a few hundred quads
+static const int NODES_PER_CLAIM=4;
+// entries one job copies into a batch at once
+static const unsigned ENTRIES_PER_COPY_CHUNK=2048;
// ----------------------------------------------------------------------------
void SortingRendererClass::Insert_To_Sorting_Pool(SortingNodeStruct* state)
{
if (overlapping_node_count>=MAX_OVERLAPPING_NODES) {
+ refused_polygon_count+=state->polygon_count;
Release_Refs(state);
WWASSERT(0);
return;
}
- // The pool feeds one dynamic index buffer and one dynamic vertex buffer, and both
- // are 16 bit. Past 65535 indices Flush_Sorting_Pool asks for a buffer that cannot
- // exist and writes the triangles into it anyway; past 65535 vertices the per-node
- // vertex offset stored in each triangle wraps and the geometry comes out as noise.
- // Refuse the node instead, the way an over-full node list already does.
- if (overlapping_polygon_count+state->polygon_count>MAX_SORTING_POLYGONS ||
- overlapping_vertex_count+state->vertex_count>MAX_SORTING_VERTICES) {
- Release_Refs(state);
- return;
- }
-
overlapping_nodes[overlapping_node_count]=state;
- overlapping_vertex_count+=state->vertex_count;
- overlapping_polygon_count+=state->polygon_count;
+ overlapping_entry_count+=state->quads ? state->polygon_count/2 : state->polygon_count;
overlapping_node_count++;
}
@@ -432,200 +475,356 @@ static void Apply_Render_State(RenderStateStruct& render_state)
}
// ----------------------------------------------------------------------------
+// Would Apply_Render_State leave the device exactly as it is? Byte compares on the lights and the
+// matrices can only say no to two states that are really the same, which costs a draw and nothing
+// else.
-void SortingRendererClass::Flush_Sorting_Pool()
+static bool Same_Draw_State(const RenderStateStruct& a, const RenderStateStruct& b)
{
- if (!overlapping_node_count) return;
+ if (a.shader.Get_Bits()!=b.shader.Get_Bits() || a.material!=b.material) return false;
+ for (int i=0;i<DX8Wrapper::Get_Current_Caps()->Get_Max_Textures_Per_Pass();++i) {
+ if (a.Textures[i]!=b.Textures[i]) return false;
+ }
+ if (memcmp(&a.world,&b.world,sizeof(a.world))!=0 || memcmp(&a.view,&b.view,sizeof(a.view))!=0) return false;
+ if (a.material && a.material->Get_Lighting()) {
+ if (memcmp(a.LightEnable,b.LightEnable,sizeof(a.LightEnable))!=0) return false;
+ if (memcmp(a.Lights,b.Lights,sizeof(a.Lights))!=0) return false;
+ }
+ return true;
+}
- SNAPSHOT_SAY(("SortingSystem - Flush \n"));
+// ----------------------------------------------------------------------------
- // Fill dynamic index buffer with sorting index buffer vertices
- TempIndexStruct* tis=Get_Temp_Index_Array(overlapping_polygon_count);
+static inline bool Entry_Is_Quad(const TempIndexStruct& entry)
+{
+ return entry.tri.k==QUAD_ENTRY;
+}
- unsigned vertexAllocCount = overlapping_vertex_count;
- if (DynamicVBAccessClass::Get_Default_Vertex_Count() < DEFAULT_SORTING_VERTEX_COUNT)
- vertexAllocCount = DEFAULT_SORTING_VERTEX_COUNT; //make sure that we force the DX8 dynamic vertex buffer to maximum size
- if (overlapping_vertex_count > vertexAllocCount)
- vertexAllocCount = overlapping_vertex_count;
- WWASSERT(DEFAULT_SORTING_VERTEX_COUNT == 1 || vertexAllocCount <= DEFAULT_SORTING_VERTEX_COUNT);
- DynamicVBAccessClass dyn_vb_access(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,vertexAllocCount/*overlapping_vertex_count*/);
- {
- DynamicVBAccessClass::WriteLockClass lock(&dyn_vb_access);
- VertexFormatXYZNDUV2* dest_verts=(VertexFormatXYZNDUV2 *)lock.Get_Formatted_Vertex_Array();
+static inline unsigned Entry_Vertex_Count(const TempIndexStruct& entry)
+{
+ return Entry_Is_Quad(entry) ? 4 : 3;
+}
- unsigned polygon_array_offset=0;
- unsigned vertex_array_offset=0;
- for (unsigned node_id=0;node_id<overlapping_node_count;++node_id) {
- SortingNodeStruct* state=overlapping_nodes[node_id];
- VertexFormatXYZNDUV2* src_verts=NULL;
- SortingVertexBufferClass* vertex_buffer=static_cast<SortingVertexBufferClass*>(state->sorting_state.vertex_buffers[0]);
- WWASSERT(vertex_buffer);
- src_verts=vertex_buffer->VertexBuffer;
- WWASSERT(src_verts);
- src_verts+=state->sorting_state.vba_offset;
- src_verts+=state->sorting_state.index_base_offset;
- src_verts+=state->min_vertex_index;
-
- // If you have a crash in here and "dest_verts" points to illegal memory area,
- // it is because D3D is in illegal state, and the only known cure is rebooting.
- // This illegal state is usually caused by Quake3-engine powered games such as MOHAA.
- memcpy(dest_verts, src_verts, sizeof(VertexFormatXYZNDUV2)*state->vertex_count);
- dest_verts += state->vertex_count;
-
- D3DXMATRIX d3d_mtx=(D3DXMATRIX&)state->sorting_state.world*(D3DXMATRIX&)state->sorting_state.view;
- const Matrix4x4& mtx=(const Matrix4x4&)d3d_mtx;
-
- unsigned short* indices=NULL;
- SortingIndexBufferClass* index_buffer=static_cast<SortingIndexBufferClass*>(state->sorting_state.index_buffer);
- WWASSERT(index_buffer);
- indices=index_buffer->index_buffer;
- WWASSERT(indices);
- indices+=state->start_index;
- indices+=state->sorting_state.iba_offset;
-
- if (mtx[0][2] == 0.0f && mtx[1][2] == 0.0f && mtx[3][2] == 0.0f && mtx[2][2] == 1.0f) {
- // The common case for particle systems.
- for (int i=0;i<state->polygon_count;++i) {
- unsigned short idx1=indices[i*3]-state->min_vertex_index;
- unsigned short idx2=indices[i*3+1]-state->min_vertex_index;
- unsigned short idx3=indices[i*3+2]-state->min_vertex_index;
- WWASSERT(idx1<state->vertex_count);
- WWASSERT(idx2<state->vertex_count);
- WWASSERT(idx3<state->vertex_count);
- const VertexFormatXYZNDUV2 *v1 = src_verts + idx1;
- const VertexFormatXYZNDUV2 *v2 = src_verts + idx2;
- const VertexFormatXYZNDUV2 *v3 = src_verts + idx3;
- unsigned array_index=i+polygon_array_offset;
- WWASSERT(array_index<overlapping_polygon_count);
- TempIndexStruct *tis_ptr = tis + array_index;
- tis_ptr->tri.i = idx1 + vertex_array_offset;
- tis_ptr->tri.j = idx2 + vertex_array_offset;
- tis_ptr->tri.k = idx3 + vertex_array_offset;
- tis_ptr->idx = node_id;
- tis_ptr->z = (v1->z + v2->z + v3->z)/3.0f;
- DEBUG_ASSERTCRASH((! _isnan(tis_ptr->z) && _finite(tis_ptr->z)), ("Triangle has invalid center"));
- }
- } else {
- for (int i=0;i<state->polygon_count;++i) {
- unsigned short idx1=indices[i*3]-state->min_vertex_index;
- unsigned short idx2=indices[i*3+1]-state->min_vertex_index;
- unsigned short idx3=indices[i*3+2]-state->min_vertex_index;
- WWASSERT(idx1<state->vertex_count);
- WWASSERT(idx2<state->vertex_count);
- WWASSERT(idx3<state->vertex_count);
- const VertexFormatXYZNDUV2 *v1 = src_verts + idx1;
- const VertexFormatXYZNDUV2 *v2 = src_verts + idx2;
- const VertexFormatXYZNDUV2 *v3 = src_verts + idx3;
- unsigned array_index=i+polygon_array_offset;
- WWASSERT(array_index<overlapping_polygon_count);
- TempIndexStruct *tis_ptr = tis + array_index;
- tis_ptr->tri.i = idx1 + vertex_array_offset;
- tis_ptr->tri.j = idx2 + vertex_array_offset;
- tis_ptr->tri.k = idx3 + vertex_array_offset;
- tis_ptr->idx = node_id;
- tis_ptr->z = (mtx[0][2]*(v1->x + v2->x + v3->x) +
- mtx[1][2]*(v1->y + v2->y + v3->y) +
- mtx[2][2]*(v1->z + v2->z + v3->z))/3.0f + mtx[3][2];
- DEBUG_ASSERTCRASH((! _isnan(tis_ptr->z) && _finite(tis_ptr->z)), ("Triangle has invalid center"));
- }
- }
+static inline unsigned Entry_Index_Count(const TempIndexStruct& entry)
+{
+ return Entry_Is_Quad(entry) ? 6 : 3;
+}
- state->min_vertex_index=vertex_array_offset;
+// Where each entry of a batch writes its vertices and indices. Worked out in order on the render
+// thread so the copy can be split across threads; the array only grows, and only there.
+struct BatchEntryOffset
+{
+ unsigned vertex;
+ unsigned index;
+};
- polygon_array_offset+=state->polygon_count;
- vertex_array_offset+=state->vertex_count;
- }
+static BatchEntryOffset* batch_offsets;
+static unsigned batch_offsets_count;
+
+static const BatchEntryOffset* Compute_Batch_Offsets(const TempIndexStruct* entries,unsigned entry_count)
+{
+ if (entry_count>batch_offsets_count) {
+ delete[] batch_offsets;
+ batch_offsets=W3DNEWARRAY BatchEntryOffset[entry_count];
+ batch_offsets_count=entry_count;
}
+ unsigned vertex=0;
+ unsigned index=0;
+ for (unsigned e=0;e<entry_count;++e) {
+ batch_offsets[e].vertex=vertex;
+ batch_offsets[e].index=index;
+ vertex+=Entry_Vertex_Count(entries[e]);
+ index+=Entry_Index_Count(entries[e]);
+ }
+ return batch_offsets;
+}
- Sort(tis, tis + overlapping_polygon_count);
+struct BatchCopyJob
+{
+ const TempIndexStruct* entries;
+ const BatchEntryOffset* offsets;
+ unsigned entry_count;
+ VertexFormatXYZNDUV2* vertices;
+ unsigned short* indices;
+};
-/* ///@todo: Add code to break up rendering into multiple index buffer fills to allow more than 65536/3 triangles. -MW
- int total_overlapping_polygon_count = overlapping_polygon_count;
- while ( > 0)
- {
- if ((total_overlapping_polygon_count*3) > 65535)
- { //overflowed the index buffer, must break into multiple batches
- overlapping_polygon_count = 65535/3;
+static void Copy_Batch_Vertices(int chunk,void* context)
+{
+ const BatchCopyJob* job=(const BatchCopyJob*)context;
+ const unsigned first=(unsigned)chunk*ENTRIES_PER_COPY_CHUNK;
+ const unsigned last=MIN(first+ENTRIES_PER_COPY_CHUNK,job->entry_count);
+ for (unsigned e=first;e<last;++e) {
+ const TempIndexStruct& entry=job->entries[e];
+ const VertexFormatXYZNDUV2* src_verts=overlapping_node_vertices[entry.idx];
+ VertexFormatXYZNDUV2* dest_verts=job->vertices+job->offsets[e].vertex;
+ if (Entry_Is_Quad(entry)) {
+ memcpy(dest_verts,src_verts+entry.tri.i,sizeof(VertexFormatXYZNDUV2)*4);
+ }
+ else {
+ dest_verts[0]=src_verts[entry.tri.i];
+ dest_verts[1]=src_verts[entry.tri.j];
+ dest_verts[2]=src_verts[entry.tri.k];
}
- else
- overlapping_polygon_count = total_overlapping_polygon_count;
+ }
+}
+
+static void Write_Batch_Indices(int chunk,void* context)
+{
+ const BatchCopyJob* job=(const BatchCopyJob*)context;
+ const unsigned first=(unsigned)chunk*ENTRIES_PER_COPY_CHUNK;
+ const unsigned last=MIN(first+ENTRIES_PER_COPY_CHUNK,job->entry_count);
+ for (unsigned e=first;e<last;++e) {
+ const unsigned short vertex=(unsigned short)job->offsets[e].vertex;
+ unsigned short* index_array=job->indices+job->offsets[e].index;
+ if (Entry_Is_Quad(job->entries[e])) {
+ index_array[0]=vertex;
+ index_array[1]=vertex+1;
+ index_array[2]=vertex+2;
+ index_array[3]=vertex+2;
+ index_array[4]=vertex+3;
+ index_array[5]=vertex;
+ }
+ else {
+ index_array[0]=vertex;
+ index_array[1]=vertex+1;
+ index_array[2]=vertex+2;
+ }
+ }
+}
- //insert rendering code here!!
+// Draw one batch of the sorted entries, in that order.
+//
+// Each entry's vertices are copied out of its node on their own - three for a triangle, four for a
+// quad - so a run of entries covers one contiguous stretch of the batch's vertices and indices. A
+// quad's indices are the pattern PointGroupClass's own quad index buffers use.
+//
+// A run ends where the sorted entries move to another node, and it used to be drawn there even
+// when the next node draws with exactly the same state - thirty inferno cannons each with its own
+// fire system on the same texture, interleaved in depth, were a draw every few triangles. A run
+// carries on across nodes whose state matches. The order of the entries does not change, so
+// neither does the picture.
+static void Flush_Sorting_Batch(const TempIndexStruct* entries,unsigned entry_count,unsigned vertex_count,unsigned index_count)
+{
+ BatchCopyJob job;
+ job.entries=entries;
+ job.offsets=Compute_Batch_Offsets(entries,entry_count);
+ job.entry_count=entry_count;
+ job.vertices=NULL;
+ job.indices=NULL;
+ const int chunks=(int)((entry_count+ENTRIES_PER_COPY_CHUNK-1)/ENTRIES_PER_COPY_CHUNK);
+
+ DynamicVBAccessClass dyn_vb_access(BUFFER_TYPE_DYNAMIC_DX8,dynamic_fvf_type,(unsigned short)vertex_count);
+ {
+ DynamicVBAccessClass::WriteLockClass lock(&dyn_vb_access);
- total_overlapping_polygon_count -= overlapping_polygon_count;
+ // If you have a crash in here and "dest_verts" points to illegal memory area,
+ // it is because D3D is in illegal state, and the only known cure is rebooting.
+ // This illegal state is usually caused by Quake3-engine powered games such as MOHAA.
+ job.vertices=(VertexFormatXYZNDUV2 *)lock.Get_Formatted_Vertex_Array();
+ Run_Parallel(chunks,1,Copy_Batch_Vertices,&job);
}
-*/
- unsigned polygonAllocCount = overlapping_polygon_count;
- if ((unsigned)(DynamicIBAccessClass::Get_Default_Index_Count()/3) < DEFAULT_SORTING_POLY_COUNT)
- polygonAllocCount = DEFAULT_SORTING_POLY_COUNT; //make sure that we force the DX8 index buffer to maximum size
- if (overlapping_polygon_count > polygonAllocCount)
- polygonAllocCount = overlapping_polygon_count;
- WWASSERT(DEFAULT_SORTING_POLY_COUNT <= 1 || polygonAllocCount <= DEFAULT_SORTING_POLY_COUNT);
-
- DynamicIBAccessClass dyn_ib_access(BUFFER_TYPE_DYNAMIC_DX8,polygonAllocCount*3);
+
+ DynamicIBAccessClass dyn_ib_access(BUFFER_TYPE_DYNAMIC_DX8,(unsigned short)index_count);
{
DynamicIBAccessClass::WriteLockClass lock(&dyn_ib_access);
- ShortVectorIStruct* sorted_polygon_index_array=(ShortVectorIStruct*)lock.Get_Index_Array();
+ job.indices=lock.Get_Index_Array();
try {
- for (unsigned a=0;a<overlapping_polygon_count;++a) {
- sorted_polygon_index_array[a]=tis[a].tri;
- }
+ Run_Parallel(chunks,1,Write_Batch_Indices,&job);
IndexBufferExceptionFunc();
} catch(...) {
IndexBufferExceptionFunc();
}
}
- // Set index buffer and render!
-
DX8Wrapper::Set_Index_Buffer(dyn_ib_access,0); // Override with this buffer (do something to prevent need for this!)
DX8Wrapper::Set_Vertex_Buffer(dyn_vb_access); // Override with this buffer (do something to prevent need for this!)
DX8Wrapper::Apply_Render_State_Changes();
- unsigned count_to_render=1;
- unsigned start_index=0;
- unsigned node_id=tis[0].idx;
- for (unsigned i=1;i<overlapping_polygon_count;++i) {
- if (node_id!=tis[i].idx) {
+ unsigned run_first_index=0;
+ unsigned run_first_vertex=0;
+ unsigned run_triangles=0;
+ unsigned index_cursor=0;
+ unsigned vertex_cursor=0;
+ unsigned node_id=entries[0].idx;
+ for (unsigned e=0;e<entry_count;++e) {
+ const unsigned entry_node=entries[e].idx;
+ if (entry_node!=node_id) {
SortingNodeStruct* state=overlapping_nodes[node_id];
- Apply_Render_State(state->sorting_state);
-
- DX8Wrapper::Draw_Triangles(
- start_index*3,
- count_to_render,
- state->min_vertex_index,
- state->vertex_count);
-
- count_to_render=0;
- start_index=i;
- node_id=tis[i].idx;
+ SortingNodeStruct* next=overlapping_nodes[entry_node];
+ if (!Same_Draw_State(state->sorting_state,next->sorting_state)) {
+ Apply_Render_State(state->sorting_state);
+ DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
+ run_first_index=index_cursor;
+ run_first_vertex=vertex_cursor;
+ run_triangles=0;
+ }
+ node_id=entry_node;
}
- count_to_render++; //keep track of number of polygons of same kind
+ run_triangles+=Entry_Is_Quad(entries[e]) ? 2 : 1;
+ index_cursor+=Entry_Index_Count(entries[e]);
+ vertex_cursor+=Entry_Vertex_Count(entries[e]);
}
- // Render any remaining polygons...
- if (count_to_render) {
+ Apply_Render_State(overlapping_nodes[node_id]->sorting_state);
+ DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
+}
+
+// ----------------------------------------------------------------------------
+//
+// The pool used to go out as one dynamic vertex buffer and one 16 bit index buffer, so a node that
+// would have taken either past 65535 was refused and not drawn: a screen with a hundred thousand
+// particles on it drew about sixteen thousand of them. EA had left the batching as a @todo right
+// here. Every triangle is still sorted against every other, back to front, and only then written out
+// in batches, in that order.
+//
+// ----------------------------------------------------------------------------
+
+void SortingRendererClass::Flush_Sorting_Pool()
+{
+ if (!overlapping_node_count) return;
+
+ SNAPSHOT_SAY(("SortingSystem - Flush \n"));
+
+ TempIndexStruct* tis=Get_Temp_Index_Array(overlapping_entry_count);
+
+ // Every entry's depth, with its indices kept relative to its own node's first vertex. Each node
+ // writes only its own entries, so once the offsets are known the nodes fill them in parallel.
+ struct NodeDepthJob {
+ static void Run(int node_id,void* context) {
+ TempIndexStruct* tis=(TempIndexStruct*)context;
SortingNodeStruct* state=overlapping_nodes[node_id];
- Apply_Render_State(state->sorting_state);
+ const VertexFormatXYZNDUV2* src_verts=overlapping_node_vertices[node_id];
+ const unsigned polygon_array_offset=overlapping_node_entry_offsets[node_id];
+
+ D3DXMATRIX d3d_mtx=(D3DXMATRIX&)state->sorting_state.world*(D3DXMATRIX&)state->sorting_state.view;
+ const Matrix4x4& mtx=(const Matrix4x4&)d3d_mtx;
+ const bool camera_space=(mtx[0][2] == 0.0f && mtx[1][2] == 0.0f && mtx[3][2] == 0.0f && mtx[2][2] == 1.0f);
+
+ if (state->quads) {
+ const int quad_count=state->polygon_count/2;
+ for (int q=0;q<quad_count;++q) {
+ const VertexFormatXYZNDUV2 *v = src_verts + q*4;
+ TempIndexStruct *tis_ptr = tis + polygon_array_offset + q;
+ tis_ptr->tri.i = (unsigned short)(q*4);
+ tis_ptr->tri.j = 0;
+ tis_ptr->tri.k = QUAD_ENTRY;
+ tis_ptr->idx = node_id;
+ if (camera_space) {
+ tis_ptr->z = (v[0].z + v[1].z + v[2].z + v[3].z)*0.25f;
+ } else {
+ tis_ptr->z = (mtx[0][2]*(v[0].x + v[1].x + v[2].x + v[3].x) +
+ mtx[1][2]*(v[0].y + v[1].y + v[2].y + v[3].y) +
+ mtx[2][2]*(v[0].z + v[1].z + v[2].z + v[3].z))*0.25f + mtx[3][2];
+ }
+ DEBUG_ASSERTCRASH((! _isnan(tis_ptr->z) && _finite(tis_ptr->z)), ("Quad has invalid center"));
+ }
+ return;
+ }
+
+ unsigned short* indices=NULL;
+ SortingIndexBufferClass* index_buffer=static_cast<SortingIndexBufferClass*>(state->sorting_state.index_buffer);
+ WWASSERT(index_buffer);
+ indices=index_buffer->index_buffer;
+ WWASSERT(indices);
+ indices+=state->start_index;
+ indices+=state->sorting_state.iba_offset;
+
+ if (camera_space) {
+ // The common case for particle systems.
+ for (int i=0;i<state->polygon_count;++i) {
+ unsigned short idx1=indices[i*3]-state->min_vertex_index;
+ unsigned short idx2=indices[i*3+1]-state->min_vertex_index;
+ unsigned short idx3=indices[i*3+2]-state->min_vertex_index;
+ WWASSERT(idx1<state->vertex_count);
+ WWASSERT(idx2<state->vertex_count);
+ WWASSERT(idx3<state->vertex_count);
+ const VertexFormatXYZNDUV2 *v1 = src_verts + idx1;
+ const VertexFormatXYZNDUV2 *v2 = src_verts + idx2;
+ const VertexFormatXYZNDUV2 *v3 = src_verts + idx3;
+ unsigned array_index=i+polygon_array_offset;
+ WWASSERT(array_index<overlapping_entry_count);
+ TempIndexStruct *tis_ptr = tis + array_index;
+ tis_ptr->tri.i = idx1;
+ tis_ptr->tri.j = idx2;
+ tis_ptr->tri.k = idx3;
+ tis_ptr->idx = node_id;
+ tis_ptr->z = (v1->z + v2->z + v3->z)/3.0f;
+ DEBUG_ASSERTCRASH((! _isnan(tis_ptr->z) && _finite(tis_ptr->z)), ("Triangle has invalid center"));
+ }
+ } else {
+ for (int i=0;i<state->polygon_count;++i) {
+ unsigned short idx1=indices[i*3]-state->min_vertex_index;
+ unsigned short idx2=indices[i*3+1]-state->min_vertex_index;
+ unsigned short idx3=indices[i*3+2]-state->min_vertex_index;
+ WWASSERT(idx1<state->vertex_count);
+ WWASSERT(idx2<state->vertex_count);
+ WWASSERT(idx3<state->vertex_count);
+ const VertexFormatXYZNDUV2 *v1 = src_verts + idx1;
+ const VertexFormatXYZNDUV2 *v2 = src_verts + idx2;
+ const VertexFormatXYZNDUV2 *v3 = src_verts + idx3;
+ unsigned array_index=i+polygon_array_offset;
+ WWASSERT(array_index<overlapping_entry_count);
+ TempIndexStruct *tis_ptr = tis + array_index;
+ tis_ptr->tri.i = idx1;
+ tis_ptr->tri.j = idx2;
+ tis_ptr->tri.k = idx3;
+ tis_ptr->idx = node_id;
+ tis_ptr->z = (mtx[0][2]*(v1->x + v2->x + v3->x) +
+ mtx[1][2]*(v1->y + v2->y + v3->y) +
+ mtx[2][2]*(v1->z + v2->z + v3->z))/3.0f + mtx[3][2];
+ DEBUG_ASSERTCRASH((! _isnan(tis_ptr->z) && _finite(tis_ptr->z)), ("Triangle has invalid center"));
+ }
+ }
+ }
+ };
- DX8Wrapper::Draw_Triangles(
- start_index*3,
- count_to_render,
- state->min_vertex_index,
- state->vertex_count);
+ unsigned entry_offset=0;
+ for (unsigned node_id=0;node_id<overlapping_node_count;++node_id) {
+ SortingNodeStruct* state=overlapping_nodes[node_id];
+ SortingVertexBufferClass* vertex_buffer=static_cast<SortingVertexBufferClass*>(state->sorting_state.vertex_buffers[0]);
+ WWASSERT(vertex_buffer);
+ VertexFormatXYZNDUV2* src_verts=vertex_buffer->VertexBuffer;
+ WWASSERT(src_verts);
+ src_verts+=state->sorting_state.vba_offset;
+ src_verts+=state->sorting_state.index_base_offset;
+ src_verts+=state->min_vertex_index;
+ overlapping_node_vertices[node_id]=src_verts;
+ overlapping_node_entry_offsets[node_id]=entry_offset;
+ entry_offset+=state->quads ? state->polygon_count/2 : state->polygon_count;
+ }
+ Run_Parallel((int)overlapping_node_count,NODES_PER_CLAIM,NodeDepthJob::Run,tis);
+
+ const TempIndexStruct* sorted=Sort_By_Depth(tis,temp_sort_scratch_array,overlapping_entry_count);
+
+ unsigned batch_start=0;
+ while (batch_start<overlapping_entry_count) {
+ unsigned batch_end=batch_start;
+ unsigned batch_vertices=0;
+ unsigned batch_indices=0;
+ while (batch_end<overlapping_entry_count) {
+ const unsigned vertices=Entry_Vertex_Count(sorted[batch_end]);
+ const unsigned indices=Entry_Index_Count(sorted[batch_end]);
+ if (batch_vertices+vertices>MAX_BATCH_VERTICES || batch_indices+indices>MAX_BATCH_INDICES) {
+ break;
+ }
+ batch_vertices+=vertices;
+ batch_indices+=indices;
+ ++batch_end;
+ }
+ Flush_Sorting_Batch(sorted+batch_start,batch_end-batch_start,batch_vertices,batch_indices);
+ batch_start=batch_end;
}
// Release all references and return nodes back to the clean list for the frame...
- for (node_id=0;node_id<overlapping_node_count;++node_id) {
+ for (unsigned node_id=0;node_id<overlapping_node_count;++node_id) {
SortingNodeStruct* state=overlapping_nodes[node_id];
Release_Refs(state);
clean_list.Add_Head(state);
}
overlapping_node_count=0;
- overlapping_polygon_count=0;
- overlapping_vertex_count=0;
+ overlapping_entry_count=0;
SNAPSHOT_SAY(("SortingSystem - Done flushing\n"));
@@ -723,7 +922,12 @@ void SortingRendererClass::Deinit()
delete[] temp_index_array;
temp_index_array=NULL;
+ delete[] temp_sort_scratch_array;
+ temp_sort_scratch_array=NULL;
temp_index_array_count=0;
+ delete[] batch_offsets;
+ batch_offsets=NULL;
+ batch_offsets_count=0;
}
@@ -762,6 +966,7 @@ void SortingRendererClass::Insert_VolumeParticle(
state->min_vertex_index=min_vertex_index;
state->polygon_count=polygon_count * layerCount;//THIS IS VOLUME_PARTICLE SPECIFIC
state->vertex_count=vertex_count * layerCount;//THIS IS VOLUME_PARTICLE SPECIFIC
+ state->quads=false;
SortingVertexBufferClass* vertex_buffer=static_cast<SortingVertexBufferClass*>(state->sorting_state.vertex_buffers[0]);
WWASSERT(vertex_buffer);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
index 100652529..04159b652 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
@@ -24,6 +24,7 @@
#define SORTING_RENDERER_H
#include "always.h"
+#include <string.h>
class SortingNodeStruct;
class SphereClass;
@@ -49,6 +50,13 @@ public:
unsigned short min_vertex_index,
unsigned short vertex_count);
+ /// Quads laid out four vertices each, in order, from min_vertex_index; the pool sorts one entry
+ /// a quad and does not read the index buffer.
+ static void Insert_Quads(
+ unsigned short quad_count,
+ unsigned short min_vertex_index,
+ unsigned short vertex_count);
+
static void Insert_VolumeParticle(
const SphereClass& bounding_sphere,
unsigned short start_index,
@@ -62,6 +70,26 @@ public:
static void SetMinVertexBufferSize( unsigned val );
+ /// Polygons refused since the start because the pool's node list was full; they are not drawn.
+ static unsigned Get_Refused_Polygon_Count();
+
+ /// Where the flush can hand work to more threads: work(0..count-1, context), returning once all of
+ /// it is done. WW3D2 cannot see the game's job pool, so the device layer installs one; without it
+ /// the work runs inline. The work never allocates and never touches the device.
+ typedef void (*ParallelForFunc)(int count, int granularity, void (*work)(int index, void *context), void *context);
+ static void Set_Parallel_For(ParallelForFunc parallel_for);
+
+ /// A depth as an unsigned key that orders the way the float does, negatives first and -0 just
+ /// below +0; the flush's radix sort buckets on it. The bits come out through memcpy so no
+ /// aliasing rule is bent.
+ static unsigned _Depth_Sort_Key(float depth)
+ {
+ unsigned bits;
+ memcpy(&bits,&depth,sizeof(bits));
+ const unsigned magnitude=bits&0x7FFFFFFFu;
+ return (bits&0x80000000u) ? 0x7FFFFFFFu-magnitude : 0x80000000u+magnitude;
+ }
+
static void _Enable_Triangle_Draw(bool enable) { _EnableTriangleDraw=enable; }
static bool _Is_Triangle_Draw_Enabled() { return _EnableTriangleDraw; }
};
diff --git a/GeneralsMD/Code/Tests/test_dx11twin.cpp b/GeneralsMD/Code/Tests/test_dx11twin.cpp
index 02834f991..e7a13ef6c 100644
--- a/GeneralsMD/Code/Tests/test_dx11twin.cpp
+++ b/GeneralsMD/Code/Tests/test_dx11twin.cpp
@@ -158,6 +158,81 @@ TEST(dx11twin_a_dynamic_buffer_keeps_what_a_no_overwrite_write_did_not_touch)
delete twin;
}
+// A dynamic lock while Direct3D 11 presents asks End not to copy into the D3D9 memory, because
+// Direct3D 9 skips its indexed draws then and nothing reads a D3D9 buffer back. The D3D11 buffer
+// still has to get the write, and the D3D9 block must come back exactly as it was lent.
+TEST(dx11twin_a_lock_that_skips_d3d9_still_uploads_and_leaves_d3d9_alone)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+
+ DX11BufferTwinClass * twin =
+ DX11Twin_Create_Vertex_Buffer(device.Get_Device(), device.Get_Context(), BUFFER_BYTES, true);
+ CHECK(twin != NULL);
+
+ unsigned char d3d9_memory[BUFFER_BYTES];
+ memset(d3d9_memory, UNWRITTEN_BYTE, sizeof(d3d9_memory));
+
+ DX11BufferLockClass lock;
+ memset(lock.Begin(twin, d3d9_memory, 0, RANGE_BYTES, D3DLOCK_DISCARD, false), 0x33, RANGE_BYTES);
+ lock.End();
+
+ unsigned char d3d11_memory[BUFFER_BYTES];
+ CHECK(read_back(device, twin->Buffer(), d3d11_memory, BUFFER_BYTES));
+
+ for (unsigned i = 0; i < RANGE_BYTES; ++i) {
+ CHECK_EQ(d3d11_memory[i], 0x33);
+ }
+ for (unsigned i = 0; i < BUFFER_BYTES; ++i) {
+ CHECK_EQ(d3d9_memory[i], UNWRITTEN_BYTE);
+ }
+
+ delete twin;
+}
+
+// That lock writes straight into the mapped D3D11 buffer rather than the mirror. A second,
+// non-discarding write to another range has to leave the first intact, because the engine fills
+// one dynamic buffer in batches and draws between them.
+TEST(dx11twin_direct_dynamic_writes_keep_what_a_no_overwrite_write_did_not_touch)
+{
+ DX11DeviceClass device;
+ device.Request_Debug_Layer();
+ CHECK(device.Create_Offscreen());
+
+ DX11BufferTwinClass * twin =
+ DX11Twin_Create_Vertex_Buffer(device.Get_Device(), device.Get_Context(), BUFFER_BYTES, true);
+ CHECK(twin != NULL);
+
+ unsigned char d3d9_memory[BUFFER_BYTES];
+ memset(d3d9_memory, UNWRITTEN_BYTE, sizeof(d3d9_memory));
+
+ DX11BufferLockClass first;
+ unsigned char * first_write =
+ (unsigned char *)first.Begin(twin, d3d9_memory, 0, RANGE_BYTES, D3DLOCK_DISCARD, false);
+ CHECK(first_write != twin->Mirror());
+ memset(first_write, 0x44, RANGE_BYTES);
+ first.End();
+
+ DX11BufferLockClass second;
+ memset(second.Begin(twin, d3d9_memory + RANGE_OFFSET, RANGE_OFFSET, RANGE_BYTES,
+ D3DLOCK_NOOVERWRITE, false), 0x55, RANGE_BYTES);
+ second.End();
+
+ unsigned char d3d11_memory[BUFFER_BYTES];
+ CHECK(read_back(device, twin->Buffer(), d3d11_memory, BUFFER_BYTES));
+
+ for (unsigned i = 0; i < RANGE_BYTES; ++i) {
+ CHECK_EQ(d3d11_memory[i], 0x44);
+ CHECK_EQ(d3d11_memory[RANGE_OFFSET + i], 0x55);
+ }
+ for (unsigned i = 0; i < BUFFER_BYTES; ++i) {
+ CHECK_EQ(d3d9_memory[i], UNWRITTEN_BYTE);
+ }
+
+ delete twin;
+}
+
// An append lock, which is how the terrain and the dynamic buffers fill one region at a time. The
// pointer starts at the offset, and everything outside the range is left as it was - a twin that
// uploaded the whole buffer on every partial write would still draw correctly and would cost the
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 02bc5e894..706278c7b 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -9162,6 +9162,38 @@ TEST(an_allocation_inside_a_job_is_counted)
JobSystem::shutdown();
}
+/* A fork made the moment the last one returned finds some workers still on their way back to the
+ wait; a fork made after a pause finds them all asleep. A wake lost in either case hangs this test,
+ and a wake left over from one fork and taken by the next returns before its workers are done,
+ which the visit count sees. A spin-before-sleep version of the pool hung the full test run once
+ on exactly that, and measured worse on the particle scene besides, so the pool sleeps at once. */
+TEST(parallel_for_covers_forks_back_to_back_and_forks_after_a_pause)
+{
+ static const Int BACK_TO_BACK_FORKS = 2000;
+ static const Int PAUSED_FORKS = 20;
+ static const DWORD PAUSE_MS = 5;
+ static const Int ITEMS = 64;
+
+ JobSystem::shutdown();
+ JobSystem::init( 4 );
+
+ for( Int fork = 0; fork < BACK_TO_BACK_FORKS + PAUSED_FORKS; ++fork )
+ {
+ if( fork >= BACK_TO_BACK_FORKS )
+ ::Sleep( PAUSE_MS );
+
+ resetJobVisits();
+ JobSystem::parallel_for( ITEMS, 1, jobTestCount, NULL );
+
+ Int seen = 0;
+ for( Int i = 0; i < ITEMS; ++i )
+ seen += (s_jobVisits[ i ] == 1) ? 1 : 0;
+ CHECK_EQ( ITEMS, seen );
+ }
+
+ JobSystem::shutdown();
+}
+
/* The pool is torn down inside ~GameEngine, on the way out of a process that may be quitting from
anywhere. It has to survive being stopped without ever being started, being stopped twice, and
being started again afterwards - none of which may hang. */
@@ -11543,6 +11575,24 @@ TEST(scenario_parses_a_spawn_line)
CHECK_NEAR( action.spacing, 55.0f, 0.01f );
}
+TEST(scenario_parses_a_particles_line)
+{
+ ScenarioAction action;
+
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "30 particles 0 CINE_JetLenzflareExhaust 250 760 850 25", &action ),
+ (Int)SCENARIO_PARSE_OK );
+ CHECK_EQ( (Int)action.action, (Int)SCENARIO_ACTION_PARTICLES );
+ CHECK_STR( action.selector.str(), "CINE_JetLenzflareExhaust" );
+ CHECK_EQ( action.count, 250 );
+ CHECK_NEAR( action.at.x, 760.0f, 0.01f );
+ CHECK_NEAR( action.at.y, 850.0f, 0.01f );
+ CHECK_NEAR( action.spacing, 25.0f, 0.01f );
+
+ // the same count and position rules as spawn, because it shares spawn's parse
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "30 particles 0 X 0 760 850", &action ), (Int)SCENARIO_PARSE_BAD_COUNT );
+ CHECK_EQ( (Int)ScenarioDrill_parseLine( "30 particles 0 X 5 760", &action ), (Int)SCENARIO_PARSE_MISSING_ARGS );
+}
+
TEST(scenario_parses_the_order_lines)
{
ScenarioAction action;
diff --git a/GeneralsMD/Code/Tests/test_ww3d2.cpp b/GeneralsMD/Code/Tests/test_ww3d2.cpp
index 66084c274..d0d7d6ef9 100644
--- a/GeneralsMD/Code/Tests/test_ww3d2.cpp
+++ b/GeneralsMD/Code/Tests/test_ww3d2.cpp
@@ -1764,3 +1764,22 @@ TEST(surface_draw_h_line_fills_the_run_inclusive_at_both_ends)
CHECK_EQ( *(unsigned int *)buf, 0 );
CHECK_EQ( *(unsigned int *)( buf + 2 * pitch ), 0 );
}
+
+// ---------------------------------------------------------------------------------------------
+// The sorting pool radix-sorts its triangles on an unsigned key made from each depth's bits. A key
+// that orders negatives the wrong way round draws everything behind the camera plane in reverse,
+// and nothing on screen would say why, so the ordering is pinned here across the sign.
+// ---------------------------------------------------------------------------------------------
+#include "sortingrenderer.h"
+
+TEST(sorting_depth_key_orders_the_way_the_depths_do)
+{
+ const float depths[] = { -1.0e30f, -2.5f, -1.0f, -1.0e-30f, -0.0f, 0.0f, 1.0e-30f, 1.0f, 2.5f, 1.0e30f };
+ const unsigned count = sizeof( depths ) / sizeof( depths[ 0 ] );
+
+ for( unsigned i = 1; i < count; ++i )
+ CHECK( SortingRendererClass::_Depth_Sort_Key( depths[ i - 1 ] ) < SortingRendererClass::_Depth_Sort_Key( depths[ i ] ) );
+
+ /* the same depth twice is the same key, which is what keeps equal depths in pooled order */
+ CHECK_EQ( SortingRendererClass::_Depth_Sort_Key( 3.25f ), SortingRendererClass::_Depth_Sort_Key( 3.25f ) );
+}