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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
perf(w3ddevice): particle and smoke map walks once per logic frame
Olcay Seygana774a1a228e5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a57fb4f12..aab90d8d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -170,6 +170,7 @@ found and fixed — EA's own, not port damage.**- 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.- Big fights no longer drag the picture down into the twenties. Every moving tank and soldier, and every puff of smoke, goes to the graphics card through one shared scratch area, and it was so small that a big fight on Bombardment Beach filled it about fifty times a frame. Each refill made the processor wait for the card, 8 to 12ms of every frame, while the card sat two thirds idle. The area is made full size once now and refills about seven times a frame, in 0.02ms. The same 16,000-frame battle, fast-forwarded, finishes in 226 seconds where it took between 263 and 325, and the seconds that fell under 50 frames a second went from 125 or more to 4.- Crowded battles run a good deal faster. At 1080p, thirty Inferno Cannons against twenty Crusaders went from 153 to 227 frames a second, and six Brutal computer players on one map from 146 to 240. The slowest one frame in twenty got 22 to 34% shorter, and the slowest one in a hundred 16 to 29%. The game stopped re-sending lights, materials, textures and card settings that had not changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened low-colour textures with a lookup instead of arithmetic on each pixel. The new renderer keeps the old one's settings back until something actually reads them, re-sends only the half of each draw's settings that changed, and remembers each patch of ground's colours, its blend coordinates and its tread marks between frames. Units whose shadow cannot reach the screen are no longer drawn into the shadow map, except on maps with reflecting water. The command bar and the console replay what they drew last frame when nothing under them moved, and the HUD checks for changes without rebuilding its text. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build in all eight test views on both renderers, and a recorded match plays back to the same checksum.+- A long match costs less late in the game. Four Hard computer players on Twilight Flame, well into the match, went from 111.6 to 136.2 frames a second, and the step that works out the battle from 5.59ms to 4.78ms. The computer left every group it had made and never filled in a list the game went through on every step until the match ended, and that list is cleared now. A unit looking for something to shoot passes over ground that holds nobody it could shoot at, sight is worked out with fewer lookups, and the smoke and fire are gone through once per step instead of once for every picture. Eight views over five maps came out the same as before.- Every animation runs on a clock instead of counting frames.- Tanks and trucks move the same at any frame rate. Their treads scrolled a fixed step every picture, so at 120 frames a second they ran four times too fast, and a tank turning on the spot rolled both treads forward as if it were driving. Each tread now covers exactly the ground under it. In a tight turn the two run against each other, and backing up runs them backwards. Wheels spin with the distance driven the same way. The hull's springs used to settle four times too fast as well, and every start or stop threw the chassis to its full tilt in a single picture. Now a tank squats as it pulls away and dips its nose when it brakes, easing in over a tenth of a second and settling within half a second. In a corner it leans out, a Crusader up to two and a half degrees. The Humvee, which never moved on its springs at all, rocks too. A run drawing one picture per game tick and one drawing fourteen put every tank in the same pose, to the last digit, for as long as neither skipped a tick.- A scroll that starts after the camera has stood still no longer lurches. The first frame of the move was timed from the last time the camera moved, so after a few seconds of looking at one spot it was worth three frames of scrolling at once. The clock runs while the camera is still now, and the first frame moves one frame's worth.diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.hindex 811785455..2115afc1f 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h@@ -719,7 +719,9 @@ public:void setInitialDelay( UnsignedInt delay ) { m_delayLeft = delay; }- AsciiString getParticleTypeName( void ) { return m_particleTypeName; } ///< return the name of the particles+ /// the name of the particles; a reference, as the renderer asks it of every system several times+ /// a frame and a copy is an atomic increment and decrement each+ const AsciiString &getParticleTypeName( void ) const { return m_particleTypeName; }Bool isUsingDrawables( void ) { return (m_particleType == DRAWABLE) ? true : false; }Bool isUsingStreak( void ) { return (m_particleType == STREAK) ? true : false; }Bool isUsingSmudge( void ) { return (m_particleType == SMUDGE) ? true : false; }diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.hindex 2334a08db..a65e85f2d 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h@@ -85,8 +85,48 @@ public:Bool glow; ///< written by the job: the fire's glow is in the normals, not the colour};+ /// One particle the sun's smoke map can take, as the last particle update left it.+ struct SunMapCaster+ {+ Real x, y, z, radius, opticalDepth;+ ParticleSystem * system;+ };++ /// Every particle of a billboarded alpha system that is drawn at all, with the optical depth its+ /// alpha and its system's stealth fade give it, in system list order. Walked once a particle+ /// update; fillSmokeMap culls it to its own sun every pass.+ const std::vector<SunMapCaster> &getSunMapCasters( void );+private:+ /// A system with particles that the local player sees at all, and how much of it.+ struct SystemView+ {+ ParticleSystem * system;+ Real fade; ///< ParticleSystem::getStealthFade, above zero+ };++ void refreshFrameView( void );+std::vector<BillboardFill> m_billboardFills; ///< kept across frames so the fill does not allocate++ /// Nothing moves a particle between two particle updates and nothing but the logic changes a+ /// stealth fade, and both run once a logic frame, so the walk over every system is taken once a+ /// logic frame and every pass drawn until the next one reads this. The counts and the next system+ /// id catch anything that adds or takes a system or a particle away in between; a reset clears it.+ /// That only holds while every add and remove of a system or a particle moves m_particleCount,+ /// m_particleSystemCount or m_uniqueSystemID, and while the stealth look, the opacity and the+ /// attachment that decide a fade change in the logic alone, or in doDrawModule before a pass's first+ /// refresh. Anything else that changes one of them mid-frame is not seen until the next logic frame.+ std::vector<SystemView> m_frameView;+ std::vector<ParticleSystem *> m_fieldSystems; ///< the contamination fields' systems, empty ones too+ std::vector<SunMapCaster> m_sunMapCasters;+ Bool m_frameViewValid;+ Bool m_sunMapCastersValid;+ UnsignedInt m_frameViewLogicFrame;+ UnsignedInt m_frameViewFrame;+ UnsignedInt m_frameViewParticles;+ UnsignedInt m_frameViewSystems;+ ParticleSystemID m_frameViewNextID;};#endif // end __W3DParticleSys_H_diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cppindex 450d1e8e6..db796c884 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp@@ -76,6 +76,7 @@#include "Platform/RenderTypes.h"#include "Lib/Clock.h" // Clock_Ticks: QueryPerformanceCounter on Windows, a monotonic clock elsewhere#include "GameClient/ParticleSys.h"+#include "W3DDevice/GameClient/W3DParticleSys.h"#include "W3DDevice/GameClient/Module/W3DModelDraw.h"#include <algorithm>#include <vector>@@ -3886,15 +3887,22 @@ DECLARE_PERF_TIMER(stencilShadows)DECLARE_PERF_TIMER(shadowVolumeUpdate)DECLARE_PERF_TIMER(shadowVolumeSubmit)-/** Nothing of this frame's smoke is in the map: every system keeps its blob. */+/// The systems the last fill marked, by id: a particle update since may have retired any of them.+static std::vector<ParticleSystemID> s_systemsInSunMap;++/** Nothing of this frame's smoke is in the map: every system keeps its blob. Only a system the last+ fill marked can be marked, so only those are looked up, not every system there is. */static void forgetSmokeInSunMap( void ){if (TheParticleSystemManager == NULL)return;- ParticleSystemManager::ParticleSystemList &systems = TheParticleSystemManager->getAllParticleSystems();- for (ParticleSystemManager::ParticleSystemListIt it = systems.begin(); it != systems.end(); ++it)- if (*it)- (*it)->setInSunMap( FALSE );+ for (size_t i = 0; i < s_systemsInSunMap.size(); ++i)+ {+ ParticleSystem *sys = TheParticleSystemManager->findParticleSystem( s_systemsInSunMap[ i ] );+ if (sys) // gone since, with its mark+ sys->setInSunMap( FALSE );+ }+ s_systemsInSunMap.clear();}/** One particle on its way into the smoke map, with the system it came from and how far it is from@@ -3929,53 +3937,34 @@ static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus, Reif (TheGlobalData->m_volumetricSmokeShadows && TheParticleSystemManager != NULL){- ParticleSystemManager::ParticleSystemList &systems = TheParticleSystemManager->getAllParticleSystems();- for (ParticleSystemManager::ParticleSystemListIt it = systems.begin(); it != systems.end(); ++it)+ // The particles are walked once a particle update (getSunMapCasters); a pass drawn in between,+ // half of them late in a match and most of them early, only culls that list to its own sun.+ const std::vector<W3DParticleSystemManager::SunMapCaster> &candidates =+ ((W3DParticleSystemManager *)TheParticleSystemManager)->getSunMapCasters();+ for (size_t i = 0; i < candidates.size(); ++i){- ParticleSystem *sys = *it;- if (sys == NULL || sys->getShaderType() != ParticleSystemInfo::ALPHA || !sys->shouldBillboard()- || sys->isUsingDrawables() || sys->isUsingStreak() || sys->isUsingSmudge())- continue;- // the heat haze's texture names start with SMUD, as W3DParticleSystemManager::doParticles tests- if (*((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)+ const W3DParticleSystemManager::SunMapCaster &candidate = candidates[ i ];+ const Real radius = candidate.radius;++ // the box the depth map covers, in the sun's own frame: it looks down its -Z+ Vector3 inSun;+ Matrix3D::Inverse_Transform_Vector( sunTransform, Vector3( candidate.x, candidate.y, candidate.z ), &inSun );+ const Real reach = halfWidth + radius;+ if (inSun.X < -reach || inSun.X > reach || inSun.Y < -reach || inSun.Y > reach+ || -inSun.Z < SHADOW_MAP_NEAR_CLIP - radius || -inSun.Z > farClip + radius)continue;- // a stealthed thing's smoke shades the ground only as much as it is drawn- const Real fade = sys->getStealthFade();- if (fade <= 0.0f)- continue;-- const UnsignedInt layers = sys->getVolumeParticleDepth();- for (Particle *p = sys->getFirstParticle(); p; p = p->m_systemNext)- {- const Real opticalDepth = particleSunMapOpticalDepth( p->getAlpha() * fade, layers );- if (opticalDepth <= 0.0f)- continue;- const Coord3D *pos = p->getPosition();- const Real radius = p->getSize() * 0.5f; // the billboard's size is its full width- if (radius <= 0.0f)- continue;-- // the box the depth map covers, in the sun's own frame: it looks down its -Z- Vector3 inSun;- Matrix3D::Inverse_Transform_Vector( sunTransform, Vector3( pos->x, pos->y, pos->z ), &inSun );- const Real reach = halfWidth + radius;- if (inSun.X < -reach || inSun.X > reach || inSun.Y < -reach || inSun.Y > reach- || -inSun.Z < SHADOW_MAP_NEAR_CLIP - radius || -inSun.Z > farClip + radius)- continue;-- SmokeCaster caster;- caster.x = pos->x;- caster.y = pos->y;- caster.z = pos->z;- caster.radius = radius;- caster.opticalDepth = opticalDepth;- const Real dx = pos->x - focus.X;- const Real dy = pos->y - focus.Y;- caster.distanceSqr = dx * dx + dy * dy;- caster.system = sys;- found.push_back( caster );- }+ SmokeCaster caster;+ caster.x = candidate.x;+ caster.y = candidate.y;+ caster.z = candidate.z;+ caster.radius = radius;+ caster.opticalDepth = candidate.opticalDepth;+ const Real dx = candidate.x - focus.X;+ const Real dy = candidate.y - focus.Y;+ caster.distanceSqr = dx * dx + dy * dy;+ caster.system = candidate.system;+ found.push_back( caster );}}@@ -4007,6 +3996,7 @@ static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus, Reif (!found[ i ].system->isInSunMap()){found[ i ].system->setInSunMap( TRUE );+ s_systemsInSunMap.push_back( found[ i ].system->getSystemID() );++systemsHeld;}}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppindex 453224ebc..6aa7a2368 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp@@ -49,6 +49,7 @@#include "GameLogic/Module/LifetimeUpdate.h"#include "GameLogic/PartitionManager.h"#include "GameClient/ObserverCamera.h"+#include <algorithm>#include <map>#ifdef _INTERNAL@@ -586,6 +587,15 @@ static void addFieldPuddle( FieldChunk &chunk, Real cx, Real cy, Real flatZ, Booconst Real c = WWMath::Cos( angle ) * size;const Real s = WWMath::Sin( angle ) * size;const Real step = 2.0f / steps;+ // the buffers grow once a puddle and are written in place: a large field is thousands of vertices+ // and tens of thousands of indices a frame, and a push_back each was most of what it cost+ const size_t firstVertex = s_fieldPos.size();+ s_fieldPos.resize( firstVertex + vertices );+ s_fieldUV.resize( firstVertex + vertices );+ s_fieldGlow.resize( firstVertex + vertices, glowColor );+ s_fieldStain.resize( firstVertex + vertices, stainColor );+ Vector3 *outPos = &s_fieldPos[ firstVertex ];+ Vector2 *outUV = &s_fieldUV[ firstVertex ];for (Int j = 0; j < side; ++j){const Real b = -1.0f + j * step;@@ -595,25 +605,26 @@ static void addFieldPuddle( FieldChunk &chunk, Real cx, Real cy, Real flatZ, Booconst Real x = cx + a * c - b * s;const Real y = cy + a * s + b * c;const Real z = onGround ? TheTerrainRenderObject->getHeightMapHeight( x, y, NULL ) + FIELD_LIFT : flatZ;- s_fieldPos.push_back( Vector3( x, y, z ) );- s_fieldUV.push_back( Vector2( (1.0f - a) * 0.5f, (1.0f - b) * 0.5f ) );- s_fieldGlow.push_back( glowColor );- s_fieldStain.push_back( stainColor );+ (outPos++)->Set( x, y, z );+ (outUV++)->Set( (1.0f - a) * 0.5f, (1.0f - b) * 0.5f );}}const Int base = chunk.vertexCount;+ const size_t firstIndex = s_fieldIndex.size();+ s_fieldIndex.resize( firstIndex + steps * steps * 6 );+ unsigned short *outIndex = &s_fieldIndex[ firstIndex ];for (Int j = 0; j < steps; ++j){for (Int i = 0; i < steps; ++i){const unsigned short v = (unsigned short)(base + j * side + i);- s_fieldIndex.push_back( v );- s_fieldIndex.push_back( (unsigned short)(v + 1) );- s_fieldIndex.push_back( (unsigned short)(v + side) );- s_fieldIndex.push_back( (unsigned short)(v + 1) );- s_fieldIndex.push_back( (unsigned short)(v + side + 1) );- s_fieldIndex.push_back( (unsigned short)(v + side) );+ *outIndex++ = v;+ *outIndex++ = (unsigned short)(v + 1);+ *outIndex++ = (unsigned short)(v + side);+ *outIndex++ = (unsigned short)(v + 1);+ *outIndex++ = (unsigned short)(v + side + 1);+ *outIndex++ = (unsigned short)(v + side);}}chunk.vertexCount += vertices;@@ -717,8 +728,16 @@ struct FieldDrawUnsignedInt seed; ///< the place's hash, for its bubbles};+/** Where one field's puddles lie this frame, for the overlap. */+struct FieldBounds+{+ Real minX, maxX, minY, maxY; ///< of the puddles' centres+ Real maxSize; ///< the largest puddle's half width+};+static std::vector<FieldPuddle> s_fieldPuddles;static std::vector<FieldDraw> s_fieldDraws;+static std::vector<FieldBounds> s_fieldBounds; ///< one a field draw, in their order/** The CLEANUP_HAZARD object with a LifetimeUpdate standing on a field's centre, if there is one. */static ObjectID findFieldObject( const Coord3D ¢re )@@ -795,8 +814,9 @@ static Real fieldFade( FieldState &state, Int now )}/** Collects this frame's fields from their systems and lays them on the terrain into the field- * buffers; drawGroundFields draws them. Returns the puddles laid. */-static Int collectGroundFields( ParticleSystemManager::ParticleSystemList &systems, const AABoxClass &view )+ * buffers; drawGroundFields draws them. Returns the puddles laid. `systems` is every isGroundField+ * system in list order, empty ones too. */+static Int collectGroundFields( const std::vector<ParticleSystem *> &systems, const AABoxClass &view ){const Int now = (Int)TheGameLogic->getFrame();// between the last two logic ticks, as the models are, so a pulse does not step at the logic rate@@ -805,12 +825,9 @@ static Int collectGroundFields( ParticleSystemManager::ParticleSystemList &systes_fieldDraws.clear();// where the fields are this frame, and what each one looks like- for (ParticleSystemManager::ParticleSystemListIt it = systems.begin(); it != systems.end(); ++it)+ for (size_t f = 0; f < systems.size(); ++f){- ParticleSystem *sys = *it;- if (!sys || sys->isUsingDrawables() || !isGroundField( sys ))- continue;-+ ParticleSystem *sys = systems[ f ];Coord3D pos;sys->getPosition( &pos );FieldKey key = { sys->getTemplate(), REAL_TO_INT_FLOOR( pos.x + 0.5f ), REAL_TO_INT_FLOOR( pos.y + 0.5f ) };@@ -991,20 +1008,57 @@ static Int collectGroundFields( ParticleSystemManager::ParticleSystemList &syste// goes over FIELD_STACK, so the whole pool tops out at about that many puddles' worth. A// neighbour counts at its own fade, so a field coming up or going out dims the others with it// rather than in one frame.- // ponytail: every pair, a few hundred puddles on the map at most; a grid when a map holds more- const Int puddleCount = (Int)s_fieldPuddles.size();- for (Int i = 0; i < puddleCount; ++i)+ //+ // A field's puddles lie inside the box of their own centres and reach no further past it than its+ // largest puddle, so two fields whose boxes stand further apart on an axis than their two largest+ // puddles together add nothing to each other and their pairs are not tried. The rest still sum in+ // puddle order, so every overlap comes out as it did; the margin is wide enough that no pair left+ // out could have rounded to a t above zero.+ // ponytail: every pair of near fields, a few hundred puddles on the map at most; a grid when a+ // map holds more+ const Int fieldCount = (Int)s_fieldDraws.size();+ s_fieldBounds.resize( fieldCount );+ for (Int d = 0; d < fieldCount; ++d){- FieldPuddle &p = s_fieldPuddles[ i ];- p.overlap = 1.0f;- for (Int j = 0; j < puddleCount; ++j)+ FieldBounds &b = s_fieldBounds[ d ];+ const FieldPuddle &first = s_fieldPuddles[ s_fieldDraws[ d ].firstPuddle ];+ b.minX = b.maxX = first.x;+ b.minY = b.maxY = first.y;+ b.maxSize = first.size;+ for (Int i = s_fieldDraws[ d ].firstPuddle + 1; i < s_fieldDraws[ d ].firstPuddle + s_fieldDraws[ d ].puddleCount; ++i){- const FieldPuddle &q = s_fieldPuddles[ j ];- const Real reach = p.size + q.size;- const Real dx = p.x - q.x, dy = p.y - q.y;- const Real t = 1.0f - (dx * dx + dy * dy) / (reach * reach);- if (j != i && t > 0.0f)- p.overlap += t * t * q.fade;+ const FieldPuddle &p = s_fieldPuddles[ i ];+ b.minX = WWMath::Min( b.minX, p.x ); b.maxX = WWMath::Max( b.maxX, p.x );+ b.minY = WWMath::Min( b.minY, p.y ); b.maxY = WWMath::Max( b.maxY, p.y );+ b.maxSize = WWMath::Max( b.maxSize, p.size );+ }+ }+ for (Int a = 0; a < fieldCount; ++a)+ {+ const FieldBounds &ba = s_fieldBounds[ a ];+ const Int aEnd = s_fieldDraws[ a ].firstPuddle + s_fieldDraws[ a ].puddleCount;+ for (Int i = s_fieldDraws[ a ].firstPuddle; i < aEnd; ++i)+ {+ FieldPuddle &p = s_fieldPuddles[ i ];+ p.overlap = 1.0f;+ for (Int f = 0; f < fieldCount; ++f)+ {+ const FieldBounds &bf = s_fieldBounds[ f ];+ const Real apart = (ba.maxSize + bf.maxSize) * 1.01f + 0.01f;+ if (bf.minX - ba.maxX > apart || ba.minX - bf.maxX > apart+ || bf.minY - ba.maxY > apart || ba.minY - bf.maxY > apart)+ continue;+ const Int fEnd = s_fieldDraws[ f ].firstPuddle + s_fieldDraws[ f ].puddleCount;+ for (Int j = s_fieldDraws[ f ].firstPuddle; j < fEnd; ++j)+ {+ const FieldPuddle &q = s_fieldPuddles[ j ];+ const Real reach = p.size + q.size;+ const Real dx = p.x - q.x, dy = p.y - q.y;+ const Real t = 1.0f - (dx * dx + dy * dy) / (reach * reach);+ if (j != i && t > 0.0f)+ p.overlap += t * t * q.fade;+ }+ }}}@@ -1137,6 +1191,14 @@ W3DParticleSystemManager::W3DParticleSystemManager()m_onScreenParticleCount = 0;+ m_frameViewValid = FALSE;+ m_sunMapCastersValid = FALSE;+ m_frameViewLogicFrame = 0;+ m_frameViewFrame = 0;+ m_frameViewParticles = 0;+ m_frameViewSystems = 0;+ m_frameViewNextID = INVALID_PARTICLE_SYSTEM_ID;+m_pointGroup = NEW PointGroupClass();//m_streakLine = NULL;m_streakLine = NEW StreakLineClass();@@ -1170,9 +1232,158 @@ void W3DParticleSystemManager::reset(){ParticleSystemManager::reset();s_fireLightsValid = FALSE;+ m_frameViewValid = FALSE; // its systems are gone+ m_frameView.clear();+ m_fieldSystems.clear();+ m_sunMapCasters.clear();s_fieldStates.clear(); // the object IDs it holds belong to the game that ended}+/** The systems a pass draws from, walked again only when a particle update or anything else that+ * adds or takes away a system or a particle has run since the last walk. A system with no+ * particles draws nothing and one the local player cannot see is skipped, so neither is kept. */+void W3DParticleSystemManager::refreshFrameView( void )+{+ const UnsignedInt logicFrame = TheGameLogic->getFrame();+ if (m_frameViewValid && m_frameViewLogicFrame == logicFrame && m_frameViewFrame == m_lastLogicFrameUpdate+ && m_frameViewParticles == m_particleCount && m_frameViewSystems == m_particleSystemCount+ && m_frameViewNextID == m_uniqueSystemID)+ return;++ m_frameView.clear();+ m_fieldSystems.clear();+ for (ParticleSystemListIt it = m_allParticleSystemList.begin(); it != m_allParticleSystemList.end(); ++it)+ {+ ParticleSystem *sys = *it;+ if (sys == NULL || sys->isUsingDrawables())+ continue;+ // a field is kept with no particles too: its system still says where the pool is+ if (isGroundField( sys ))+ m_fieldSystems.push_back( sys );+ if (sys->getParticleCount() == 0)+ continue;+ const Real fade = sys->getStealthFade();+ if (fade <= 0.0f)+ continue;+ SystemView view;+ view.system = sys;+ view.fade = fade;+ m_frameView.push_back( view );+ }++ m_frameViewValid = TRUE;+ m_sunMapCastersValid = FALSE;+ m_frameViewLogicFrame = logicFrame;+ m_frameViewFrame = m_lastLogicFrameUpdate;+ m_frameViewParticles = m_particleCount;+ m_frameViewSystems = m_particleSystemCount;+ m_frameViewNextID = m_uniqueSystemID;+}++/** One smoke system's share of the walk getSunMapCasters hands the job pool: the room reserved for+ * its particles in the caster list, and how many of them its job kept. */+struct SunMapWalk+{+ ParticleSystem * system;+ Real fade; ///< its stealth fade: a stealthed thing's smoke shades only as much as it is drawn+ UnsignedInt layers; ///< ParticleSystem::getVolumeParticleDepth+ Int first; ///< its first slot in the caster list+ Int capacity; ///< its particles+ Int kept; ///< written by the job+};++struct SunMapWalkJob+{+ SunMapWalk * walks;+ W3DParticleSystemManager::SunMapCaster * casters;+};++/// systems a pool thread claims at once; most smoke systems are a handful of particles+static const Int SUN_MAP_WALKS_PER_CLAIM = 8;++static std::vector<SunMapWalk> s_sunMapWalks; ///< kept so the walk does not allocate++/** One system's particles into its own slots of the caster list. Reads its particles and writes only+ * those slots and its own walk: no allocation, nothing another job touches. */+static void walkSunMapCasters( Int index, void *context )+{+ SunMapWalkJob *job = (SunMapWalkJob *)context;+ SunMapWalk &walk = job->walks[ index ];+ W3DParticleSystemManager::SunMapCaster *out = job->casters + walk.first;+ Int kept = 0;+ for (Particle *p = walk.system->getFirstParticle(); p && kept < walk.capacity; p = p->m_systemNext)+ {+ const Real opticalDepth = particleSunMapOpticalDepth( p->getAlpha() * walk.fade, walk.layers );+ if (opticalDepth <= 0.0f)+ continue;+ const Real radius = p->getSize() * 0.5f; // the billboard's size is its full width+ if (radius <= 0.0f)+ continue;+ const Coord3D *pos = p->getPosition();+ out[ kept ].x = pos->x;+ out[ kept ].y = pos->y;+ out[ kept ].z = pos->z;+ out[ kept ].radius = radius;+ out[ kept ].opticalDepth = opticalDepth;+ out[ kept ].system = walk.system;+ ++kept;+ }+ walk.kept = kept;+}++/** See W3DParticleSys.h. A ground-aligned system is a decal already, fire is additive and casts+ * nothing, and the heat haze's texture names start with SMUD, as doParticles tests. The particles+ * are walked on the job pool, each system into room reserved for it in list order, and the gaps+ * the faint ones leave are closed in the same order, so the list is the one a serial walk makes. */+const std::vector<W3DParticleSystemManager::SunMapCaster> &W3DParticleSystemManager::getSunMapCasters( void )+{+ refreshFrameView();+ if (m_sunMapCastersValid)+ return m_sunMapCasters;++ s_sunMapWalks.clear();+ Int reserved = 0;+ for (size_t v = 0; v < m_frameView.size(); ++v)+ {+ ParticleSystem *sys = m_frameView[ v ].system;+ if (sys->getShaderType() != ParticleSystemInfo::ALPHA || !sys->shouldBillboard()+ || sys->isUsingStreak() || sys->isUsingSmudge())+ continue;+ if (*((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)+ continue;++ SunMapWalk walk;+ walk.system = sys;+ walk.fade = m_frameView[ v ].fade;+ walk.layers = sys->getVolumeParticleDepth();+ walk.first = reserved;+ walk.capacity = (Int)sys->getParticleCount();+ walk.kept = 0;+ reserved += walk.capacity;+ s_sunMapWalks.push_back( walk );+ }++ m_sunMapCasters.resize( (size_t)reserved );+ SunMapWalkJob job;+ job.walks = s_sunMapWalks.empty() ? NULL : &s_sunMapWalks[ 0 ];+ job.casters = m_sunMapCasters.empty() ? NULL : &m_sunMapCasters[ 0 ];+ JobSystem::parallel_for( (Int)s_sunMapWalks.size(), SUN_MAP_WALKS_PER_CLAIM, walkSunMapCasters, &job );++ size_t kept = 0;+ for (size_t w = 0; w < s_sunMapWalks.size(); ++w)+ {+ const SunMapWalk &walk = s_sunMapWalks[ w ];+ if (kept != (size_t)walk.first)+ std::copy( m_sunMapCasters.begin() + walk.first, m_sunMapCasters.begin() + walk.first + walk.kept,+ m_sunMapCasters.begin() + kept );+ kept += walk.kept;+ }+ m_sunMapCasters.resize( kept );++ m_sunMapCastersValid = TRUE;+ return m_sunMapCasters;+}+/*** Hack because DoParticles is called from Flush(), which is called* multiple times per frame. We only want to render once.@@ -1240,20 +1451,18 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)tFillStart = Clock_Ticks();#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.+ // alpha-tested systems stay in that loop as they were. Both loops walk the frame view, which+ // leaves out what neither would draw: drawable systems, empty ones and ones the player cannot see.+ refreshFrameView();m_billboardFills.clear();- for( ParticleSystemManager::ParticleSystemListIt it = particleSysList.begin(); it != particleSysList.end(); ++it)+ for (size_t v = 0; v < m_frameView.size(); ++v){- ParticleSystem *sys = (*it);- if (!sys || sys->isUsingDrawables())- continue;+ ParticleSystem *sys = m_frameView[ v ].system;if (*((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)continue;@@ -1264,13 +1473,7 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)continue;const Int particles = (Int)sys->getParticleCount();- if (particles == 0)- continue;-- fill.fade = sys->getStealthFade();- if (fill.fade <= 0.0f)- continue;-+ fill.fade = m_frameView[ v ].fade;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;@@ -1300,18 +1503,10 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)|| s_fireLightsParticles != m_particleCount || s_fireLightsSystems != m_particleSystemCount){s_fireLights.clear();- for( ParticleSystemManager::ParticleSystemListIt it = particleSysList.begin(); it != particleSysList.end(); ++it)- {- ParticleSystem *sys = *it;- if (sys && !sys->isUsingDrawables() && sys->getShaderType() == ParticleSystemInfo::ADDITIVE- && sys->getParticleCount() > 0)- {- // a hidden fire lights nothing, an own stealthed one only as much as it shows- const Real fade = sys->getStealthFade();- if (fade > 0.0f)- gatherFireLight( sys, fade );- }- }+ // a hidden fire lights nothing, an own stealthed one only as much as it shows+ for (size_t v = 0; v < m_frameView.size(); ++v)+ if (m_frameView[ v ].system->getShaderType() == ParticleSystemInfo::ADDITIVE)+ gatherFireLight( m_frameView[ v ].system, m_frameView[ v ].fade );s_fireLightsValid = TRUE;s_fireLightsFrame = m_lastLogicFrameUpdate;s_fireLightsParticles = m_particleCount;@@ -1329,7 +1524,7 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)s_fieldIndex.clear();s_fieldChunks.clear();{- const Int puddles = collectGroundFields( particleSysList, bbox );+ const Int puddles = collectGroundFields( m_fieldSystems, bbox );// counted as field particles on purpose: past MaxFieldParticleCount the field systems keep// one particle each, and that one is all the steady pool needs from themm_fieldParticleCount += puddles;@@ -1338,21 +1533,24 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)drawGroundFields();size_t nextFill = 0;- for( ParticleSystemManager::ParticleSystemListIt it = particleSysList.begin(); it != particleSysList.end(); ++it)+ for (size_t v = 0; v < m_frameView.size(); ++v){- ParticleSystem *sys = (*it);- if (!sys) {- continue;- }+ ParticleSystem *sys = m_frameView[ v ].system;+ const Real fade = m_frameView[ v ].fade;- // only look at particle/point style systems- if (sys->isUsingDrawables())- continue;-- // the same answer the billboard reservation above had, so a skipped system is skipped here too- const Real fade = sys->getStealthFade();- if (fade <= 0.0f)+ // first, as a reserved system is never a smudge+ 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.glow != FALSE );+ 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;+#endifcontinue;+ }//temporary hack that checks if texture name starts with "SMUD" - if so, we can assume it's a smudge typeif (/*sys->isUsingSmudge()*/ *((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)@@ -1390,19 +1588,6 @@ 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.glow != FALSE );- 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;- }-if (isGroundField( sys ))continue; // drawn above, every field at once