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
feat(gameclient): paint the ground a defence can hit on the terrain
Olcay Seygan7646d9fc8953
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dee3cf45a..d9f152532 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ found and fixed, EA's own, not port damage.**---+## The ground a defence can hit++- Click one of your defences, or put a new one on the cursor, and the ground it fires on is painted on the terrain in your colour: a quiet wash with a sharp line round its edge, lying over the hills and down the slopes, under your units and buildings. While a building is on the cursor every defence of yours and your allies' shows its ground as well, so the gap between two Patriot batteries is something you see before you pay for a third. The enemy's defences show nothing. This came back after the one-interface change took the old range ring away with the Reforged interface.+- Only ground the defence really hits is painted. Every spot is put to the same questions the game asks before a defence fires on its own: is the target in reach, with the extra reach high ground gives; does a hill or a building stand in the line of the shot; can you see the spot at all; is it too close, the way the patch under a Fire Base's walls is. A spot is painted only if the answer is yes for the lowest raider and the widest tank in the game, and for every gun the defence might pick for it. Where the edge steps round the corner of a building or along the brow of a hill, that is the game's own grid: the shot is decided square by square there, and a smoother line would paint ground the defence cannot hit. The old ring was drawn flat on the screen, over the units, and for weeks it ringed a Patriot at its 450 assist missile when it shoots tanks out to 225.+- A Patriot battery shows where it shoots ground targets by itself. The long missile it fires only when another Patriot calls for help is left out, so is its anti-aircraft missile, and so is anything in the air. A defence with no power, or one that has been hacked or hit by an EMP, shows nothing, because it fires at nothing.+- Checked against the game itself. On Twilight Flame's hilly south-west plateau a Patriot, a Fire Base and a Gattling Cannon had their painted ground sampled at 3,490 random spots, with a Combat Cycle, a Rebel or an Overlord standing on each and the game asked whether the defence would fire: it would, on all 3,490. Leave the hill test out of the painting and the same check finds 51 to 338 painted spots per run the Patriot never shoots at.+## What a rank gives- America, China and GLA units now get what their rank ladder on the website promises. Rank has always raised a unit's stats; now certain grades also add a perk of their own, and the officers and leaders further up the ladder carry an aura that helps friendly units around them.diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 7273e15d9..29e63d1de 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -140,6 +140,7 @@ Data/Cinema/rankaurasnow.txtData/Cinema/rankladder.txtData/Cinema/rankringsall.txtData/Cinema/rankzero.txt+Data/Cinema/reachhills.txtData/Cinema/readme_water.txtData/Cinema/rf_ai.txtData/Cinema/rf_ai_wave.txt@@ -386,6 +387,8 @@ Data/Scenarios/rankaurawiki.txtData/Scenarios/rankladder.txtData/Scenarios/rankringsall.txtData/Scenarios/rankzero.txt+Data/Scenarios/reachhills.txt+Data/Scenarios/reachproof.txtData/Scenarios/reachshot.txtData/Scenarios/readme_hud.txtData/Scenarios/readme_water.txt@@ -749,6 +752,7 @@ GameEngine/Include/GameClient/PlayerColorScheme.hGameEngine/Include/GameClient/ProcessAnimateWindow.hGameEngine/Include/GameClient/RadiusDecal.hGameEngine/Include/GameClient/RayEffect.h+GameEngine/Include/GameClient/ReachOverlay.hGameEngine/Include/GameClient/SelectionInfo.hGameEngine/Include/GameClient/SelectionPriority.hGameEngine/Include/GameClient/SelectionXlat.h@@ -1399,6 +1403,7 @@ GameEngine/Source/GameClient/ObserverCamera.cppGameEngine/Source/GameClient/ParabolicEase.cppGameEngine/Source/GameClient/PlayerColorScheme.cppGameEngine/Source/GameClient/RadiusDecal.cpp+GameEngine/Source/GameClient/ReachOverlay.cppGameEngine/Source/GameClient/SelectionInfo.cppGameEngine/Source/GameClient/Snow.cppGameEngine/Source/GameClient/Statistics.cpp@@ -1823,6 +1828,7 @@ GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.hGameEngineDevice/Include/W3DDevice/GameClient/W3DPoly.hGameEngineDevice/Include/W3DDevice/GameClient/W3DProjectedShadow.hGameEngineDevice/Include/W3DDevice/GameClient/W3DPropBuffer.h+GameEngineDevice/Include/W3DDevice/GameClient/W3DReachOverlay.hGameEngineDevice/Include/W3DDevice/GameClient/W3DRoadBuffer.hGameEngineDevice/Include/W3DDevice/GameClient/W3DScene.hGameEngineDevice/Include/W3DDevice/GameClient/W3DShaderManager.h@@ -1922,6 +1928,7 @@ GameEngineDevice/Source/W3DDevice/Common/W3DConvert.cppGameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cppGameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cppGameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cpp+GameEngineDevice/Source/W3DDevice/GameClient/DX11ReachOverlay.cppGameEngineDevice/Source/W3DDevice/GameClient/DX11VolumeSmoke.cppGameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cppGameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp@@ -2006,6 +2013,7 @@ GameEngineDevice/Source/W3DDevice/GameClient/W3DMouse.cppGameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppGameEngineDevice/Source/W3DDevice/GameClient/W3DPoly.cppGameEngineDevice/Source/W3DDevice/GameClient/W3DPropBuffer.cpp+GameEngineDevice/Source/W3DDevice/GameClient/W3DReachOverlay.cppGameEngineDevice/Source/W3DDevice/GameClient/W3DRoadBuffer.cppGameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cppGameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cppdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 7020c1571..2cd4f6c71 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -1544,6 +1544,9 @@ if(ZH_PLATFORM_POSIX)list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/DX11GpuParticles\\.cpp$")# The -volsmoke smoke volumes are Direct3D 11's alone; W3DParticleSys calls them only on Windows.list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/DX11VolumeSmoke\\.cpp$")+ # The reach overlay's Direct3D 11 pass; W3DReachOverlay.cpp calls it only on Windows and draws the+ # fixed-function sheet without it.+ list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/DX11ReachOverlay\\.cpp$")# ---- the movies (V1): Windows' Bink player and its Bink API on FFmpeg, the same two files -------------# FFmpeg is built from the tarball Tools/vendor.sh keeps, into the build tree, with the Bink demuxerdiff --git a/GeneralsMD/Code/Data/Scenarios/reachhills.txt b/GeneralsMD/Code/Data/Scenarios/reachhills.txtnew file mode 100644index 000000000..55074b311--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/reachhills.txt@@ -0,0 +1,16 @@+# The reach overlay on hilly ground, for a picture: reachproof's defences on Twilight Flame's+# south-west plateau, with an American seat that plays (no -observer), so a click on a defence+# selects it and its ground is painted. Nobody thinks (-takeover); the enemy stays at home.+#+# generals.exe -win -borderless -xres 1920 -yres 1080 -quickstart -noshellmap -multiInstance+# -map "Maps\Twilight Flame\Twilight Flame.map" -autoskirmish 2 -takeover+# -side 0 FactionAmerica -side 1 FactionGLA -seed 1 -scenario reachhills -control <port>+#+# See mobstress.txt for the line grammar.++30 spawn 0 AmericaPowerPlant 1 3600 4150+30 spawn 0 AmericaPowerPlant 1 3700 4150++30 spawn 0 AmericaPatriotBattery 1 3400 3700+30 spawn 0 AmericaFireBase 1 3550 3950+30 spawn 0 ChinaGattlingCannon 1 3300 3950diff --git a/GeneralsMD/Code/Data/Scenarios/reachproof.txt b/GeneralsMD/Code/Data/Scenarios/reachproof.txtnew file mode 100644index 000000000..268a18246--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/reachproof.txt@@ -0,0 +1,40 @@+# Does the reach overlay lie? Each defence's field, and its template's on the placement cursor at+# the same spot, against the logic itself: a GLA probe is stood on random points inside the lit+# ground, outside it and within 6 of its edge, and asked the way an idle defence asks (the mood+# target search, the fog, the chosen weapon's range and attack tests). Every HEADLESS REACHPROOF+# block ends PASS or FAIL with its count of lies: lit points the logic refused.+#+# Twilight Flame's south-west plateau: its rim drops to the south of y 3620, so the Patriot looks+# down a cliff and the Fire Base and the Gattling Cannon across uneven ground; the ground sampled+# spans 25 to 152 high. Three probes: a low raider (Combat Cycle), a soldier, and a wide tank+# (Overlord), parked by slot 1's start, the soldier away from the cycle so he does not climb on it,+# and moved by the proof. Nobody thinks (-takeover).+#+# 2026-10-28: every block PASS, 0 lies; with the line of sight test taken out of the overlay the+# Patriot read 51, 338 and 332 lies and the Fire Base 84 each, so the check catches a missing test.+#+# generals.exe -headless -quickstart -noshellmap -observer -multiInstance -noFPSLimit+# -map "Maps\Twilight Flame\Twilight Flame.map" -autoskirmish 2 -takeover+# -side 0 FactionAmerica -side 1 FactionGLA -seed 1 -maxframes 900+# -scenario reachproof -logPrefix reachproof_+#+# See mobstress.txt for the line grammar.++30 spawn 0 AmericaPowerPlant 1 3600 4150+30 spawn 0 AmericaPowerPlant 1 3700 4150++30 spawn 0 AmericaPatriotBattery 1 3400 3700+30 spawn 0 AmericaFireBase 1 3550 3950+30 spawn 0 ChinaGattlingCannon 1 3300 3950++30 spawn 1 GLAVehicleCombatBike 1 start1:200:0+30 spawn 1 GLAInfantryRebel 1 start1:-250:-250+30 spawn 1 ChinaTankOverlord 1 start1:200:120++200 reachproof 0 AmericaPatriotBattery 1 GLAVehicleCombatBike 300+200 reachproof 0 AmericaPatriotBattery 1 GLAInfantryRebel 300+200 reachproof 0 AmericaPatriotBattery 1 ChinaTankOverlord 300+200 reachproof 0 AmericaFireBase 1 GLAVehicleCombatBike 300+200 reachproof 0 AmericaFireBase 1 ChinaTankOverlord 300+200 reachproof 0 ChinaGattlingCannon 1 GLAVehicleCombatBike 300+200 reachproof 0 ChinaGattlingCannon 1 ChinaTankOverlord 300diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ReachOverlay.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ReachOverlay.hnew file mode 100644index 000000000..ca841ec7e--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ReachOverlay.h@@ -0,0 +1,52 @@+// The ground a defence can hit, as the renderer draws it: a signed distance field on a world+// aligned grid for each defence shown this frame. GameClient fills it (ReachOverlay.cpp), the+// device draws it on the terrain. Nothing here goes back into the logic.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#ifndef __REACHOVERLAY_H__+#define __REACHOVERLAY_H__++#include "Lib/BaseType.h"+#include "Common/GameType.h"+#include <vector>++class Object;+class ThingTemplate;++/** One defence's hittable ground. Sample (i, j) sits at world (originX + i * step, originY + j * step).+ * distance[ j * width + i ] is in world units: positive inside the ground the defence can hit, negative+ * outside, nought on the edge, clamped to +-distanceLimit. The edge drawn where the field taken+ * bilinearly crosses nought lies only in grid cells whose four corners the logic's own tests passed+ * (ReachOverlay.cpp says how), so the renderer must not grow the area: draw nothing where the+ * filtered distance is at or under nought. */+struct ReachOverlayField+{+ Real originX;+ Real originY;+ Real step;+ Int width;+ Int height;+ Real distanceLimit;+ std::vector< Real > distance;+ Color color; ///< the owner's colour, alpha ignored+ Real opacity; ///< 0..1, the whole area's strength this frame+ UnsignedInt version; ///< changes whenever distance or the grid changes, so a texture can be kept+};++/** The fields to draw this frame, in no particular order. Empty when nothing is shown, and always+ * empty headless. The pointers stay valid until the next GameClient update. */+void ReachOverlay_getFields( std::vector< const ReachOverlayField * > &out );++/** Work out this frame's fields: the selected defences of the local player, an ally or (to an+ * observer) anyone, and while a building is on the cursor every such defence plus the one on the+ * cursor. InGameUI::update calls it once a frame. */+void ReachOverlay_update( void );++/** Sample a standing defence's field, and its template's on the cursor at the same spot, against+ * the logic's own acquisition and fire tests with the probe Object standing on each sample point,+ * and write the mismatch counts as HEADLESS REACHPROOF lines. Moves the probe and runs the+ * partition: a scenario's reachproof line only. TRUE when no lit point was refused. */+Bool ReachOverlay_prove( Object *defence, Object *probe, Int samples );++#endifdiff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.hindex bf78ae4d7..409a22cfb 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/AIPathfind.h@@ -1046,6 +1046,7 @@ public:Bool isViewBlockedByObstacle(const Object* obj, const Object* objOther); ///< Return true if the straight line between the given points contains any obstacle, and thus blocks visionBool isAttackViewBlockedByObstacle(const Object* obj, const Coord3D& attackerPos, const Object* victim, const Coord3D& victimPos); ///< Return true if the straight line between the given points contains any obstacle, and thus blocks vision+ Bool isGroundViewBlockedByObstacle(const Coord3D& attackerPos, const Coord3D& victimPos, ObjectID standingIn = INVALID_ID); ///< the same walk for a ground shooter and target that are no Objects (the placement cursor's reach overlay)Bool isLinePassable( const Object *obj, LocomotorSurfaceTypeMask acceptableSurfaces,PathfindLayerEnum layer, const Coord3D& startWorld, const Coord3D& endWorld,diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.hindex f98ee7fea..038a393c1 100644--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h@@ -96,7 +96,8 @@ enum ScenarioActionTypeSCENARIO_ACTION_REPEAT, ///< repeat <slot> <building> <template> on|off; the Ctrl+Alt build key, as MSG_SET_REPEAT_UNIT onto the message streamSCENARIO_ACTION_RANK, ///< rank <slot> <selector> veteran|elite|heroic|xp N|grade N; a level as the rank cheat sets it (a ladder's pin), N same-class kills of experience, or a ladder gradeSCENARIO_ACTION_GIVEMONEY, ///< givemoney <slot> <targetSlot> <amount>; the Tab screen's Send, as MSG_TRANSFER_MONEY onto the message stream- SCENARIO_ACTION_CLICKSTOP ///< clickstop <slot> <selector>; the Stop key, the group idle MSG_DO_STOP gives (CMD_FROM_PLAYER)+ SCENARIO_ACTION_CLICKSTOP, ///< clickstop <slot> <selector>; the Stop key, the group idle MSG_DO_STOP gives (CMD_FROM_PLAYER)+ SCENARIO_ACTION_REACHPROOF ///< reachproof <slot> <selector> <targetSlot> <probe> [samples]; every matching defence's reach overlay against the logic, the probe stood on each sample point (ReachOverlay_prove)};/// ScenarioAction::atStart when the position is plain numbersdiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex fa64d16b1..d320b00de 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -101,6 +101,7 @@#include "GameClient/WindowLayout.h"#include "GameClient/LookAtXlat.h"#include "GameClient/ParticleSys.h"+#include "GameClient/ReachOverlay.h"#include "GameClient/SelectionXlat.h"#include "GameClient/Shadow.h"#include "GameClient/GlobalLanguage.h"@@ -2564,6 +2565,7 @@ void InGameUI::update( void )if( TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() )watchDozers();updateSignalMarks();+ ReachOverlay_update(); // the ground a selected or sited defence hits, drawn on the terrainUnsignedByte r, g, b, a;Int amount;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/ReachOverlay.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/ReachOverlay.cppnew file mode 100644index 000000000..0ed89d1be--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/ReachOverlay.cpp@@ -0,0 +1,966 @@+// The ground a defence can hit, worked out with the logic's own tests and handed to the renderer+// as a signed distance field (ReachOverlay.h). Client side: it reads the logic and writes nothing+// back, and it draws no logic random number. ReachOverlay_prove is the check that the picture+// does not lie; a scenario's reachproof line runs it.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.++#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine++#include "GameClient/ReachOverlay.h"++#include "Common/GlobalData.h"+#include "Common/LogicThread.h"+#include "Common/Player.h"+#include "Common/PlayerList.h"+#include "Common/ThingFactory.h"+#include "Common/ThingTemplate.h"+#include "GameClient/Drawable.h"+#include "GameClient/GameClient.h"+#include "GameClient/InGameUI.h"+#include "GameClient/PlayerColorScheme.h"+#include "GameLogic/AI.h"+#include "GameLogic/AIPathfind.h"+#include "GameLogic/GameLogic.h"+#include "GameLogic/Module/AIUpdate.h"+#include "GameLogic/Object.h"+#include "GameLogic/PartitionManager.h"+#include "GameLogic/TerrainLogic.h"+#include "GameLogic/Weapon.h"+#include "GameLogic/WeaponSet.h"++#include <chrono>+#include <map>+#include <random>++//-------------------------------------------------------------------------------------------------+// What is shown, and why it can be trusted.+//+// A ground cell is lit for a defence only if every test the logic puts an idle defence through+// before it fires at a ground target there passes, asked of the same functions with the defence's+// own Object:+//+// - getNextMoodTarget's search: the defence's adjusted vision range (TheAI's, with the mood and+// owner factors), stretched by the high ground the way PartitionFilterElevatedReach stretches it;+// - its line of sight, for a defence the INI marks ATTACK_NEEDS_LINE_OF_SIGHT: the terrain line+// from the top of the defence to the top of the target (isClearLineOfSightTerrain), and the+// structure walk of Pathfinder::isAttackViewBlockedByObstacle;+// - the fog: the target's cell has to be clear for the defence's player (PartitionFilterFreeOfFog);+// - the weapon: the set's chooser (WeaponSet::chooseBestWeaponForTarget) may pick any slot whose+// AutoChooseSources lets an AI-picked target choose it and that hits ground, and the turret fires+// only once the chosen one is in range (TurretAIAimTurretState), so EVERY such slot has to have+// the point inside Weapon::isWithinAttackRange. A Patriot's ground missile qualifies; its 450+// assist missile (AutoChooseSources NONE, fired only when another Patriot asks) and its anti-air+// missile do not, so the Patriot shows the ground it hits on its own. Air targets are not shown;+// - a pitch band (the Fire Base's howitzer): only the ground within the height Weapon::isWithinTargetPitch+// waves through whatever the band.+//+// The target is the worst one of its kind, test by test: a range is measured to its centre (a wider+// target is reached sooner), a minimum range to the edge of the widest ground unit the game can build,+// and a sight line to the top of the lowest one. A cell under a building or a bridge deck, where no+// ground unit stands, is left out.+//+// The tests are taken on a grid, a quarter of a pathfind cell apart, and a grid point is lit only if+// it and its eight neighbours all pass. The renderer paints where the field, taken bilinearly, is+// above nought, which needs one lit corner, so every painted spot lies in a grid cell whose four+// corners all passed. ReachOverlay_prove measures what is left: points between the grid points.+//-------------------------------------------------------------------------------------------------++static const Real LIVE_STEP = PATHFIND_CELL_SIZE_F * 0.25f; ///< a standing defence's grid+static const Real GHOST_STEP = PATHFIND_CELL_SIZE_F * 0.5f; ///< the placement cursor's, worked out as it moves+static const Real DISTANCE_LIMIT = 16.0f; ///< the field is clamped to this either side+static const UnsignedInt FOG_REFRESH_FRAMES = 15; ///< client frames between two looks at the fog+static const UnsignedInt FORGET_FRAMES = 300; ///< a field not wanted this long is dropped+static const Real BUILD_BUDGET_MS = 4.0f; ///< grids worked out in one frame, past the first++//-------------------------------------------------------------------------------------------------+/** The worst ground target the game can field: the lowest top and the widest body of every unit a+ * player can build that drives or walks. */+//-------------------------------------------------------------------------------------------------+struct GroundProbe+{+ Real lowestTop;+ Real widestRadius;+};++static GroundProbe theProbe = { 0.0f, 0.0f };+static const ThingTemplate *theProbeFrom = NULL;++static const GroundProbe &groundProbe( void )+{+ const ThingTemplate *first = TheThingFactory ? TheThingFactory->firstTemplate() : NULL;+ if( first == theProbeFrom )+ return theProbe;+ theProbeFrom = first;++ theProbe.lowestTop = FLT_MAX;+ theProbe.widestRadius = 0.0f;+ for( const ThingTemplate *tmpl = first; tmpl; tmpl = tmpl->friend_getNextTemplate() )+ {+ if( !tmpl->isKindOf( KINDOF_VEHICLE ) && !tmpl->isKindOf( KINDOF_INFANTRY ) )+ continue;+ // a player's: it costs something. Ships, trains and film props cost nothing+ // and something to see on the ground: an angry mob's nexus is the mob's invisible one-unit-high+ // leader, and the mob itself is what gets shot+ if( tmpl->isKindOf( KINDOF_AIRCRAFT ) || tmpl->isKindOf( KINDOF_PROJECTILE ) || tmpl->isKindOf( KINDOF_MOB_NEXUS )+ || tmpl->getBuildable() != BSTATUS_YES || tmpl->friend_getBuildCost() <= 0 )+ continue;+ // no Geometry of its own (ThingTemplate's default, a sphere of one): it never stands on the field+ // as itself, the way a Technical comes out as one of its chassis+ const GeometryInfo &geom = tmpl->getTemplateGeometryInfo();+ if( geom.getGeomType() == GEOMETRY_SPHERE && geom.getMajorRadius() == 1.0f && geom.getMaxHeightAbovePosition() <= 1.0f )+ continue;+ theProbe.lowestTop = min( theProbe.lowestTop, geom.getMaxHeightAbovePosition() );+ theProbe.widestRadius = max( theProbe.widestRadius, geom.getBoundingCircleRadius() );+ }+ if( theProbe.lowestTop == FLT_MAX )+ theProbe.lowestTop = 0.0f;+ theProbe.lowestTop = max( theProbe.lowestTop, 0.0f );+ DEBUG_LOG(( "REACHOVERLAY: ground targets judged by a top %.2f high and a body %.2f wide\n",+ theProbe.lowestTop, theProbe.widestRadius ));+ return theProbe;+}++//-------------------------------------------------------------------------------------------------+/** A defence as the tests below see it: a standing one through its Object, or one on the+ * placement cursor through its template. */+//-------------------------------------------------------------------------------------------------+struct ReachGun+{+ const Weapon *live; ///< the standing defence's weapon, NULL for the cursor's+ const WeaponTemplate *tmpl;+};++struct ReachShooter+{+ const Object *obj; ///< NULL on the placement cursor+ const ThingTemplate *tmpl;+ Coord3D center;+ Real radius;+ Real eyeZ;+ Real acquireRange; ///< getNextMoodTarget's rangeToFindWithin before the high ground+ Bool lineOfSight;+ Int playerIndex;+ const Player *owner;+ std::vector< ReachGun > guns;+ Real reachBound; ///< nothing further than this from the centre passes+ ObjectID standingIn; ///< the cursor's twin in the proof stands in this building's cells+};++/// a slot the weapon set's chooser can pick for a ground target the defence found itself+static Bool picksGround( UnsignedInt sources, Int antiMask )+{+ if( ( antiMask & WEAPON_ANTI_GROUND ) == 0 )+ return FALSE;+ return ( sources & ( 1 << CMD_FROM_AI ) ) != 0 || ( sources & CMD_DEFAULT_SWITCH_WEAPON ) != 0;+}++/// a weapon that refuses targets outside a pitch band, the Fire Base's howitzer (-15 to 15 degrees)+static Bool pitchLimited( const WeaponTemplate *wt )+{+ return wt->getMinTargetPitch() > -PI || wt->getMaxTargetPitch() < PI;+}++/// Weapon::isWithinTargetPitch lets anything through whose height is within this of the shooter's,+/// whatever the band; past it the answer turns on the target's own shape, so the overlay stops there+static const Real PITCH_FREE_HEIGHT = 10.0f;++static void boundShooter( ReachShooter &s, const WeaponBonus *bonusless )+{+ Real bound = s.acquireRange + Weapon_elevationRangeBonus( s.acquireRange, FLT_MAX );+ for( size_t g = 0; g < s.guns.size(); ++g )+ {+ const Real range = s.guns[ g ].live ? s.guns[ g ].live->getAttackRange( s.obj ) : s.guns[ g ].tmpl->getAttackRange( *bonusless );+ bound = min( bound, range + Weapon_elevationRangeBonus( range, FLT_MAX ) );+ }+ s.reachBound = bound + s.radius;+}++static const char *theRefusal = NULL; ///< why liveShooter last said no, for the proof's log++static Bool refuse( const char *why )+{+ theRefusal = why;+ return FALSE;+}++static Bool liveShooter( const Object *obj, ReachShooter &s )+{+ if( obj == NULL || obj->isEffectivelyDead() || !obj->isKindOf( KINDOF_STRUCTURE ) )+ return refuse( "not a standing structure" );+ if( obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION ) || obj->testStatus( OBJECT_STATUS_SOLD ) )+ return refuse( "under construction or sold" );+ // unpowered, hacked, EMP'd: it fires at nothing, so it shows nothing+ if( obj->isDisabled() || !obj->isAbleToAttack() )+ return refuse( "disabled or unable to attack" );+ // a jammed defence's sight shrinks on a clock the drawing does not follow. A Stinger Site's+ // shots come from soldiers who walk about it, and it has no gun of its own to show; a Fire Base+ // carries the same SPAWNS_ARE_THE_WEAPONS kind and its own howitzer, which is what is shown+ if( obj->getContainedBy() != NULL || obj->isSightJammed() )+ return refuse( "contained or jammed" );++ const AIUpdateInterface *ai = obj->getAI();+ if( ai == NULL || !ai->canAutoAcquire() )+ return refuse( "no idle auto-acquire" );+ if( ai->getMoodMatrixActionAdjustment( MM_Action_Idle ) & MAA_Affect_Range_IgnoreAll )+ return refuse( "mood ignores all" );+ if( obj->testStatus( OBJECT_STATUS_STEALTHED ) && !ai->canAutoAcquireWhileStealthed() )+ return refuse( "stealthed" );++ s.guns.clear();+ if( obj->isCurWeaponLocked() )+ {+ const Weapon *w = obj->getCurrentWeapon();+ if( w && ( w->getAntiMask() & WEAPON_ANTI_GROUND ) )+ {+ ReachGun gun = { w, w->getTemplate() };+ s.guns.push_back( gun );+ }+ }+ else+ {+ for( Int slot = PRIMARY_WEAPON; slot < WEAPONSLOT_COUNT; ++slot )+ {+ const Weapon *w = obj->getWeaponInWeaponSlot( (WeaponSlotType)slot );+ if( w == NULL || !picksGround( obj->getWeaponInWeaponSlotCommandSourceMask( (WeaponSlotType)slot ), w->getAntiMask() ) )+ continue;+ ReachGun gun = { w, w->getTemplate() };+ s.guns.push_back( gun );+ }+ }+ if( s.guns.empty() )+ return refuse( "no gun an idle scan picks for the ground" );+ for( size_t g = 0; g < s.guns.size(); ++g )+ {+ if( s.guns[ g ].live->isContactWeapon() )+ return refuse( "contact weapon" );+ }++ s.obj = obj;+ s.tmpl = obj->getTemplate();+ s.center = *obj->getPosition();+ s.radius = obj->getGeometryInfo().getBoundingCircleRadius();+ s.eyeZ = s.center.z + obj->getGeometryInfo().getMaxHeightAbovePosition();+ s.acquireRange = TheAI->getAdjustedVisionRangeForObject( obj, AI_VISIONFACTOR_OWNERTYPE | AI_VISIONFACTOR_MOOD );+ if( s.tmpl->acquiresBeyondVision() )+ s.acquireRange = max( s.acquireRange, obj->getLargestWeaponRange() );+ s.lineOfSight = TheAI->getAiData()->m_attackUsesLineOfSight && obj->isKindOf( KINDOF_ATTACK_NEEDS_LINE_OF_SIGHT );+ s.owner = obj->getControllingPlayer();+ s.playerIndex = s.owner ? s.owner->getPlayerIndex() : 0;+ s.standingIn = INVALID_ID;+ boundShooter( s, NULL );+ return s.acquireRange > 0.0f;+}++/// the defence on the placement cursor, as it will stand there: its template's default weapon set,+/// no bonus, the sight a human player's turret gets (the cursor is always the local player's)+static Bool ghostShooter( const ThingTemplate *tmpl, Real x, Real y, const Player *owner, ReachShooter &s )+{+ if( tmpl == NULL || owner == NULL || !tmpl->isKindOf( KINDOF_STRUCTURE ) )+ return FALSE;+ const WeaponTemplateSet *set = tmpl->findWeaponTemplateSet( WeaponSetFlags() );+ if( set == NULL )+ return FALSE;++ s.guns.clear();+ Real longest = 0.0f;+ const WeaponBonus bonusless;+ for( Int slot = PRIMARY_WEAPON; slot < WEAPONSLOT_COUNT; ++slot )+ {+ const WeaponTemplate *wt = set->getNth( (WeaponSlotType)slot );+ if( wt == NULL )+ continue;+ longest = max( longest, wt->getAttackRange( bonusless ) );+ if( !picksGround( set->getNthCommandSourceMask( (WeaponSlotType)slot ), wt->getAntiMask() ) )+ continue;+ if( wt->isContactWeapon() )+ return FALSE;+ ReachGun gun = { NULL, wt };+ s.guns.push_back( gun );+ }+ if( s.guns.empty() )+ return FALSE;++ s.obj = NULL;+ s.tmpl = tmpl;+ s.center.x = x;+ s.center.y = y;+ s.center.z = TheTerrainLogic->getGroundHeight( x, y );+ s.radius = tmpl->getTemplateGeometryInfo().getBoundingCircleRadius();+ s.eyeZ = s.center.z + tmpl->getTemplateGeometryInfo().getMaxHeightAbovePosition();+ s.acquireRange = tmpl->friend_calcVisionRange() * TheAI->getAiData()->m_guardOuterModifierHuman;+ if( tmpl->acquiresBeyondVision() )+ s.acquireRange = max( s.acquireRange, longest );+ s.lineOfSight = TheAI->getAiData()->m_attackUsesLineOfSight && tmpl->isKindOf( KINDOF_ATTACK_NEEDS_LINE_OF_SIGHT );+ s.owner = owner;+ s.playerIndex = owner->getPlayerIndex();+ s.standingIn = INVALID_ID;+ boundShooter( s, &bonusless );+ return s.acquireRange > 0.0f;+}++/// where a ground unit at (x, y) stands: on the ground, or on the water over it+static Real standHeight( Real x, Real y )+{+ Real z = TheTerrainLogic->getGroundHeight( x, y );+ Real waterZ = 0.0f;+ if( TheTerrainLogic->isUnderwater( x, y, &waterZ ) )+ z = max( z, waterZ );+ return z;+}++//-------------------------------------------------------------------------------------------------+/** Every test but the fog, for the worst ground target standing at (x, y). */+//-------------------------------------------------------------------------------------------------+static Bool hitsGroundAt( const ReachShooter &s, const GroundProbe &probe, Real x, Real y )+{+ const Real dx = x - s.center.x;+ const Real dy = y - s.center.y;+ if( dx * dx + dy * dy > s.reachBound * s.reachBound )+ return FALSE;++ Coord3D at;+ at.set( x, y, standHeight( x, y ) );++ const PathfindCell *cell = TheAI->pathfinder()->getCell( LAYER_GROUND, &at );+ if( cell == NULL || cell->getType() == PathfindCell::CELL_OBSTACLE )+ return FALSE;+ if( TheTerrainLogic->findBridgeAt( &at ) != NULL )+ return FALSE;++ // FROM_BOUNDINGSPHERE_2D from the defence's edge to the target's middle+ Real distSqr;+ if( s.obj )+ distSqr = ThePartitionManager->getDistanceSquared( s.obj, &at, FROM_BOUNDINGSPHERE_2D );+ else+ {+ const Real d = sqrtf( dx * dx + dy * dy ) - s.radius;+ distSqr = d > 0.0f ? d * d : 0.0f;+ }++ // getNextMoodTarget's search and PartitionFilterElevatedReach+ const Real look = s.obj ? Weapon_elevatedRange( s.obj, s.acquireRange, at.z )+ : s.acquireRange + Weapon_elevationRangeBonus( s.acquireRange, s.center.z - at.z );+ if( distSqr > look * look )+ return FALSE;++ // the widest target's edge is this much nearer than its middle (distCalcProc_BoundaryAndBoundary_2D)+ const Real edge = max( 0.0f, sqrtf( distSqr ) - probe.widestRadius );+ const WeaponBonus bonusless;+ for( size_t g = 0; g < s.guns.size(); ++g )+ {+ const ReachGun &gun = s.guns[ g ];+ if( gun.live )+ {+ if( !gun.live->isWithinAttackRange( s.obj, &at ) )+ return FALSE;+ }+ else+ {+ const Real range = gun.tmpl->getAttackRange( bonusless );+ const Real reach = range + Weapon_elevationRangeBonus( range, s.center.z - at.z );+ const Real minimum = gun.tmpl->getMinimumAttackRange();+ if( distSqr > reach * reach || distSqr < minimum * minimum )+ return FALSE;+ }+ const Real minimum = gun.tmpl->getMinimumAttackRange();+ if( minimum > 0.0f && edge * edge < minimum * minimum )+ return FALSE;+ if( pitchLimited( gun.tmpl ) && fabs( at.z - s.center.z ) >= PITCH_FREE_HEIGHT )+ return FALSE;+ }++ if( s.lineOfSight )+ {+ Coord3D top = at;+ top.z += probe.lowestTop;+ if( s.obj )+ {+ if( !ThePartitionManager->isClearLineOfSightTerrain( s.obj, *s.obj->getPosition(), NULL, top ) )+ return FALSE;+ if( TheAI->pathfinder()->isAttackViewBlockedByObstacle( s.obj, *s.obj->getPosition(), NULL, at ) )+ return FALSE;+ }+ else+ {+ Coord3D eye = s.center;+ eye.z = s.eyeZ;+ if( !ThePartitionManager->isClearLineOfSightTerrain( NULL, eye, NULL, top ) )+ return FALSE;+ if( TheAI->pathfinder()->isGroundViewBlockedByObstacle( s.center, at, s.standingIn ) )+ return FALSE;+ }+ }+ return TRUE;+}++//-------------------------------------------------------------------------------------------------+// One defence's field and the grid behind it.+//-------------------------------------------------------------------------------------------------+struct ReachEntry+{+ ReachOverlayField field;+ std::vector< UnsignedByte > geometry; ///< every test but the fog passed at this grid point+ UnsignedInt signature;+ UnsignedInt fogFrame;+ UnsignedInt lastWanted;+ Int playerIndex;+ Bool built;+ Bool regridded; ///< the grid moved or changed size since the last field, so the version must change+};++static UnsignedInt theVersion = 0;++static void layGrid( ReachOverlayField &field, const ReachShooter &s, Real step )+{+ field.step = step;+ field.originX = floorf( ( s.center.x - s.reachBound ) / step ) * step - step;+ field.originY = floorf( ( s.center.y - s.reachBound ) / step ) * step - step;+ field.width = (Int)ceilf( ( s.center.x + s.reachBound - field.originX ) / step ) + 2;+ field.height = (Int)ceilf( ( s.center.y + s.reachBound - field.originY ) / step ) + 2;+ field.distanceLimit = DISTANCE_LIMIT;+ field.color = clientPlayerColor( s.owner );+ field.opacity = 1.0f;+}++static void traceGeometry( ReachEntry &entry, const ReachShooter &s, Real step )+{+ layGrid( entry.field, s, step );+ const GroundProbe &probe = groundProbe();+ const Int w = entry.field.width;+ const Int h = entry.field.height;+ entry.geometry.assign( w * h, 0 );+ for( Int j = 0; j < h; ++j )+ {+ const Real y = entry.field.originY + j * step;+ for( Int i = 0; i < w; ++i )+ entry.geometry[ j * w + i ] = hitsGroundAt( s, probe, entry.field.originX + i * step, y ) ? 1 : 0;+ }++ // the bound allows for all the high ground a range can gain; cut the grid down to what passed,+ // two points of nothing round it, so the fog pass, the field and the texture stay small+ Int loI = w, hiI = -1, loJ = h, hiJ = -1;+ for( Int j = 0; j < h; ++j )+ {+ for( Int i = 0; i < w; ++i )+ {+ if( !entry.geometry[ j * w + i ] )+ continue;+ loI = min( loI, i );+ hiI = max( hiI, i );+ loJ = min( loJ, j );+ hiJ = max( hiJ, j );+ }+ }+ if( hiI < 0 )+ {+ loI = loJ = 0;+ hiI = hiJ = 1;+ }+ loI = max( loI - 2, 0 );+ loJ = max( loJ - 2, 0 );+ hiI = min( hiI + 2, w - 1 );+ hiJ = min( hiJ + 2, h - 1 );+ const Int cw = hiI - loI + 1;+ const Int ch = hiJ - loJ + 1;+ std::vector< UnsignedByte > cropped( cw * ch );+ for( Int j = 0; j < ch; ++j )+ memcpy( &cropped[ j * cw ], &entry.geometry[ ( j + loJ ) * w + loI ], cw );+ entry.geometry.swap( cropped );+ entry.field.originX += loI * step;+ entry.field.originY += loJ * step;+ entry.field.width = cw;+ entry.field.height = ch;++ entry.playerIndex = s.playerIndex;+ entry.built = TRUE;+ entry.regridded = TRUE;+ entry.fogFrame = 0;+}++//-------------------------------------------------------------------------------------------------+/** The fog on top of the geometry, then the erosion, then the signed distance (a chamfer walk, a+ * grid step straight and step root two across; only the sign is load-bearing, the size only shapes+ * the border the renderer draws). */+//-------------------------------------------------------------------------------------------------+static void shadeField( ReachEntry &entry )+{+ ReachOverlayField &field = entry.field;+ const Int w = field.width;+ const Int h = field.height;+ const Real step = field.step;++ std::vector< UnsignedByte > seen( w * h, 0 );+ for( Int j = 0; j < h; ++j )+ {+ for( Int i = 0; i < w; ++i )+ {+ const Int k = j * w + i;+ if( !entry.geometry[ k ] )+ continue;+ Coord3D at;+ at.set( field.originX + i * step, field.originY + j * step, 0.0f );+ seen[ k ] = ThePartitionManager->getShroudStatusForPlayer( entry.playerIndex, &at ) == CELLSHROUD_CLEAR ? 1 : 0;+ }+ }++ // lit: it and its eight neighbours passed+ std::vector< UnsignedByte > lit( w * h, 0 );+ for( Int j = 1; j < h - 1; ++j )+ {+ for( Int i = 1; i < w - 1; ++i )+ {+ Bool all = TRUE;+ for( Int dj = -1; dj <= 1 && all; ++dj )+ for( Int di = -1; di <= 1 && all; ++di )+ all = seen[ ( j + dj ) * w + i + di ] != 0;+ lit[ j * w + i ] = all ? 1 : 0;+ }+ }++ const Real across = step * 1.41421356f;+ const Real outOfReach = DISTANCE_LIMIT + step;+ std::vector< Real > d( w * h, outOfReach );+ for( Int j = 0; j < h; ++j )+ {+ for( Int i = 0; i < w; ++i )+ {+ const UnsignedByte mine = lit[ j * w + i ];+ for( Int dj = -1; dj <= 1; ++dj )+ {+ for( Int di = -1; di <= 1; ++di )+ {+ const Int ni = i + di;+ const Int nj = j + dj;+ if( ( di == 0 && dj == 0 ) || ni < 0 || nj < 0 || ni >= w || nj >= h || lit[ nj * w + ni ] == mine )+ continue;+ d[ j * w + i ] = min( d[ j * w + i ], ( di != 0 && dj != 0 ) ? across : step );+ }+ }+ }+ }+ for( Int j = 0; j < h; ++j )+ {+ for( Int i = 0; i < w; ++i )+ {+ Real &here = d[ j * w + i ];+ if( i > 0 ) here = min( here, d[ j * w + i - 1 ] + step );+ if( j > 0 ) here = min( here, d[ ( j - 1 ) * w + i ] + step );+ if( i > 0 && j > 0 ) here = min( here, d[ ( j - 1 ) * w + i - 1 ] + across );+ if( i < w - 1 && j > 0 ) here = min( here, d[ ( j - 1 ) * w + i + 1 ] + across );+ }+ }+ for( Int j = h - 1; j >= 0; --j )+ {+ for( Int i = w - 1; i >= 0; --i )+ {+ Real &here = d[ j * w + i ];+ if( i < w - 1 ) here = min( here, d[ j * w + i + 1 ] + step );+ if( j < h - 1 ) here = min( here, d[ ( j + 1 ) * w + i ] + step );+ if( i < w - 1 && j < h - 1 ) here = min( here, d[ ( j + 1 ) * w + i + 1 ] + across );+ if( i > 0 && j < h - 1 ) here = min( here, d[ ( j + 1 ) * w + i - 1 ] + across );+ }+ }++ // a fog refresh that changed nothing keeps the version, so the renderer keeps its texture+ Bool changed = (Int)field.distance.size() != w * h;+ field.distance.resize( w * h );+ for( Int k = 0; k < w * h; ++k )+ {+ const Real magnitude = min( d[ k ] - 0.5f * step, DISTANCE_LIMIT );+ const Real value = lit[ k ] ? magnitude : -magnitude;+ changed = changed || field.distance[ k ] != value;+ field.distance[ k ] = value;+ }+ if( changed || entry.regridded )+ field.version = ++theVersion;+ entry.regridded = FALSE;+}++/// the field taken bilinearly, as the renderer takes it; outside the grid it is the limit below nought+static Real fieldAt( const ReachOverlayField &field, Real x, Real y )+{+ const Real fx = ( x - field.originX ) / field.step;+ const Real fy = ( y - field.originY ) / field.step;+ const Int i = (Int)floorf( fx );+ const Int j = (Int)floorf( fy );+ if( i < 0 || j < 0 || i + 1 >= field.width || j + 1 >= field.height )+ return -field.distanceLimit;+ const Real tx = fx - i;+ const Real ty = fy - j;+ const Real *row = &field.distance[ j * field.width + i ];+ const Real top = row[ 0 ] * ( 1.0f - tx ) + row[ 1 ] * tx;+ const Real bottom = row[ field.width ] * ( 1.0f - tx ) + row[ field.width + 1 ] * tx;+ return top * ( 1.0f - ty ) + bottom * ty;+}++//-------------------------------------------------------------------------------------------------+// What is on the map this frame, and which fields are wanted.+//-------------------------------------------------------------------------------------------------+struct StructureMark+{+ ObjectID id;+ Real x;+ Real y;+};++static std::vector< StructureMark > theStructures;+static std::map< ObjectID, ReachEntry > theEntries;+static ReachEntry theGhost;+static const ThingTemplate *theGhostTemplate = NULL;+static Coord3D theGhostAt;+static Bool theGhostShown = FALSE;+static std::vector< const ReachOverlayField * > theShown;++static UnsignedInt mix( UnsignedInt hash, UnsignedInt value )+{+ return ( hash ^ value ) * 16777619u;+}++static UnsignedInt mixReal( UnsignedInt hash, Real value )+{+ UnsignedInt bits;+ memcpy( &bits, &value, sizeof( bits ) );+ return mix( hash, bits );+}++/// what the grid depends on: the defence and its guns, and every structure standing near it+static UnsignedInt shooterSignature( const ReachShooter &s )+{+ UnsignedInt hash = 2166136261u;+ hash = mixReal( hash, s.center.x );+ hash = mixReal( hash, s.center.y );+ hash = mixReal( hash, s.center.z );+ hash = mixReal( hash, s.eyeZ );+ hash = mixReal( hash, s.acquireRange );+ hash = mix( hash, s.lineOfSight ? 1 : 0 );+ hash = mix( hash, (UnsignedInt)s.playerIndex );+ for( size_t g = 0; g < s.guns.size(); ++g )+ {+ hash = mix( hash, (UnsignedInt)(uintptr_t)s.guns[ g ].tmpl );+ if( s.guns[ g ].live )+ hash = mixReal( hash, s.guns[ g ].live->getAttackRange( s.obj ) );+ }+ const Real nearSqr = sqr( s.reachBound + PATHFIND_CELL_SIZE_F * 10.0f );+ for( size_t k = 0; k < theStructures.size(); ++k )+ {+ const StructureMark &mark = theStructures[ k ];+ if( sqr( mark.x - s.center.x ) + sqr( mark.y - s.center.y ) > nearSqr )+ continue;+ hash = mix( hash, mark.id );+ hash = mixReal( hash, mark.x );+ hash = mixReal( hash, mark.y );+ }+ return hash;+}++/// a defence whose reach the local player is shown: their own, an ally's, or any to an observer+static Bool revealedToLocal( const Object *obj )+{+ const Player *local = ThePlayerList->getLocalPlayer();+ if( local == NULL || obj == NULL )+ return FALSE;+ if( obj->getControllingPlayer() == local )+ return TRUE;+ if( !local->isPlayerObserver() && local->getRelationship( obj->getTeam() ) != ALLIES )+ return FALSE;+ return obj->getShroudedStatus( local->getPlayerIndex() ) < OBJECTSHROUD_FOGGED;+}++static void clearAll( void )+{+ theEntries.clear();+ theShown.clear();+ theGhostShown = FALSE;+ theGhostTemplate = NULL;+ theGhost.built = FALSE;+}++static Real millisecondsSince( const std::chrono::steady_clock::time_point &start )+{+ return std::chrono::duration< Real, std::milli >( std::chrono::steady_clock::now() - start ).count();+}++void ReachOverlay_update( void )+{+ if( TheGlobalData == NULL || TheGlobalData->m_headless || TheGameLogic == NULL || TheInGameUI == NULL+ || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() || ThePlayerList == NULL+ || ThePlayerList->getLocalPlayer() == NULL || TheAI == NULL || TheAI->pathfinder() == NULL )+ {+ clearAll();+ return;+ }++ // the tick may be running beside this frame: keep what was worked out at the last sync point+ if( LogicThread::isInsideWindow() )+ return;++ const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();+ const UnsignedInt now = TheGameClient ? TheGameClient->getFrame() : 0;++ theStructures.clear();+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )+ {+ if( !obj->isKindOf( KINDOF_STRUCTURE ) || obj->isEffectivelyDead() )+ continue;+ StructureMark mark = { obj->getID(), obj->getPosition()->x, obj->getPosition()->y };+ theStructures.push_back( mark );+ }++ // which defences are wanted: the selected ones, and while a building is on the cursor every one+ // the local player is shown+ std::vector< const Object * > wanted;+ const ThingTemplate *pending = TheInGameUI->getPendingPlaceType();+ if( pending != NULL )+ {+ for( size_t k = 0; k < theStructures.size(); ++k )+ {+ const Object *obj = TheGameLogic->findObjectByID( theStructures[ k ].id );+ if( revealedToLocal( obj ) )+ wanted.push_back( obj );+ }+ }+ else+ {+ const DrawableList *selected = TheInGameUI->getAllSelectedDrawables();+ for( DrawableListCIt it = selected->begin(); it != selected->end(); ++it )+ {+ const Object *obj = (*it)->getObject();+ if( revealedToLocal( obj ) )+ wanted.push_back( obj );+ }+ }++ theShown.clear();+ Bool builtOne = FALSE;++ // the cursor's first: it is what the player is looking at+ theGhostShown = FALSE;+ const Drawable *icon = TheInGameUI->getPendingPlaceDrawable();+ ReachShooter ghost;+ if( pending != NULL && icon != NULL+ && ghostShooter( pending, icon->getPosition()->x, icon->getPosition()->y, ThePlayerList->getLocalPlayer(), ghost ) )+ {+ const Bool moved = pending != theGhostTemplate || !theGhost.built+ || sqr( ghost.center.x - theGhostAt.x ) + sqr( ghost.center.y - theGhostAt.y ) > sqr( 0.5f * GHOST_STEP );+ if( moved )+ {+ theGhostTemplate = pending;+ theGhostAt = ghost.center;+ traceGeometry( theGhost, ghost, GHOST_STEP );+ builtOne = TRUE;+ }+ if( moved || now - theGhost.fogFrame >= FOG_REFRESH_FRAMES )+ {+ shadeField( theGhost );+ theGhost.fogFrame = now;+ }+ theGhost.field.opacity = 1.0f;+ theShown.push_back( &theGhost.field );+ theGhostShown = TRUE;+ }++ for( size_t k = 0; k < wanted.size(); ++k )+ {+ ReachShooter s;+ if( !liveShooter( wanted[ k ], s ) )+ continue;++ ReachEntry &entry = theEntries[ s.obj->getID() ];+ entry.lastWanted = now;+ const UnsignedInt signature = shooterSignature( s );+ if( !entry.built || entry.signature != signature )+ {+ // a grid that no longer matches what stands round it is not drawn until it is worked out again+ if( builtOne && millisecondsSince( start ) > BUILD_BUDGET_MS )+ {+ entry.built = FALSE;+ continue;+ }+ traceGeometry( entry, s, LIVE_STEP );+ entry.signature = signature;+ shadeField( entry );+ entry.fogFrame = now;+ builtOne = TRUE;+ }+ else if( now - entry.fogFrame >= FOG_REFRESH_FRAMES )+ {+ shadeField( entry );+ entry.fogFrame = now;+ }+ entry.field.color = clientPlayerColor( s.owner );+ theShown.push_back( &entry.field );+ }++ for( std::map< ObjectID, ReachEntry >::iterator it = theEntries.begin(); it != theEntries.end(); )+ {+ if( now - it->second.lastWanted > FORGET_FRAMES )+ theEntries.erase( it++ );+ else+ ++it;+ }+}++void ReachOverlay_getFields( std::vector< const ReachOverlayField * > &out )+{+ out = theShown;+}++//-------------------------------------------------------------------------------------------------+/** The check that the picture does not lie. For a standing defence and a probe of the enemy's, a+ * real Object: the field the defence would show, and the one its template would show on the cursor+ * at the same spot, are sampled at random points, inside, outside and near the edge; the probe is+ * put on each point and the logic is asked itself, the way an idle defence asks it: getNextMoodTarget+ * as the turret's idle scan calls it, the fog filter it applies for this owner, then the weapon the+ * chooser takes and the range and attack tests the turret's aim state makes before it fires. A lit+ * point the logic refuses is a lie; an unlit one it accepts is ground the picture leaves out.+ *+ * Diagnostic: it moves the probe, runs the partition and sets the defence's current weapon, so only+ * a scenario calls it. The sample points come from a generator of their own, not the logic's. */+//-------------------------------------------------------------------------------------------------+static Bool logicHits( Object *defence, Object *probe )+{+ AIUpdateInterface *ai = defence->getAI();+ if( ai == NULL || ai->getNextMoodTarget( FALSE, TRUE, FALSE, TRUE ) != probe )+ return FALSE;++ const Player *owner = defence->getControllingPlayer();+ if( owner && ( owner->getPlayerType() == PLAYER_HUMAN || owner->isForkMapComputer() || defence->getTemplate()->acquiresBeyondVision() ) )+ {+ const ObjectShroudStatus status = probe->getShroudedStatus( owner->getPlayerIndex() );+ if( status != OBJECTSHROUD_CLEAR && status != OBJECTSHROUD_PARTIAL_CLEAR )+ return FALSE;+ }++ defence->chooseBestWeaponForTarget( probe, PREFER_MOST_DAMAGE, CMD_FROM_AI );+ const Weapon *weapon = defence->getCurrentWeapon();+ if( weapon == NULL || !weapon->isWithinAttackRange( defence, probe ) )+ return FALSE;+ const CanAttackResult result = defence->getAbleToAttackSpecificObject( ATTACK_CONTINUED_TARGET, probe, CMD_FROM_AI );+ return result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING;+}++struct ProofCount+{+ Int drawn;+ Int drawnMissed; ///< lies+ Int undrawn;+ Int undrawnHit; ///< ground left out+};++static void tally( ProofCount &count, Bool drawn, Bool hit )+{+ if( drawn )+ {+ ++count.drawn;+ if( !hit )+ ++count.drawnMissed;+ }+ else+ {+ ++count.undrawn;+ if( hit )+ ++count.undrawnHit;+ }+}++Bool ReachOverlay_prove( Object *defence, Object *probe, Int samples )+{+ ReachShooter live;+ if( defence == NULL || probe == NULL || !liveShooter( defence, live ) )+ {+ DEBUG_LOG(( "HEADLESS REACHPROOF: no field for %s: %s\n", defence ? defence->getTemplate()->getName().str() : "(none)",+ theRefusal ? theRefusal : "no probe" ));+ return FALSE;+ }+ ReachShooter ghost;+ const Bool hasGhost = ghostShooter( defence->getTemplate(), live.center.x, live.center.y, live.owner, ghost );+ ghost.standingIn = defence->getID();++ const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();+ ReachEntry liveEntry;+ traceGeometry( liveEntry, live, LIVE_STEP );+ shadeField( liveEntry );+ const Real liveMS = millisecondsSince( start );+ ReachEntry ghostEntry;+ if( hasGhost )+ {+ traceGeometry( ghostEntry, ghost, GHOST_STEP );+ ghostEntry.playerIndex = live.playerIndex;+ shadeField( ghostEntry );+ }++ Int litPoints = 0;+ for( size_t k = 0; k < liveEntry.field.distance.size(); ++k )+ litPoints += liveEntry.field.distance[ k ] > 0.0f ? 1 : 0;++ const Coord3D home = *probe->getPosition();+ // mt19937's raw output is the same on every platform; its distributions are not+ std::mt19937 pick( (UnsignedInt)defence->getID() * 2654435761u + (UnsignedInt)samples );+ const Real span = live.reachBound + 10.0f;+ auto across = [ &pick, span ]( void ) { return ( (Real)( pick() >> 8 ) * ( 1.0f / 16777216.0f ) * 2.0f - 1.0f ) * span; };++ enum { ANYWHERE, INSIDE, EDGE, KINDS };+ static const char *const kindNames[ KINDS ] = { "anywhere", "inside", "edge" };+ ProofCount liveCount[ KINDS ];+ ProofCount ghostCount[ KINDS ];+ memset( liveCount, 0, sizeof( liveCount ) );+ memset( ghostCount, 0, sizeof( ghostCount ) );+ Int unstandable = 0;+ Real lowest = FLT_MAX;+ Real highest = -FLT_MAX;++ for( Int kind = 0; kind < KINDS; ++kind )+ {+ Int taken = 0;+ for( Int tries = 0; taken < samples && tries < samples * 200; ++tries )+ {+ const Real x = live.center.x + across();+ const Real y = live.center.y + across();+ const Real d = fieldAt( liveEntry.field, x, y );+ if( kind == INSIDE && d <= 0.0f )+ continue;+ if( kind == EDGE && fabs( d ) > 6.0f )+ continue;++ Coord3D at;+ at.set( x, y, standHeight( x, y ) );+ const PathfindCell *cell = TheAI->pathfinder()->getCell( LAYER_GROUND, &at );+ if( cell == NULL || cell->getType() == PathfindCell::CELL_OBSTACLE || TheTerrainLogic->findBridgeAt( &at ) != NULL )+ {+ ++unstandable;+ continue;+ }+ ++taken;+ lowest = min( lowest, at.z );+ highest = max( highest, at.z );++ probe->setPosition( &at );+ ThePartitionManager->update();+ const Bool hit = logicHits( defence, probe );+ tally( liveCount[ kind ], d > 0.0f, hit );+ if( hasGhost )+ tally( ghostCount[ kind ], fieldAt( ghostEntry.field, x, y ) > 0.0f, hit );+ }+ }++ probe->setPosition( &home );+ ThePartitionManager->update();++ const GroundProbe &worst = groundProbe();+ DEBUG_LOG(( "HEADLESS REACHPROOF: %s at (%.0f,%.0f,%.1f) against %s: reach bound %.1f, %d lit grid points, grid in %.1f ms, worst target top %.2f body %.2f, ground sampled from %.1f to %.1f high, %d unstandable points skipped\n",+ defence->getTemplate()->getName().str(), live.center.x, live.center.y, live.center.z,+ probe->getTemplate()->getName().str(), live.reachBound, litPoints, liveMS, worst.lowestTop, worst.widestRadius,+ lowest, highest, unstandable ));+ Int lies = 0;+ for( Int kind = 0; kind < KINDS; ++kind )+ {+ DEBUG_LOG(( "HEADLESS REACHPROOF: %-8s live drawn %d, %d not hit; undrawn %d, %d hit\n", kindNames[ kind ],+ liveCount[ kind ].drawn, liveCount[ kind ].drawnMissed, liveCount[ kind ].undrawn, liveCount[ kind ].undrawnHit ));+ if( hasGhost )+ DEBUG_LOG(( "HEADLESS REACHPROOF: %-8s ghost drawn %d, %d not hit; undrawn %d, %d hit\n", kindNames[ kind ],+ ghostCount[ kind ].drawn, ghostCount[ kind ].drawnMissed, ghostCount[ kind ].undrawn, ghostCount[ kind ].undrawnHit ));+ lies += liveCount[ kind ].drawnMissed + ghostCount[ kind ].drawnMissed;+ }+ DEBUG_LOG(( "HEADLESS REACHPROOF: %s %s, %d lies\n", defence->getTemplate()->getName().str(), lies == 0 ? "PASS" : "FAIL", lies ));+ return lies == 0;+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cppindex 79244bf55..d62e69a4c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/AI/AIPathfind.cpp@@ -11430,6 +11430,7 @@ struct ViewAttackBlockedStructconst Object *victim;const PathfindCell *victimCell;Int skipCount;+ ObjectID standingIn; ///< with no obj: a building whose cells the shooter would stand in, not in its way};/*static*/ Int Pathfinder::attackBlockedByObstacleCallback(Pathfinder* pathfinder, PathfindCell* from, PathfindCell* to, Int to_x, Int to_y, void* userData)@@ -11442,8 +11443,11 @@ struct ViewAttackBlockedStruct}if (to != NULL && (to->getType() == PathfindCell::CELL_OBSTACLE)){- // we never block our own view!- if (to->isObstaclePresent(d->obj->getID()))+ // we never block our own view! No obj is a shooter not standing yet (isGroundViewBlockedByObstacle),+ // which has no cells, container or slaver of its own.+ if (d->obj && to->isObstaclePresent(d->obj->getID()))+ return 0;+ if (!d->obj && d->standingIn != INVALID_ID && to->isObstaclePresent(d->standingIn))return 0;if (d->victim) {@@ -11462,7 +11466,7 @@ struct ViewAttackBlockedStruct// @todo: if the obstacle is objOther's container, AND it's a "visible" container, ignore it.// if the obstacle is the item to which we are slaved, ignore it as an obstacle.- if (to->isObstaclePresent(getSlaverID(d->obj)))+ if (d->obj && to->isObstaclePresent(getSlaverID(d->obj)))return 0;if (to->isObstacleTransparent())@@ -11581,9 +11585,10 @@ Bool Pathfinder::isAttackViewBlockedByObstacle(const Object* attacker, const Coolayer = victim->getLayer();}info.victimCell = getCell(layer, &victimPos);-+ info.standingIn = INVALID_ID;+info.skipCount = 0;- if (attacker->getLayer() != LAYER_GROUND)+ if (attacker->getLayer() != LAYER_GROUND){info.skipCount = 3; /// srj -- someone wanna tell me what this magic number means?/// jba - Yes, it means that if someone is on a bridge, or rooftop, they can see@@ -11599,6 +11604,23 @@ Bool Pathfinder::isAttackViewBlockedByObstacle(const Object* attacker, const Cooreturn ret != 0;}+//-----------------------------------------------------------------------------+/** The structure walk of isAttackViewBlockedByObstacle for a ground shooter that does not stand yet+ * (a defence on the placement cursor) and a ground target with no Object: the same cells, the same+ * callback. standingIn is a building the shooter would stand in, whose cells are no more in its way+ * than a standing defence's own are (the reach proof puts the cursor's twin on a built defence).+ * Only the client's reach overlay asks; nothing in the simulation does. */+Bool Pathfinder::isGroundViewBlockedByObstacle(const Coord3D& attackerPos, const Coord3D& victimPos, ObjectID standingIn)+{+ ViewAttackBlockedStruct info;+ info.obj = NULL;+ info.victim = NULL;+ info.victimCell = getCell(LAYER_GROUND, &victimPos);+ info.skipCount = 0;+ info.standingIn = standingIn;+ return iterateCellsAlongLine(attackerPos, victimPos, LAYER_GROUND, attackBlockedByObstacleCallback, &info) != 0;+}+static void computeNormalRadialOffset(const Coord3D& from, Coord3D& insert, const Coord3D& to,Object *obj, Real radius){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cppindex bb2b47c82..3c99a69c5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp@@ -55,6 +55,7 @@#include "GameLogic/PartitionManager.h"#include "GameLogic/Module/BodyModule.h"#include "GameLogic/Weapon.h"+#include "GameClient/ReachOverlay.h"#include <algorithm>#include <map>@@ -253,6 +254,8 @@ static Bool parseActionType( const AsciiString &token, ScenarioActionType *actio*action = SCENARIO_ACTION_GIVEMONEY;else if (token == "rank")*action = SCENARIO_ACTION_RANK;+ else if (token == "reachproof")+ *action = SCENARIO_ACTION_REACHPROOF;elsereturn FALSE;@@ -354,6 +357,7 @@ static Int tokensNeededFor( ScenarioActionType action )case SCENARIO_ACTION_REPEAT: return SCENARIO_TOKENS_ATTACK;case SCENARIO_ACTION_GIVEMONEY: return SCENARIO_TOKENS_STANCE;case SCENARIO_ACTION_RANK: return SCENARIO_TOKENS_STANCE;+ case SCENARIO_ACTION_REACHPROOF: return SCENARIO_TOKENS_ATTACK;case SCENARIO_ACTION_STOP: return SCENARIO_TOKENS_STOP;case SCENARIO_ACTION_CLICKSTOP: return SCENARIO_TOKENS_STOP;case SCENARIO_ACTION_TALLY: return SCENARIO_TOKENS_STOP;@@ -473,6 +477,17 @@ ScenarioParseResult ScenarioDrill_parseLine( const char *line, ScenarioAction *abreak;}+ case SCENARIO_ACTION_REACHPROOF:+ {+ if (!parseWholeNumber( tokens[ 4 ], &action->targetSlot ))+ return SCENARIO_PARSE_BAD_SLOT;+ action->targetSelector = tokens[ 5 ];+ action->count = 400; // sample points of each kind+ if (count > 6 && (!parseWholeNumber( tokens[ 6 ], &action->count ) || action->count < 1))+ return SCENARIO_PARSE_BAD_COUNT;+ break;+ }+case SCENARIO_ACTION_SHIFTUPGRADE:action->name = tokens[ SCENARIO_SHIFTUPGRADE_NAME_TOKEN ];break;@@ -1921,6 +1936,7 @@ static Bool executeOrder( const ScenarioAction &action, Player *player, const Cocase SCENARIO_ACTION_GIVEMONEY:case SCENARIO_ACTION_TALLY:case SCENARIO_ACTION_RESPOND:+ case SCENARIO_ACTION_REACHPROOF:ordered = FALSE; // handled before the group is builtbreak;}@@ -1929,6 +1945,43 @@ static Bool executeOrder( const ScenarioAction &action, Player *player, const Coreturn ordered;}+/** Every matching defence of the seat put through ReachOverlay_prove against the first matching unit+ of the target seat, which is moved about for it and put back. */+static Bool executeReachProof( const ScenarioAction &action, Player *player )+{+ Player *targetPlayer = findPlayerForSlot( action.targetSlot );+ Object *probe = NULL;+ for( Object *obj = TheGameLogic->getFirstObject(); obj && targetPlayer; obj = obj->getNextObject() )+ {+ if (obj->getControllingPlayer() == targetPlayer && !obj->isEffectivelyDead() && obj->getContainedBy() == NULL+ && selectorMatches( action.targetSelector, obj ))+ {+ probe = obj;+ break;+ }+ }+ if (probe == NULL)+ {+ DEBUG_LOG(("SCENARIO: frame %d reachproof slot %d: no '%s' of slot %d to stand in\n",+ action.frame, action.slot, action.targetSelector.str(), action.targetSlot));+ return FALSE;+ }++ Int proven = 0;+ Int passed = 0;+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )+ {+ if (obj->getControllingPlayer() != player || obj->isEffectivelyDead() || !selectorMatches( action.selector, obj ))+ continue;+ ++proven;+ if (ReachOverlay_prove( obj, probe, action.count ))+ ++passed;+ }+ DEBUG_LOG(("SCENARIO: frame %d reachproof slot %d '%s' against '%s': %d of %d passed\n",+ action.frame, action.slot, action.selector.str(), probe->getTemplate()->getName().str(), passed, proven));+ return proven > 0 && passed == proven;+}+/** A placement click, as PlaceEventTranslator sends it: one MSG_DOZER_CONSTRUCT onto the messagestream, so it is recorded in the replay and reaches every machine of a network game, and thelogic picks the builder from whatever is selected then - with nothing selected, the player's idle@@ -2038,6 +2091,9 @@ Bool ScenarioDrill_execute( const ScenarioAction &action )if (action.action == SCENARIO_ACTION_TALLY)return executeTally( action, player );+ if (action.action == SCENARIO_ACTION_REACHPROOF)+ return executeReachProof( action, player );+if (action.action == SCENARIO_ACTION_PURCHASE)return executePurchase( action, player );diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DReachOverlay.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DReachOverlay.hnew file mode 100644index 000000000..c45ff9a4a--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DReachOverlay.h@@ -0,0 +1,41 @@+// The ground a defence can hit (GameClient/ReachOverlay.h), drawn on the terrain.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#ifndef __W3DREACHOVERLAY_H__+#define __W3DREACHOVERLAY_H__++#include "Lib/BaseType.h"+#include <vector>++class CameraClass;+struct ReachOverlayField;++/** The look, in world units and alphas, read by both renderers. The Direct3D 11 program takes them+ * through its constants, so tuning one needs no new program in the shader cache. */+namespace ReachLook+{+ const Real BorderWidth = 1.5f; ///< the line on the inside of the edge+ const Real BandWidth = 10.0f; ///< the stronger wash just inside the edge fades out over this+ const Real FillAlpha = 0.10f; ///< the whole area+ const Real BandAlpha = 0.14f; ///< added at the edge, nought BandWidth in+ const Real LineAlpha = 0.70f;+ const Real LineWhite = 0.35f; ///< how far the line goes from the owner's colour toward white (Direct3D 11)+}++/** This frame's fields on the ground. Called from the terrain pass once the ground, the roads, the+ * bridges and the tracks are down and before the shroud and any model: the shroud darkens it with+ * the ground, every unit and building stands on it, and the interface is drawn long after. */+void W3DReachOverlay_Draw( CameraClass &camera );++/** Lets go of every texture and Direct3D 11 object the overlay holds, for the terrain going away or a+ * device reset; the next draw makes them again. */+void W3DReachOverlay_Release( void );++/** The Direct3D 11 pass (DX11ReachOverlay.cpp, Windows only). False when it cannot draw at all, and+ * the fixed-function path draws instead. Makes its program on the first terrain frame, fields or+ * not, so the first defence selected does not pay for the compile. */+Bool DX11ReachOverlay_Draw( CameraClass &camera, const std::vector< const ReachOverlayField * > &fields );+void DX11ReachOverlay_Release( void );++#endifdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11ReachOverlay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11ReachOverlay.cppnew file mode 100644index 000000000..6f6f7abf7--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11ReachOverlay.cpp@@ -0,0 +1,508 @@+// The ground a defence can hit, drawn on Direct3D 11 as a decal read back out of the scene's depth.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+//+// The pass runs from the terrain pass, when the depth holds the ground, its roads, bridges and+// tracks and nothing standing on them. Each pixel goes back to the world through its own depth, so+// the overlay lies exactly on whatever the ground drew there: no geometry of its own, nothing to+// fight the ground's depth, no slope it can float off. The fields are sampled bilinearly by hand+// and the edges smoothed by the pixel's own footprint (fwidth), so no zoom shows their grid.+//+// The fields of one owner are drawn in one pass as one area, the union of their distances (the+// largest), so overlaps neither darken nor draw a line through each other.+#include "W3DDevice/GameClient/W3DReachOverlay.h"++#include "Common/Debug.h"+#include "Common/MapObject.h"+#include "GameClient/ReachOverlay.h"+#include "Platform/HazardCloudCore.h"+#include "WW3D2/camera.h"+#include "WW3D2/ww3d.h"++#include "dx11backend.h"+#include "dx11device.h"+#include "dx11runtime.h"++#include <d3d11.h>+#include <algorithm>+#include <cmath>+#include <cstring>+#include <string>+#include <vector>++namespace+{++// a pass's worth of fields of one owner; past it a second pass draws over the first. The program's+// arrays below hold the same number.+enum { FieldsPerPass = 32 };++template < class T > void drop( T *&object )+{+ if( object )+ {+ object->Release();+ object = nullptr;+ }+}++// Laid out as the program's constant buffer.+struct Constants+{+ float WorldFromClip[ 16 ];+ float Viewport[ 4 ]; // pixel origin (half a pixel in, as the backend's viewport sits), size+ float Colour[ 4 ]; // the owner's colour; w unused+ float Look0[ 4 ]; // border width, band width, fill alpha, band alpha+ float Look1[ 4 ]; // line alpha, line toward white, field count+ float Grid[ FieldsPerPass ][ 4 ]; // origin, 1 / step, -distanceLimit+ float Size[ FieldsPerPass ][ 4 ]; // width - 1, height - 1, opacity+};++const char *const PixelSource = R"HLSL(+cbuffer Reach : register(b0)+{+ row_major float4x4 WorldFromClip;+ float4 Viewport;+ float4 Colour;+ float4 Look0;+ float4 Look1;+ float4 Grid[32];+ float4 Size[32];+};+Texture2D<float> SceneDepth : register(t0);+Texture2D<float> Fields[32] : register(t1);++float4 main(float4 position : SV_Position) : SV_Target+{+ float depth = SceneDepth.Load(int3(position.xy, 0));+ float2 uv = (position.xy - Viewport.xy) / max(Viewport.zw, float2(1, 1));+ float4 world = mul(float4(uv * float2(2, -2) + float2(-1, 1), depth, 1), WorldFromClip);+ float w = abs(world.w) < 0.000001 ? 0.000001 : world.w;+ float2 at = world.xy / w;++ // the union of the fields: the largest distance, and the strongest opacity among the fields+ // the pixel is inside+ float d = -1.0e6;+ float inside[32];+ uint count = (uint)Look1.z;+ [unroll] for (uint i = 0; i < 32; ++i)+ {+ inside[i] = Grid[i].w;+ if (i < count)+ {+ float2 g = (at - Grid[i].xy) * Grid[i].z;+ if (all(g >= 0) && all(g <= Size[i].xy))+ {+ float2 base = min(floor(g), Size[i].xy - 1);+ float2 f = g - base;+ int3 p = int3(base, 0);+ float a = Fields[i].Load(p);+ float b = Fields[i].Load(p + int3(1, 0, 0));+ float c = Fields[i].Load(p + int3(0, 1, 0));+ float e = Fields[i].Load(p + int3(1, 1, 0));+ inside[i] = lerp(lerp(a, b, f.x), lerp(c, e, f.x), f.y);+ }+ d = max(d, inside[i]);+ }+ }++ // world units of distance a pixel spans; capped, so a cliff's or a bridge's edge in the depth+ // cannot widen the line beyond a pixel+ float pixel = clamp(fwidth(d), 0.001, 16.0);+ float opacity = 0;+ [unroll] for (uint k = 0; k < 32; ++k)+ if (k < count) opacity = max(opacity, Size[k].z * saturate(inside[k] / pixel));++ // nothing at or under nought: the antialiasing ramps inward from the edge, never out of it+ float edge = saturate(d / pixel);+ float border = max(Look0.x, pixel);+ float stroke = edge * saturate((border - d) / pixel + 0.5) * Look1.x;+ float band = saturate(1 - d / Look0.y);+ float fill = (Look0.z + Look0.w * band * band) * edge;+ float alpha = stroke + fill * (1 - stroke);+ float3 colour = lerp(Colour.rgb, float3(1, 1, 1), Look1.y) * stroke + Colour.rgb * fill * (1 - stroke);+ if (d <= 0 || depth >= 1) discard;+ return float4(colour, alpha) * opacity;+}+)HLSL";++struct FieldTexture+{+ ID3D11Texture2D *texture = nullptr;+ ID3D11ShaderResourceView *view = nullptr;+ UnsignedInt version = 0;+ Real originX = 0, originY = 0, step = 0;+ Int width = 0, height = 0;+ Bool used = false;+};++struct Shared+{+ ID3D11Device *device = nullptr;+ Bool refused = false;+ ID3D11VertexShader *fullscreen = nullptr;+ ID3D11PixelShader *pixel = nullptr;+ ID3D11BlendState *blend = nullptr;+ ID3D11RasterizerState *rasterizer = nullptr;+ ID3D11Buffer *constants = nullptr;+ std::vector< FieldTexture > fields;+};+Shared shared;++void releaseFields()+{+ for( FieldTexture &field : shared.fields )+ {+ drop( field.view );+ drop( field.texture );+ }+ shared.fields.clear();+}++void releaseShared()+{+ releaseFields();+ drop( shared.fullscreen );+ drop( shared.pixel );+ drop( shared.blend );+ drop( shared.rasterizer );+ drop( shared.constants );+ shared.device = nullptr;+ shared.refused = false;+}++Bool makeShared( DX11BackendClass *backend, ID3D11Device *device )+{+ if( shared.device == device )+ return !shared.refused;+ releaseShared();+ shared.device = device;+ std::vector< unsigned char > code;+ // the hazard clouds' full screen triangle, the same text, so the same program in the cache+ Bool made = backend->Compile_Program( HazardCloud::vertexShader(), "reach overlay fullscreen", "vs_5_0", code )+ && SUCCEEDED( device->CreateVertexShader( code.data(), code.size(), nullptr, &shared.fullscreen ) );+ made = made && backend->Compile_Program( PixelSource, "reach overlay", "ps_5_0", code )+ && SUCCEEDED( device->CreatePixelShader( code.data(), code.size(), nullptr, &shared.pixel ) );+ if( !made )+ DEBUG_LOG( ( "REACHOVERLAY: the Direct3D 11 program did not compile: %s\n", backend->First_Compiler_Error() ) );++ // premultiplied over the scene, its alpha left alone+ D3D11_BLEND_DESC blend = {};+ D3D11_RENDER_TARGET_BLEND_DESC &target = blend.RenderTarget[ 0 ];+ target.BlendEnable = TRUE;+ target.SrcBlend = D3D11_BLEND_ONE;+ target.DestBlend = D3D11_BLEND_INV_SRC_ALPHA;+ target.BlendOp = target.BlendOpAlpha = D3D11_BLEND_OP_ADD;+ target.SrcBlendAlpha = D3D11_BLEND_ZERO;+ target.DestBlendAlpha = D3D11_BLEND_ONE;+ target.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_RED | D3D11_COLOR_WRITE_ENABLE_GREEN | D3D11_COLOR_WRITE_ENABLE_BLUE;+ made = made && SUCCEEDED( device->CreateBlendState( &blend, &shared.blend ) );++ D3D11_RASTERIZER_DESC rasterizer = {};+ rasterizer.FillMode = D3D11_FILL_SOLID;+ rasterizer.CullMode = D3D11_CULL_NONE;+ rasterizer.DepthClipEnable = TRUE;+ rasterizer.ScissorEnable = TRUE;+ made = made && SUCCEEDED( device->CreateRasterizerState( &rasterizer, &shared.rasterizer ) );++ D3D11_BUFFER_DESC buffer = {};+ buffer.Usage = D3D11_USAGE_DYNAMIC;+ buffer.BindFlags = D3D11_BIND_CONSTANT_BUFFER;+ buffer.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;+ buffer.ByteWidth = sizeof( Constants );+ made = made && SUCCEEDED( device->CreateBuffer( &buffer, nullptr, &shared.constants ) );+ if( !made )+ {+ DEBUG_LOG( ( "REACHOVERLAY: Direct3D 11 refused the pass; the fixed-function overlay draws instead\n" ) );+ releaseShared();+ shared.device = device;+ shared.refused = true;+ }+ return made;+}++// The field's distances as a texture, kept while the field's version and grid hold.+ID3D11ShaderResourceView *viewFor( const ReachOverlayField &field )+{+ for( FieldTexture &held : shared.fields )+ {+ if( held.version == field.version && held.width == field.width && held.height == field.height+ && held.originX == field.originX && held.originY == field.originY && held.step == field.step )+ {+ held.used = true;+ return held.view;+ }+ }+ FieldTexture made;+ D3D11_TEXTURE2D_DESC description = {};+ description.Width = (UINT)field.width;+ description.Height = (UINT)field.height;+ description.MipLevels = 1;+ description.ArraySize = 1;+ description.Format = DXGI_FORMAT_R32_FLOAT;+ description.SampleDesc.Count = 1;+ description.Usage = D3D11_USAGE_IMMUTABLE;+ description.BindFlags = D3D11_BIND_SHADER_RESOURCE;+ D3D11_SUBRESOURCE_DATA data = {};+ data.pSysMem = field.distance.data();+ data.SysMemPitch = (UINT)( field.width * sizeof( Real ) );+ if( FAILED( shared.device->CreateTexture2D( &description, &data, &made.texture ) )+ || FAILED( shared.device->CreateShaderResourceView( made.texture, nullptr, &made.view ) ) )+ {+ drop( made.view );+ drop( made.texture );+ return nullptr;+ }+ made.version = field.version;+ made.originX = field.originX;+ made.originY = field.originY;+ made.step = field.step;+ made.width = field.width;+ made.height = field.height;+ made.used = true;+ shared.fields.push_back( made );+ return made.view;+}++// The camera as the scene is drawn from it: CameraClass::Apply's matrices and viewport.+struct SceneCamera+{+ float viewProjection[ 16 ];+ float worldFromClip[ 16 ];+ float x, y, width, height, minZ, maxZ;+};++Bool sceneCamera( CameraClass &camera, SceneCamera &result )+{+ Matrix4x4 projection;+ camera.Get_D3D_Projection_Matrix( &projection );+ Matrix3D view;+ camera.Get_View_Matrix( &view );+ const Matrix4x4 d3dProjection = projection.Transpose();+ const Matrix4x4 d3dView = Matrix4x4( view ).Transpose();+ float viewRows[ 16 ], projectionRows[ 16 ];+ memcpy( viewRows, &d3dView, sizeof( viewRows ) );+ memcpy( projectionRows, &d3dProjection, sizeof( projectionRows ) );+ HazardCloud::multiply( viewRows, projectionRows, result.viewProjection );+ if( !HazardCloud::inverse( result.viewProjection, result.worldFromClip ) )+ return false;++ int width, height, bits;+ bool windowed;+ WW3D::Get_Render_Target_Resolution( width, height, bits, windowed );+ const ViewportClass &viewport = camera.Get_Viewport();+ result.x = (float)(unsigned)( viewport.Min.X * (float)width );+ result.y = (float)(unsigned)( viewport.Min.Y * (float)height );+ result.width = (float)(unsigned)( ( viewport.Max.X - viewport.Min.X ) * (float)width );+ result.height = (float)(unsigned)( ( viewport.Max.Y - viewport.Min.Y ) * (float)height );+ camera.Get_Depth_Range( &result.minZ, &result.maxZ );+ const float range = result.maxZ - result.minZ;+ if( result.width < 1 || result.height < 1 || range <= 1.0e-8f )+ return false;+ // the depth read back is the viewport's, minZ to maxZ, not the projection's nought to one+ for( unsigned column = 0; column < 4; ++column )+ {+ const float row = result.worldFromClip[ 8 + column ] / range;+ result.worldFromClip[ 12 + column ] -= result.minZ * row;+ result.worldFromClip[ 8 + column ] = row;+ }+ return true;+}++/** The pixels a group of fields can cover: their rectangles from below the lowest ground to above+ * the highest bridge, through the camera. The whole viewport when a corner is behind it. */+D3D11_RECT coverage( const SceneCamera &camera, const ReachOverlayField *const *fields, unsigned count,+ unsigned targetWidth, unsigned targetHeight )+{+ const LONG left = (LONG)camera.x, top = (LONG)camera.y;+ const LONG right = (LONG)( std::min )( camera.x + camera.width, (float)targetWidth );+ const LONG bottom = (LONG)( std::min )( camera.y + camera.height, (float)targetHeight );+ const D3D11_RECT all = { left, top, right, bottom };+ const float lowZ = -20.0f, highZ = 255.0f * MAP_HEIGHT_SCALE + 80.0f;+ float minX = 1.0e30f, minY = 1.0e30f, maxX = -1.0e30f, maxY = -1.0e30f;+ for( unsigned f = 0; f < count; ++f )+ {+ const ReachOverlayField &field = *fields[ f ];+ const float xs[ 2 ] = { field.originX, field.originX + ( field.width - 1 ) * field.step };+ const float ys[ 2 ] = { field.originY, field.originY + ( field.height - 1 ) * field.step };+ const float zs[ 2 ] = { lowZ, highZ };+ for( unsigned corner = 0; corner < 8; ++corner )+ {+ const float point[ 4 ] = { xs[ corner & 1 ], ys[ ( corner >> 1 ) & 1 ], zs[ corner >> 2 ], 1.0f };+ float clip[ 4 ] = {};+ for( unsigned column = 0; column < 4; ++column )+ for( unsigned row = 0; row < 4; ++row )+ clip[ column ] += point[ row ] * camera.viewProjection[ row * 4 + column ];+ if( clip[ 3 ] <= 0.001f )+ return all;+ const float px = camera.x + ( clip[ 0 ] / clip[ 3 ] * 0.5f + 0.5f ) * camera.width;+ const float py = camera.y + ( 0.5f - clip[ 1 ] / clip[ 3 ] * 0.5f ) * camera.height;+ minX = ( std::min )( minX, px );+ maxX = ( std::max )( maxX, px );+ minY = ( std::min )( minY, py );+ maxY = ( std::max )( maxY, py );+ }+ }+ D3D11_RECT rect;+ rect.left = ( std::max )( left, (LONG)floorf( minX ) - 1 );+ rect.top = ( std::max )( top, (LONG)floorf( minY ) - 1 );+ rect.right = ( std::min )( right, (LONG)ceilf( maxX ) + 2 );+ rect.bottom = ( std::min )( bottom, (LONG)ceilf( maxY ) + 2 );+ return rect;+}++Bool supported( DX11DeviceClass *device )+{+ return Direct3D11_Present_Is_Enabled() && Direct3D11_Backend() && device && device->Get_Device()+ && device->Get_Depth_Texture() && device->Get_Device()->GetFeatureLevel() >= D3D_FEATURE_LEVEL_11_0;+}++} // namespace++void DX11ReachOverlay_Release( void )+{+ releaseShared();+}++Bool DX11ReachOverlay_Draw( CameraClass &camera, const std::vector< const ReachOverlayField * > &fields )+{+ DX11DeviceClass *device = Direct3D11_Device();+ DX11BackendClass *backend = Direct3D11_Backend();+ if( !supported( device ) )+ {+ if( shared.device )+ releaseShared();+ return false;+ }+ // made on the first terrain frame of a device (shell map or match), so the first defence shown+ // does not pay a compile; the cache makes it cheap after the first run+ const Bool made = makeShared( backend, device->Get_Device() );+ if( fields.empty() )+ {+ releaseFields();+ return true;+ }+ if( !made )+ return false;+ // a mirror or the sun's map has no scene target; the fixed-function sheet goes there+ ID3D11RenderTargetView *scene = backend->Scene_Target();+ if( !scene )+ return false;+ SceneCamera view;+ if( !sceneCamera( camera, view ) )+ return true; // nothing on the screen to draw on++ ID3D11DepthStencilView *sceneDepth = backend->Scene_Depth_Target();+ backend->Resolve_Scene_Depth();+ ID3D11ShaderResourceView *depth = device->Get_Depth_Texture();+ ID3D11DeviceContext *context = device->Get_Context();+ ID3D11Resource *sceneResource = nullptr;+ scene->GetResource( &sceneResource );+ D3D11_TEXTURE2D_DESC sceneDescription;+ static_cast< ID3D11Texture2D * >( sceneResource )->GetDesc( &sceneDescription );+ sceneResource->Release(); // the backend's own view keeps it++ for( FieldTexture &held : shared.fields )+ held.used = false;++ // the fields of each owner together, in runs of up to a pass's worth+ std::vector< const ReachOverlayField * > order( fields );+ std::stable_sort( order.begin(), order.end(),+ []( const ReachOverlayField *a, const ReachOverlayField *b ) { return ( a->color & 0xFFFFFF ) < ( b->color & 0xFFFFFF ); } );++ // Everything below binds on the context behind the backend's back: the viewport it set is put+ // back, the targets with their depth, and it forgets the rest.+ D3D11_VIEWPORT savedViewport;+ UINT viewportCount = 1;+ context->RSGetViewports( &viewportCount, &savedViewport );+ const D3D11_VIEWPORT sceneViewport = { view.x, view.y, view.width, view.height, view.minZ, view.maxZ };+ context->RSSetViewports( 1, &sceneViewport );+ context->OMSetRenderTargets( 1, &scene, nullptr );+ context->OMSetBlendState( shared.blend, nullptr, 0xffffffff );+ context->OMSetDepthStencilState( nullptr, 0 );+ context->RSSetState( shared.rasterizer );+ context->IASetInputLayout( nullptr );+ context->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );+ context->VSSetShader( shared.fullscreen, nullptr, 0 );+ context->PSSetShader( shared.pixel, nullptr, 0 );+ context->PSSetConstantBuffers( 0, 1, &shared.constants );++ Constants constants = {};+ memcpy( constants.WorldFromClip, view.worldFromClip, sizeof( constants.WorldFromClip ) );+ constants.Viewport[ 0 ] = view.x + 0.5f;+ constants.Viewport[ 1 ] = view.y + 0.5f;+ constants.Viewport[ 2 ] = view.width;+ constants.Viewport[ 3 ] = view.height;+ constants.Look0[ 0 ] = ReachLook::BorderWidth;+ constants.Look0[ 1 ] = ReachLook::BandWidth;+ constants.Look0[ 2 ] = ReachLook::FillAlpha;+ constants.Look0[ 3 ] = ReachLook::BandAlpha;+ constants.Look1[ 0 ] = ReachLook::LineAlpha;+ constants.Look1[ 1 ] = ReachLook::LineWhite;++ for( size_t start = 0; start < order.size(); )+ {+ const Int colour = order[ start ]->color & 0xFFFFFF;+ const ReachOverlayField *group[ FieldsPerPass ];+ ID3D11ShaderResourceView *views[ 1 + FieldsPerPass ] = { depth };+ unsigned count = 0;+ size_t next = start;+ for( ; next < order.size() && count < FieldsPerPass && ( order[ next ]->color & 0xFFFFFF ) == colour; ++next )+ {+ ID3D11ShaderResourceView *field = viewFor( *order[ next ] );+ if( !field )+ continue;+ const ReachOverlayField &source = *order[ next ];+ constants.Grid[ count ][ 0 ] = source.originX;+ constants.Grid[ count ][ 1 ] = source.originY;+ constants.Grid[ count ][ 2 ] = 1.0f / source.step;+ constants.Grid[ count ][ 3 ] = -( std::max )( source.distanceLimit, 1.0f );+ constants.Size[ count ][ 0 ] = (float)( source.width - 1 );+ constants.Size[ count ][ 1 ] = (float)( source.height - 1 );+ constants.Size[ count ][ 2 ] = ( std::min )( ( std::max )( source.opacity, 0.0f ), 1.0f );+ views[ 1 + count ] = field;+ group[ count++ ] = &source;+ }+ start = next;+ if( count == 0 )+ continue;+ constants.Colour[ 0 ] = ( ( colour >> 16 ) & 0xff ) / 255.0f;+ constants.Colour[ 1 ] = ( ( colour >> 8 ) & 0xff ) / 255.0f;+ constants.Colour[ 2 ] = ( colour & 0xff ) / 255.0f;+ constants.Look1[ 2 ] = (float)count;+ const D3D11_RECT rect = coverage( view, group, count, sceneDescription.Width, sceneDescription.Height );+ if( rect.right <= rect.left || rect.bottom <= rect.top )+ continue;+ D3D11_MAPPED_SUBRESOURCE mapped;+ if( FAILED( context->Map( shared.constants, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped ) ) )+ continue;+ memcpy( mapped.pData, &constants, sizeof( constants ) );+ context->Unmap( shared.constants, 0 );+ context->RSSetScissorRects( 1, &rect );+ context->PSSetShaderResources( 0, 1 + FieldsPerPass, views );+ context->Draw( 3, 0 );+ }++ ID3D11ShaderResourceView *const none[ 1 + FieldsPerPass ] = {};+ context->PSSetShaderResources( 0, 1 + FieldsPerPass, none );+ context->OMSetRenderTargets( 1, &scene, sceneDepth );+ context->RSSetViewports( viewportCount, &savedViewport );+ backend->Forget_Bindings();+ static Bool logged = false;+ if( !logged )+ {+ logged = true;+ DEBUG_LOG( ( "REACHOVERLAY: Direct3D 11 pass drawn, %d fields\n", (Int)fields.size() ) );+ }++ // a texture no field drew this frame goes; a field shown again is uploaded again, which is cheap+ for( size_t i = shared.fields.size(); i-- > 0; )+ {+ if( !shared.fields[ i ].used )+ {+ drop( shared.fields[ i ].view );+ drop( shared.fields[ i ].texture );+ shared.fields.erase( shared.fields.begin() + i );+ }+ }+ return true;+}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cppindex a00cebabf..49a321b2a 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp@@ -80,6 +80,7 @@#include "W3DDevice/GameClient/W3DDynamicLight.h"#include "W3DDevice/GameClient/W3DScene.h"#include "W3DDevice/GameClient/W3DTerrainTracks.h"+#include "W3DDevice/GameClient/W3DReachOverlay.h"#include "W3DDevice/GameClient/W3DBibBuffer.h"#include "W3DDevice/GameClient/W3DTreeBuffer.h"#include "W3DDevice/GameClient/W3DPropBuffer.h"@@ -1108,6 +1109,7 @@ Int HeightMapRenderObjClass::updateBlock(Int x0, Int y0, Int x1, Int y1, WorldH//=============================================================================HeightMapRenderObjClass::~HeightMapRenderObjClass(void){+ W3DReachOverlay_Release();freeMapResources();if (m_extraBlendTilePositions) {delete [] m_extraBlendTilePositions;@@ -1222,6 +1224,7 @@ void HeightMapRenderObjClass::adjustTerrainLOD(Int adj)//=============================================================================void HeightMapRenderObjClass::ReleaseResources(void){+ W3DReachOverlay_Release();BaseHeightMapRenderObjClass::ReleaseResources();}@@ -2218,6 +2221,12 @@ void HeightMapRenderObjClass::Render(RenderInfoClass & rinfo)}}#endif+ // A defence's hittable ground goes on the bare ground and its roads, read back from their depth+ // on Direct3D 11: so before the props and the bridges, which stand on it, and before the shroud,+ // which darkens it with the ground. Every model is drawn over it. Not into a mirror.+ if (!ShaderClass::Is_Backface_Culling_Inverted())+ W3DReachOverlay_Draw(rinfo.Camera);+if (m_propBuffer) {m_propBuffer->drawProps(rinfo);}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DReachOverlay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DReachOverlay.cppnew file mode 100644index 000000000..dea65dc42--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DReachOverlay.cpp@@ -0,0 +1,354 @@+// The ground a defence can hit, on the terrain. Direct3D 11 draws it in DX11ReachOverlay.cpp from+// the distance fields themselves; this file picks the pass and holds the fixed-function one that+// -d3d9, SDL3 and a refused Direct3D 11 program fall back to.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "W3DDevice/GameClient/W3DReachOverlay.h"++#include "Common/Debug.h"+#include "Common/MapObject.h"+#include "GameClient/ReachOverlay.h"+#include "W3DDevice/GameClient/BaseHeightMap.h"+#include "W3DDevice/GameClient/WorldHeightMap.h"+#include "WW3D2/camera.h"+#include "WW3D2/dx8wrapper.h"+#include "WW3D2/dx8vertexbuffer.h"+#include "WW3D2/dx8indexbuffer.h"+#include "WW3D2/shader.h"+#include "WW3D2/texture.h"+#include "WW3D2/vertmaterial.h"+#include "WW3D2/surfaceclass.h"++#include <cmath>++namespace+{++/* The fixed-function look is a texture baked from the field, drawn on the terrain's own cells.++ The baked grid is the field's grid cut n ways, so every baked texel's cell lies inside one of the+ field's cells and the field taken bilinearly over it is a blend of its four corners. A texel is+ lit only when it and its eight neighbours are all inside, so whatever the filter blends into a+ pixel comes from a baked cell whose four corners are inside, and the field there is inside too:+ the area shrinks by at most one baked texel and never grows. */+const Int MaxBakedSide = 512;+const Real BakedTexel = 0.75f; // finest texel, world units: half the border line+const Real InsideMargin = 0.05f; // world units, for the filter's own rounding+const Real CellLift = 0.01f * MAP_XY_FACTOR; // the projected decals' lift off the ground they are laid on++struct Baked+{+ TextureClass *texture;+ UnsignedInt version;+ Real originX, originY, step;+ Int width, height;+ Int color; // the owner's, baked in: the line is lighter than the fill+ Real texel; // world units a baked texel spans+ Int side[ 2 ]; // the texture's size, a power of two each way+ Bool used;+};+std::vector< Baked > s_baked;++Bool sameGrid( const Baked &baked, const ReachOverlayField &field )+{+ return baked.version == field.version && baked.width == field.width && baked.height == field.height+ && baked.originX == field.originX && baked.originY == field.originY && baked.step == field.step+ && baked.color == ( field.color & 0xFFFFFF );+}++Real clamp01( Real value )+{+ return value < 0.0f ? 0.0f : ( value > 1.0f ? 1.0f : value );+}++// The field taken bilinearly at grid coordinates (gx, gy), both inside the grid.+Real fieldAt( const ReachOverlayField &field, Real gx, Real gy )+{+ Int i = (Int)floorf( gx ), j = (Int)floorf( gy );+ if( i > field.width - 2 ) i = field.width - 2;+ if( j > field.height - 2 ) j = field.height - 2;+ const Real fx = gx - (Real)i, fy = gy - (Real)j;+ const Real *row = &field.distance[ j * field.width + i ];+ const Real bottom = row[ 0 ] + ( row[ 1 ] - row[ 0 ] ) * fx;+ const Real top = row[ field.width ] + ( row[ field.width + 1 ] - row[ field.width ] ) * fx;+ return bottom + ( top - bottom ) * fy;+}++/** A baked texel at distance d inside the edge, as straight colour and alpha for a SRCALPHA blend.+ * The lit texels start up to a texel and a half in (the nine-neighbour rule), so the line is laid+ * from there, and at least two texels wide: at the border's own 1.5 units a coarse texel held half+ * a line, which the filter smeared into the fade and no edge showed. */+UnsignedInt texelAt( Real d, Real texel, const Real owner[ 3 ] )+{+ const Real lineEnd = 1.5f * texel + ( ReachLook::BorderWidth > 2.0f * texel ? ReachLook::BorderWidth : 2.0f * texel );+ const Real line = clamp01( ( lineEnd - d ) / texel ) * ReachLook::LineAlpha;+ Real band = clamp01( 1.0f - d / ReachLook::BandWidth );+ band *= band;+ const Real fill = ( ReachLook::FillAlpha + ReachLook::BandAlpha * band ) * ( 1.0f - line );+ const Real alpha = line + fill;+ UnsignedInt result = (UnsignedInt)( alpha * 255.0f + 0.5f ) << 24;+ for( Int c = 0; c < 3; ++c )+ {+ const Real lineColour = owner[ c ] + ( 1.0f - owner[ c ] ) * ReachLook::LineWhite;+ const Real colour = alpha > 0.0f ? ( lineColour * line + owner[ c ] * fill ) / alpha : owner[ c ];+ result |= (UnsignedInt)( clamp01( colour ) * 255.0f + 0.5f ) << ( 16 - 8 * c );+ }+ return result;+}++Int powerOfTwo( Int value )+{+ Int result = 1;+ while( result < value )+ result <<= 1;+ return result;+}++Bool bake( const ReachOverlayField &field, Baked &baked )+{+ Int cuts = (Int)ceilf( field.step / BakedTexel );+ cuts = cuts < 1 ? 1 : ( cuts > 8 ? 8 : cuts );+ while( cuts > 1 && ( ( field.width - 1 ) * cuts + 1 > MaxBakedSide || ( field.height - 1 ) * cuts + 1 > MaxBakedSide ) )+ --cuts;+ const Int across = ( field.width - 1 ) * cuts + 1, down = ( field.height - 1 ) * cuts + 1;+ if( across > MaxBakedSide * 2 || down > MaxBakedSide * 2 )+ return FALSE; // ponytail: a field past 1024 samples a side is left out here; cut the grid if one ever comes++ std::vector< Real > d( across * down );+ for( Int y = 0; y < down; ++y )+ for( Int x = 0; x < across; ++x )+ d[ y * across + x ] = fieldAt( field, (Real)x / cuts, (Real)y / cuts );++ baked.texel = field.step / cuts;+ baked.side[ 0 ] = powerOfTwo( across );+ baked.side[ 1 ] = powerOfTwo( down );+ baked.texture = MSGNEW( "TextureClass" ) TextureClass( baked.side[ 0 ], baked.side[ 1 ], WW3D_FORMAT_A8R8G8B8, MIP_LEVELS_1 );+ SurfaceClass *surface = baked.texture->Get_Surface_Level();+ Int pitch = 0;+ UnsignedByte *bits = surface ? (UnsignedByte *)surface->Lock( &pitch ) : NULL;+ if( bits == NULL )+ {+ REF_PTR_RELEASE( surface );+ REF_PTR_RELEASE( baked.texture );+ return FALSE;+ }+ const Real owner[ 3 ] = { ( ( field.color >> 16 ) & 0xff ) / 255.0f, ( ( field.color >> 8 ) & 0xff ) / 255.0f,+ ( field.color & 0xff ) / 255.0f };+ // what an unlit texel holds: no alpha and the line's colour, so the filter blends no other colour+ // into the edge it fades out on+ const UnsignedInt unlit = texelAt( 0.0f, baked.texel, owner ) & 0x00FFFFFF;+ for( Int y = 0; y < baked.side[ 1 ]; ++y )+ {+ UnsignedInt *row = (UnsignedInt *)( bits + y * pitch );+ for( Int x = 0; x < baked.side[ 0 ]; ++x )+ {+ Bool lit = x > 0 && y > 0 && x < across - 1 && y < down - 1;+ for( Int dy = -1; lit && dy <= 1; ++dy )+ for( Int dx = -1; lit && dx <= 1; ++dx )+ lit = d[ ( y + dy ) * across + x + dx ] > InsideMargin;+ row[ x ] = lit ? texelAt( d[ y * across + x ], baked.texel, owner ) : unlit;+ }+ }+ surface->Unlock();+ REF_PTR_RELEASE( surface );+ baked.texture->Get_Filter().Set_U_Addr_Mode( TextureFilterClass::TEXTURE_ADDRESS_CLAMP );+ baked.texture->Get_Filter().Set_V_Addr_Mode( TextureFilterClass::TEXTURE_ADDRESS_CLAMP );+ return TRUE;+}++Baked *bakedFor( const ReachOverlayField &field )+{+ for( size_t i = 0; i < s_baked.size(); ++i )+ if( sameGrid( s_baked[ i ], field ) )+ return &s_baked[ i ];+ Baked baked = {};+ baked.version = field.version;+ baked.originX = field.originX;+ baked.originY = field.originY;+ baked.step = field.step;+ baked.width = field.width;+ baked.height = field.height;+ baked.color = field.color & 0xFFFFFF;+ if( !bake( field, baked ) )+ return NULL;+ s_baked.push_back( baked );+ return &s_baked.back();+}++// Prelit, textured, alpha blended over the ground and depth tested against it, no depth written.+#define SC_REACH_OVERLAY ( SHADE_CNST(ShaderClass::PASS_LEQUAL, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, ShaderClass::SRCBLEND_SRC_ALPHA, \+ ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, ShaderClass::TEXTURING_ENABLE, \+ ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_DISABLE, \+ ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) )++/** One field on the terrain's own vertices: the heights and the diagonal of every cell as the ground+ * is drawn (queueDecal's fill), lifted as the decals are, so it lies on the ground without fighting+ * it. Several fields of one owner overlap here as two sheets. */+void drawCells( const ReachOverlayField &field, const Baked &baked )+{+ WorldHeightMap *map = TheTerrainRenderObject->getMap();+ if( map == NULL )+ return;+ const Int border = map->getBorderSizeInline();+ const Int lastX = map->getXExtent() - 1, lastY = map->getYExtent() - 1;+ const Real maxX = field.originX + ( field.width - 1 ) * field.step;+ const Real maxY = field.originY + ( field.height - 1 ) * field.step;+ Int startX = (Int)floorf( field.originX / MAP_XY_FACTOR ) + border;+ Int endX = (Int)ceilf( maxX / MAP_XY_FACTOR ) + border;+ Int startY = (Int)floorf( field.originY / MAP_XY_FACTOR ) + border;+ Int endY = (Int)ceilf( maxY / MAP_XY_FACTOR ) + border;+ startX = startX < 0 ? 0 : ( startX > lastX ? lastX : startX );+ endX = endX < 0 ? 0 : ( endX > lastX ? lastX : endX );+ startY = startY < 0 ? 0 : ( startY > lastY ? lastY : startY );+ endY = endY < 0 ? 0 : ( endY > lastY ? lastY : endY );+ const Int vertsPerRow = endX - startX + 1;+ if( vertsPerRow < 2 || endY <= startY )+ return;++ // the colour is in the texture; the vertex carries the opacity alone+ const UnsignedInt alpha = (UnsignedInt)( clamp01( field.opacity ) * 255.0f + 0.5f );+ const UnsignedInt diffuse = ( alpha << 24 ) | 0x00FFFFFF;+ const Real uScale = 1.0f / ( baked.texel * baked.side[ 0 ] ), vScale = 1.0f / ( baked.texel * baked.side[ 1 ] );+ const Real uHalf = 0.5f / baked.side[ 0 ], vHalf = 0.5f / baked.side[ 1 ];+ const UnsignedByte *heights = map->getDataPtr();+ const Int heightRow = map->getXExtent();++ // in row bands, so a band's vertices and its 16 bit indices fit the dynamic buffers+ const Int cellsPerRow = vertsPerRow - 1;+ Int rowsPerBand = 16000 / vertsPerRow - 1;+ if( rowsPerBand * cellsPerRow * 6 > 60000 )+ rowsPerBand = 60000 / ( cellsPerRow * 6 );+ if( rowsPerBand < 1 )+ return;+ for( Int bandStart = startY; bandStart < endY; bandStart += rowsPerBand )+ {+ const Int bandEnd = bandStart + rowsPerBand < endY ? bandStart + rowsPerBand : endY;+ const Int rows = bandEnd - bandStart;+ const Int verts = ( rows + 1 ) * vertsPerRow;+ DynamicVBAccessClass vbAccess( BUFFER_TYPE_DYNAMIC_DX8, DX8_FVF_XYZNDUV2, verts );+ DynamicIBAccessClass ibAccess( BUFFER_TYPE_DYNAMIC_DX8, rows * cellsPerRow * 6 );+ {+ DynamicVBAccessClass::WriteLockClass vbLock( &vbAccess );+ DynamicIBAccessClass::WriteLockClass ibLock( &ibAccess );+ VertexFormatXYZNDUV2 *vb = vbLock.Get_Formatted_Vertex_Array();+ UnsignedShort *ib = ibLock.Get_Index_Array();+ if( vb == NULL || ib == NULL )+ return;+ for( Int j = bandStart; j <= bandEnd; ++j )+ {+ const Real y = (Real)( j - border ) * MAP_XY_FACTOR;+ const UnsignedByte *height = heights + j * heightRow + startX;+ for( Int i = 0; i < vertsPerRow; ++i, ++vb )+ {+ const Real x = (Real)( startX + i - border ) * MAP_XY_FACTOR;+ vb->x = x;+ vb->y = y;+ vb->z = (Real)height[ i ] * MAP_HEIGHT_SCALE + CellLift;+ vb->nx = 0.0f;+ vb->ny = 0.0f;+ vb->nz = 1.0f;+ vb->diffuse = diffuse;+ vb->u1 = ( x - field.originX ) * uScale + uHalf;+ vb->v1 = ( y - field.originY ) * vScale + vHalf;+ vb->u2 = 0.0f;+ vb->v2 = 0.0f;+ }+ }+ for( Int j = 0; j < rows; ++j )+ {+ for( Int k = 0; k < cellsPerRow; ++k )+ {+ const UnsignedShort at = (UnsignedShort)( j * vertsPerRow + k );+ if( map->getQuickFlipState( startX + k, bandStart + j ) )+ {+ *ib++ = at + 1; *ib++ = at + vertsPerRow; *ib++ = at;+ *ib++ = at + 1; *ib++ = at + 1 + vertsPerRow; *ib++ = at + vertsPerRow;+ }+ else+ {+ *ib++ = at; *ib++ = at + 1 + vertsPerRow; *ib++ = at + vertsPerRow;+ *ib++ = at; *ib++ = at + 1; *ib++ = at + 1 + vertsPerRow;+ }+ }+ }+ }+ DX8Wrapper::Set_Index_Buffer( ibAccess, 0 );+ DX8Wrapper::Set_Vertex_Buffer( vbAccess );+ DX8Wrapper::Draw_Triangles( 0, rows * cellsPerRow * 2, 0, verts );+ }+}++void drawFixedFunction( const std::vector< const ReachOverlayField * > &fields )+{+ if( TheTerrainRenderObject == NULL || DX8Wrapper::_Get_D3D_Device() == NULL )+ return;+ static ShaderClass shader( SC_REACH_OVERLAY );+ VertexMaterialClass *material = VertexMaterialClass::Get_Preset( VertexMaterialClass::PRELIT_DIFFUSE );+ DX8Wrapper::Set_Material( material );+ REF_PTR_RELEASE( material );+ DX8Wrapper::Set_Shader( shader );+ DX8Wrapper::Set_Transform( D3DTS_WORLD, Matrix3D( 1 ) );+ for( size_t i = 0; i < fields.size(); ++i )+ {+ Baked *baked = bakedFor( *fields[ i ] );+ if( baked == NULL )+ continue;+ baked->used = TRUE;+ DX8Wrapper::Set_Texture( 0, baked->texture );+ DX8Wrapper::Set_Texture( 1, NULL );+ drawCells( *fields[ i ], *baked );+ }+ DX8Wrapper::Set_Texture( 0, NULL );+ ShaderClass::Invalidate();+ static Bool logged = FALSE;+ if( !logged )+ {+ logged = TRUE;+ DEBUG_LOG( ( "REACHOVERLAY: fixed-function sheet drawn, %d fields\n", (Int)fields.size() ) );+ }+}++} // namespace++void W3DReachOverlay_Release( void )+{+ for( size_t i = 0; i < s_baked.size(); ++i )+ REF_PTR_RELEASE( s_baked[ i ].texture );+ s_baked.clear();+#ifdef _WIN32+ DX11ReachOverlay_Release();+#endif+}++void W3DReachOverlay_Draw( CameraClass &camera )+{+ static std::vector< const ReachOverlayField * > fields;+ fields.clear();+ ReachOverlay_getFields( fields );+ // a field with no cell to blend cannot be drawn by either pass+ for( size_t i = fields.size(); i-- > 0; )+ {+ const ReachOverlayField *field = fields[ i ];+ if( field->width < 2 || field->height < 2 || field->step <= 0.0f || field->opacity <= 0.0f+ || field->distance.size() < (size_t)field->width * field->height )+ fields.erase( fields.begin() + i );+ }++ for( size_t i = 0; i < s_baked.size(); ++i )+ s_baked[ i ].used = FALSE;+ // Direct3D 11 is asked with no fields too, so it lets go of its textures+ Bool drawn = fields.empty();+#ifdef _WIN32+ drawn = DX11ReachOverlay_Draw( camera, fields ) || drawn;+#endif+ if( !drawn )+ drawFixedFunction( fields );+ // a texture no field drew this frame goes; a field shown again is baked again, which is cheap+ for( size_t i = s_baked.size(); i-- > 0; )+ {+ if( !s_baked[ i ].used )+ {+ REF_PTR_RELEASE( s_baked[ i ].texture );+ s_baked.erase( s_baked.begin() + i );+ }+ }+}