LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpRallyPointRenderer.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 10 505 2.0 %
Date: 2026-12-02 01:21:50 Functions: 1 30 3.3 %

          Line data    Source code
       1             : /* Copyright (C) 2025 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "CCmpRallyPointRenderer.h"
      21             : 
      22             : #include "graphics/TextureManager.h"
      23             : #include "lib/debug.h"
      24             : #include "lib/path.h"
      25             : #include "maths/Fixed.h"
      26             : #include "maths/FixedVector3D.h"
      27             : #include "ps/CLogger.h"
      28             : #include "ps/Profile.h"
      29             : #include "ps/algorithm.h"
      30             : #include "renderer/Renderer.h"
      31             : #include "renderer/Scene.h"
      32             : #include "renderer/backend/Sampler.h"
      33             : #include "simulation2/MessageTypes.h"
      34             : #include "simulation2/components/ICmpFootprint.h"
      35             : #include "simulation2/components/ICmpIdentity.h"
      36             : #include "simulation2/components/ICmpObstructionManager.h"
      37             : #include "simulation2/components/ICmpOwnership.h"
      38             : #include "simulation2/components/ICmpPathfinder.h"
      39             : #include "simulation2/components/ICmpPlayer.h"
      40             : #include "simulation2/components/ICmpPlayerManager.h"
      41             : #include "simulation2/components/ICmpPosition.h"
      42             : #include "simulation2/components/ICmpRangeManager.h"
      43             : #include "simulation2/components/ICmpTerrain.h"
      44             : #include "simulation2/components/ICmpWaterManager.h"
      45             : #include "simulation2/helpers/Geometry.h"
      46             : #include "simulation2/helpers/Los.h"
      47             : #include "simulation2/helpers/PathGoal.h"
      48             : #include "simulation2/helpers/Pathfinding.h"
      49             : #include "simulation2/helpers/Position.h"
      50             : #include "simulation2/helpers/Render.h"
      51             : #include "simulation2/system/Message.h"
      52             : 
      53             : #include <algorithm>
      54             : #include <cmath>
      55             : 
      56             : class CFrustum;
      57             : 
      58         137 : std::string CCmpRallyPointRenderer::GetSchema()
      59             : {
      60         137 :     return
      61             :         "<a:help>Displays a rally point marker where created units will gather when spawned</a:help>"
      62             :         "<a:example>"
      63             :             "<MarkerTemplate>special/rallypoint</MarkerTemplate>"
      64             :             "<LineThickness>0.75</LineThickness>"
      65             :             "<LineStartCap>round</LineStartCap>"
      66             :             "<LineEndCap>square</LineEndCap>"
      67             :             "<LineDashColor r='158' g='11' b='15'></LineDashColor>"
      68             :             "<LinePassabilityClass>default</LinePassabilityClass>"
      69             :         "</a:example>"
      70             :         "<element name='MarkerTemplate' a:help='Template name for the rally point marker entity (typically a waypoint flag actor)'>"
      71             :             "<text/>"
      72             :         "</element>"
      73             :         "<element name='LineTexture' a:help='Texture file to use for the rally point line'>"
      74             :             "<text />"
      75             :         "</element>"
      76             :         "<element name='LineTextureMask' a:help='Texture mask to indicate where overlay colors are to be applied (see LineColor and LineDashColor)'>"
      77             :             "<text />"
      78             :         "</element>"
      79             :         "<element name='LineThickness' a:help='Thickness of the marker line connecting the entity to the rally point marker'>"
      80             :             "<data type='decimal'/>"
      81             :         "</element>"
      82             :         "<element name='LineDashColor'>"
      83             :             "<attribute name='r'>"
      84             :                 "<data type='integer'><param name='minInclusive'>0</param><param name='maxInclusive'>255</param></data>"
      85             :             "</attribute>"
      86             :             "<attribute name='g'>"
      87             :                 "<data type='integer'><param name='minInclusive'>0</param><param name='maxInclusive'>255</param></data>"
      88             :             "</attribute>"
      89             :             "<attribute name='b'>"
      90             :                 "<data type='integer'><param name='minInclusive'>0</param><param name='maxInclusive'>255</param></data>"
      91             :             "</attribute>"
      92             :         "</element>"
      93             :         "<element name='LineStartCap'>"
      94             :             "<choice>"
      95             :                 "<value a:help='Abrupt line ending; line endings are not closed'>flat</value>"
      96             :                 "<value a:help='Semi-circular line end cap'>round</value>"
      97             :                 "<value a:help='Sharp, pointy line end cap'>sharp</value>"
      98             :                 "<value a:help='Square line end cap'>square</value>"
      99             :             "</choice>"
     100             :         "</element>"
     101             :         "<element name='LineEndCap'>"
     102             :             "<choice>"
     103             :                 "<value a:help='Abrupt line ending; line endings are not closed'>flat</value>"
     104             :                 "<value a:help='Semi-circular line end cap'>round</value>"
     105             :                 "<value a:help='Sharp, pointy line end cap'>sharp</value>"
     106             :                 "<value a:help='Square line end cap'>square</value>"
     107             :             "</choice>"
     108             :         "</element>"
     109             :         "<element name='LinePassabilityClass' a:help='The pathfinder passability class to use for computing the rally point marker line path'>"
     110             :             "<text />"
     111         137 :         "</element>";
     112             : }
     113             : 
     114           0 : void CCmpRallyPointRenderer::Init(const CParamNode& paramNode)
     115             : {
     116           0 :     m_Displayed = false;
     117           0 :     m_SmoothPath = true;
     118           0 :     m_LastOwner = INVALID_PLAYER;
     119           0 :     m_LastMarkerCount = 0;
     120           0 :     m_EnableDebugNodeOverlay = false;
     121             : 
     122           0 :     UpdateLineColor();
     123             :     // ---------------------------------------------------------------------------------------------
     124             :     // Load some XML configuration data (schema guarantees that all these nodes are valid)
     125             : 
     126           0 :     m_MarkerTemplate = paramNode.GetChild("MarkerTemplate").ToWString();
     127           0 :     const CParamNode& lineDashColor = paramNode.GetChild("LineDashColor");
     128           0 :     m_LineDashColor = CColor(
     129           0 :         lineDashColor.GetChild("@r").ToInt()/255.f,
     130           0 :         lineDashColor.GetChild("@g").ToInt()/255.f,
     131           0 :         lineDashColor.GetChild("@b").ToInt()/255.f,
     132             :         1.f
     133             :     );
     134             : 
     135           0 :     m_LineThickness = paramNode.GetChild("LineThickness").ToFixed().ToFloat();
     136           0 :     m_LineTexturePath = paramNode.GetChild("LineTexture").ToWString();
     137           0 :     m_LineTextureMaskPath = paramNode.GetChild("LineTextureMask").ToWString();
     138           0 :     m_LineStartCapType = SOverlayTexturedLine::StrToLineCapType(paramNode.GetChild("LineStartCap").ToWString());
     139           0 :     m_LineEndCapType = SOverlayTexturedLine::StrToLineCapType(paramNode.GetChild("LineEndCap").ToWString());
     140           0 :     m_LinePassabilityClass = paramNode.GetChild("LinePassabilityClass").ToString();
     141             : 
     142             :     // ---------------------------------------------------------------------------------------------
     143             :     // Load some textures
     144             : 
     145           0 :     if (CRenderer::IsInitialised())
     146             :     {
     147           0 :         CTextureProperties texturePropsBase(m_LineTexturePath);
     148           0 :         texturePropsBase.SetAddressMode(
     149             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_BORDER,
     150             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
     151           0 :         texturePropsBase.SetAnisotropicFilter(true);
     152           0 :         m_Texture = g_Renderer.GetTextureManager().CreateTexture(texturePropsBase);
     153             : 
     154           0 :         CTextureProperties texturePropsMask(m_LineTextureMaskPath);
     155           0 :         texturePropsMask.SetAddressMode(
     156             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_BORDER,
     157             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
     158           0 :         texturePropsMask.SetAnisotropicFilter(true);
     159           0 :         m_TextureMask = g_Renderer.GetTextureManager().CreateTexture(texturePropsMask);
     160           0 :     }
     161           0 : }
     162             : 
     163         137 : void CCmpRallyPointRenderer::ClassInit(CComponentManager& componentManager)
     164             : {
     165         137 :     componentManager.SubscribeGloballyToMessageType(MT_PlayerColorChanged);
     166         137 :     componentManager.SubscribeToMessageType(MT_OwnershipChanged);
     167         137 :     componentManager.SubscribeToMessageType(MT_TurnStart);
     168         137 :     componentManager.SubscribeToMessageType(MT_Destroy);
     169         137 :     componentManager.SubscribeToMessageType(MT_PositionChanged);
     170         137 : }
     171             : 
     172           0 : void CCmpRallyPointRenderer::Deinit()
     173             : {
     174           0 : }
     175             : 
     176           0 : void CCmpRallyPointRenderer::Serialize(ISerializer&)
     177             : {
     178             :     // Do NOT serialize anything; this is a rendering-only component, it does not and should not affect simulation state
     179           0 : }
     180             : 
     181           0 : void CCmpRallyPointRenderer::Deserialize(const CParamNode& paramNode, IDeserializer&)
     182             : {
     183           0 :     Init(paramNode);
     184             :     // The dependent components have not been deserialized, so the color is loaded on first SetDisplayed
     185           0 : }
     186             : 
     187           0 : void CCmpRallyPointRenderer::HandleMessage(const CMessage& msg, bool /*global*/)
     188             : {
     189           0 :     switch (msg.GetType())
     190             :     {
     191           0 :     case MT_PlayerColorChanged:
     192           0 :     {
     193           0 :         const CMessagePlayerColorChanged& msgData = static_cast<const CMessagePlayerColorChanged&> (msg);
     194             : 
     195           0 :         CmpPtr<ICmpOwnership> cmpOwnership(GetEntityHandle());
     196           0 :         if (!cmpOwnership || msgData.player != cmpOwnership->GetOwner())
     197             :             break;
     198             : 
     199           0 :         UpdateLineColor();
     200           0 :         ConstructAllOverlayLines();
     201             :     }
     202             :     break;
     203           0 :     case MT_RenderSubmit:
     204           0 :     {
     205           0 :         PROFILE("RallyPoint::RenderSubmit");
     206           0 :         if (m_Displayed && IsSet())
     207             :         {
     208           0 :             const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
     209           0 :             RenderSubmit(msgData.collector, msgData.frustum, msgData.culling);
     210             :         }
     211           0 :     }
     212           0 :     break;
     213           0 :     case MT_OwnershipChanged:
     214           0 :     {
     215           0 :         const CMessageOwnershipChanged& msgData = static_cast<const CMessageOwnershipChanged&> (msg);
     216             : 
     217             :         // Ignore destroyed entities
     218           0 :         if (msgData.to == INVALID_PLAYER)
     219             :             break;
     220           0 :         Reset();
     221             :         // Required for both the initial and capturing players color
     222           0 :         UpdateLineColor();
     223             : 
     224             :         // Support capturing, even though RallyPoint is typically deleted then
     225           0 :         UpdateMarkers();
     226           0 :         ConstructAllOverlayLines();
     227             :     }
     228           0 :     break;
     229           0 :     case MT_TurnStart:
     230           0 :     {
     231           0 :         UpdateOverlayLines(); // Check for changes to the SoD and update the overlay lines accordingly
     232             :     }
     233           0 :     break;
     234           0 :     case MT_Destroy:
     235           0 :     {
     236           0 :         Reset();
     237             :     }
     238           0 :     break;
     239           0 :     case MT_PositionChanged:
     240           0 :     {
     241             :         // Unlikely to happen in-game, but can occur in atlas
     242             :         // Just recompute the path from the entity to the first rally point
     243           0 :         RecomputeRallyPointPath_wrapper(0);
     244             :     }
     245           0 :     break;
     246             :     }
     247           0 : }
     248             : 
     249           0 : void CCmpRallyPointRenderer::UpdateMessageSubscriptions()
     250             : {
     251           0 :     GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_RenderSubmit, this, m_Displayed && IsSet());
     252           0 : }
     253             : 
     254           0 : void CCmpRallyPointRenderer::CreateMarkerEntity(size_t index, player_id_t ownerId)
     255             : {
     256           0 :     if (m_MarkerTemplate.empty() || ownerId == INVALID_PLAYER)
     257           0 :         return;
     258             : 
     259           0 :     CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
     260           0 :     if (!cmpPlayerManager)
     261             :         return;
     262             : 
     263           0 :     CmpPtr<ICmpPlayer> cmpPlayer(GetSimContext(), cmpPlayerManager->GetPlayerByID(ownerId));
     264           0 :     if (!cmpPlayer)
     265             :         return;
     266             : 
     267           0 :     CmpPtr<ICmpIdentity> cmpIdentity(GetSimContext(), cmpPlayer->GetEntityId());
     268           0 :     if (!cmpIdentity)
     269             :         return;
     270             : 
     271             :     // Create a copy we do not want to alter the marker template.
     272           0 :     std::wstring markerTemplate = m_MarkerTemplate;
     273           0 :     PS::ReplaceSubrange(markerTemplate, L"{civ}", cmpIdentity->GetCiv());
     274             : 
     275           0 :     CComponentManager& componentMgr = GetSimContext().GetComponentManager();
     276           0 :     entity_id_t newMarker = componentMgr.AllocateNewLocalEntity();
     277             : 
     278           0 :     if (newMarker != INVALID_ENTITY)
     279           0 :         newMarker = componentMgr.AddEntity(markerTemplate, newMarker);
     280             : 
     281           0 :     m_MarkerEntityIds[index] = newMarker;
     282           0 : }
     283             : 
     284           0 : void CCmpRallyPointRenderer::UpdateMarkers()
     285             : {
     286           0 :     player_id_t previousOwner = m_LastOwner;
     287           0 :     CmpPtr<ICmpOwnership> cmpOwnership(GetEntityHandle());
     288           0 :     const player_id_t ownerId{cmpOwnership ? cmpOwnership->GetOwner() : 0};
     289             : 
     290           0 :     for (size_t i = 0; i < m_RallyPoints.size(); ++i)
     291             :     {
     292           0 :         if (i >= m_MarkerEntityIds.size())
     293           0 :             m_MarkerEntityIds.push_back(INVALID_ENTITY);
     294             : 
     295           0 :         if (m_MarkerEntityIds[i] == INVALID_ENTITY)
     296           0 :             CreateMarkerEntity(i, ownerId);
     297             : 
     298           0 :         if (m_MarkerEntityIds[i] == INVALID_ENTITY)
     299             :         {
     300           0 :             LOGERROR("Failed to create rally point marker entity");
     301           0 :             continue;
     302           0 :         }
     303             : 
     304           0 :         CmpPtr<ICmpPosition> markerCmpPosition(GetSimContext(), m_MarkerEntityIds[i]);
     305           0 :         if (markerCmpPosition)
     306             :         {
     307           0 :             if (m_Displayed && IsSet())
     308           0 :                 markerCmpPosition->MoveTo(m_RallyPoints[i].X, m_RallyPoints[i].Y);
     309             :             else
     310           0 :                 markerCmpPosition->MoveOutOfWorld();
     311             :         }
     312             : 
     313           0 :         if (ownerId == INVALID_PLAYER || (ownerId == previousOwner && m_LastMarkerCount >= i))
     314           0 :             continue;
     315             : 
     316           0 :         m_LastOwner = ownerId;
     317             :     }
     318             : 
     319           0 :     m_LastMarkerCount = m_RallyPoints.size() - 1;
     320           0 : }
     321             : 
     322           0 : void CCmpRallyPointRenderer::UpdateLineColor()
     323             : {
     324           0 :     CmpPtr<ICmpOwnership> cmpOwnership(GetEntityHandle());
     325           0 :     if (!cmpOwnership)
     326             :         return;
     327             : 
     328           0 :     player_id_t owner = cmpOwnership->GetOwner();
     329           0 :     if (owner == INVALID_PLAYER)
     330             :         return;
     331             : 
     332           0 :     CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
     333           0 :     if (!cmpPlayerManager)
     334             :         return;
     335             : 
     336           0 :     CmpPtr<ICmpPlayer> cmpPlayer(GetSimContext(), cmpPlayerManager->GetPlayerByID(owner));
     337           0 :     if (!cmpPlayer)
     338             :         return;
     339             : 
     340           0 :     m_LineColor = cmpPlayer->GetDisplayedColor();
     341             : }
     342             : 
     343           0 : void CCmpRallyPointRenderer::RecomputeAllRallyPointPaths()
     344             : {
     345           0 :     m_Path.clear();
     346           0 :     m_VisibilitySegments.clear();
     347           0 :     m_TexturedOverlayLines.clear();
     348             : 
     349           0 :     if (m_EnableDebugNodeOverlay)
     350           0 :         m_DebugNodeOverlays.clear();
     351             : 
     352             :     // No use computing a path if the rally point isn't set
     353           0 :     if (!IsSet())
     354           0 :         return;
     355             : 
     356           0 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     357             :     // No point going on if this entity doesn't have a position or is outside of the world
     358           0 :     if (!cmpPosition || !cmpPosition->IsInWorld())
     359           0 :         return;
     360             : 
     361           0 :     CmpPtr<ICmpFootprint> cmpFootprint(GetEntityHandle());
     362           0 :     CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
     363             : 
     364           0 :     for (size_t i = 0; i < m_RallyPoints.size(); ++i)
     365             :     {
     366           0 :         RecomputeRallyPointPath(i, cmpPosition, cmpFootprint, cmpPathfinder);
     367             :     }
     368             : }
     369             : 
     370           0 : void CCmpRallyPointRenderer::RecomputeRallyPointPath_wrapper(size_t index)
     371             : {
     372             :     // No use computing a path if the rally point isn't set
     373           0 :     if (!IsSet())
     374           0 :         return;
     375             : 
     376             :     // No point going on if this entity doesn't have a position or is outside of the world
     377           0 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     378           0 :     if (!cmpPosition || !cmpPosition->IsInWorld())
     379           0 :         return;
     380             : 
     381           0 :     CmpPtr<ICmpFootprint> cmpFootprint(GetEntityHandle());
     382           0 :     CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
     383             : 
     384           0 :     RecomputeRallyPointPath(index, cmpPosition, cmpFootprint, cmpPathfinder);
     385             : }
     386             : 
     387           0 : void CCmpRallyPointRenderer::RecomputeRallyPointPath(size_t index, CmpPtr<ICmpPosition>& cmpPosition, CmpPtr<ICmpFootprint>& cmpFootprint, CmpPtr<ICmpPathfinder> cmpPathfinder)
     388             : {
     389           0 :     while (index >= m_Path.size())
     390             :     {
     391           0 :         std::vector<CVector2D> tmp;
     392           0 :         m_Path.push_back(tmp);
     393           0 :     }
     394           0 :     m_Path[index].clear();
     395             : 
     396           0 :     while (index >= m_VisibilitySegments.size())
     397             :     {
     398           0 :         std::vector<SVisibilitySegment> tmp;
     399           0 :         m_VisibilitySegments.push_back(tmp);
     400           0 :     }
     401           0 :     m_VisibilitySegments[index].clear();
     402             : 
     403             :     // Find a long path to the goal point -- this uses the tile-based pathfinder, which will return a
     404             :     // list of waypoints (i.e. a Path) from the goal to the foundation/previous rally point, where each
     405             :     // waypoint is centered at a tile. We'll have to do some post-processing on the path to get it smooth.
     406           0 :     WaypointPath path;
     407           0 :     std::vector<Waypoint>& waypoints = path.m_Waypoints;
     408             : 
     409           0 :     CFixedVector2D start(cmpPosition->GetPosition2D());
     410           0 :     PathGoal goal = { PathGoal::POINT, m_RallyPoints[index].X, m_RallyPoints[index].Y };
     411             : 
     412           0 :     if (index == 0)
     413           0 :         GetClosestsEdgePointFrom(start,m_RallyPoints[index], cmpPosition, cmpFootprint);
     414             :     else
     415             :     {
     416           0 :         start.X = m_RallyPoints[index-1].X;
     417           0 :         start.Y = m_RallyPoints[index-1].Y;
     418             :     }
     419           0 :     cmpPathfinder->ComputePathImmediate(start.X, start.Y, goal, cmpPathfinder->GetPassabilityClass(m_LinePassabilityClass), path);
     420             : 
     421             :     // Check if we got a path back; if not we probably have two markers less than one tile apart.
     422           0 :     if (path.m_Waypoints.size() < 2)
     423             :     {
     424           0 :         m_Path[index].emplace_back(start.X.ToFloat(), start.Y.ToFloat());
     425           0 :         m_Path[index].emplace_back(m_RallyPoints[index].X.ToFloat(), m_RallyPoints[index].Y.ToFloat());
     426           0 :         return;
     427             :     }
     428           0 :     else if (index == 0)
     429             :     {
     430             :         // Sometimes this ends up not being optimal if you asked for a long path, so improve.
     431           0 :         CFixedVector2D newend(waypoints[waypoints.size()-2].x,waypoints[waypoints.size()-2].z);
     432           0 :         GetClosestsEdgePointFrom(newend,newend, cmpPosition, cmpFootprint);
     433           0 :         waypoints.back().x = newend.X;
     434           0 :         waypoints.back().z = newend.Y;
     435             :     }
     436             :     else
     437             :     {
     438             :         // Make sure we actually start at the rallypoint because the pathfinder moves us to a usable tile.
     439           0 :         waypoints.back().x = m_RallyPoints[index-1].X;
     440           0 :         waypoints.back().z = m_RallyPoints[index-1].Y;
     441             :     }
     442             : 
     443             :     // Pathfinder makes us go to the nearest passable cell which isn't always what we want
     444           0 :     waypoints[0].x = m_RallyPoints[index].X;
     445           0 :     waypoints[0].z = m_RallyPoints[index].Y;
     446             : 
     447             :     // From here on, we choose to represent the waypoints as CVector2D floats to avoid to have to convert back and forth
     448             :     // between fixed-point Waypoint/CFixedVector2D and various other float-based formats used by interpolation and whatnot.
     449             :     // Since we'll only be further using these points for rendering purposes, using floats should be fine.
     450             : 
     451           0 :     for (Waypoint& waypoint : waypoints)
     452           0 :         m_Path[index].emplace_back(waypoint.x.ToFloat(), waypoint.z.ToFloat());
     453             : 
     454             :     // Post-processing
     455             : 
     456             :     // Linearize the path;
     457             :     // Pass through the waypoints, averaging each waypoint with its next one except the last one. Because the path
     458             :     // goes from the marker to this entity/the previous flag and we want to keep the point at the marker's exact position,
     459             :     // loop backwards through the waypoints so that the marker waypoint is maintained.
     460             :     // TODO: see if we can do this at the same time as the waypoint -> coord conversion above
     461           0 :     for(size_t i = m_Path[index].size() - 2; i > 0; --i)
     462           0 :         m_Path[index][i] = (m_Path[index][i] + m_Path[index][i-1]) / 2.0f;
     463             : 
     464             :     // Eliminate some consecutive waypoints that are visible from eachother. Reduce across a maximum distance of approx. 6 tiles
     465             :     // (prevents segments that are too long to properly stick to the terrain)
     466           0 :     ReduceSegmentsByVisibility(m_Path[index], 6);
     467             : 
     468             :     // Debug overlays
     469           0 :     if (m_EnableDebugNodeOverlay)
     470             :     {
     471           0 :         while (index >= m_DebugNodeOverlays.size())
     472           0 :             m_DebugNodeOverlays.emplace_back();
     473             : 
     474           0 :         m_DebugNodeOverlays[index].clear();
     475             :     }
     476           0 :     if (m_EnableDebugNodeOverlay && m_SmoothPath)
     477             :     {
     478             :         // Create separate control point overlays so we can differentiate when using smoothing (offset them a little higher from the
     479             :         // terrain so we can still see them after the interpolated points are added)
     480           0 :         for (const CVector2D& point : m_Path[index])
     481             :         {
     482           0 :             SOverlayLine overlayLine;
     483           0 :             overlayLine.m_Color = CColor(1.0f, 0.0f, 0.0f, 1.0f);
     484           0 :             overlayLine.m_Thickness = 0.1f;
     485           0 :             SimRender::ConstructSquareOnGround(GetSimContext(), point.X, point.Y, 0.2f, 0.2f, 1.0f, overlayLine, true);
     486           0 :             m_DebugNodeOverlays[index].push_back(overlayLine);
     487           0 :         }
     488             :     }
     489             : 
     490           0 :     if (m_SmoothPath)
     491             :         // The number of points to interpolate goes hand in hand with the maximum amount of node links allowed to be joined together
     492             :         // by the visibility reduction. The more node links that can be joined together, the more interpolated points you need to
     493             :         // generate to be able to deal with local terrain height changes.
     494             :         // no offset, keep line at its exact path
     495           0 :         SimRender::InterpolatePointsRNS(m_Path[index], false, 0, 4);
     496             : 
     497             :     // Find which point is the last visible point before going into the SoD, so we have a point to compare to on the next turn
     498           0 :     GetVisibilitySegments(m_VisibilitySegments[index], index);
     499             : 
     500             :     // Build overlay lines for the new path
     501           0 :     ConstructOverlayLines(index);
     502           0 : }
     503             : 
     504           0 : void CCmpRallyPointRenderer::ConstructAllOverlayLines()
     505             : {
     506           0 :     m_TexturedOverlayLines.clear();
     507             : 
     508           0 :     for (size_t i = 0; i < m_Path.size(); ++i)
     509           0 :         ConstructOverlayLines(i);
     510           0 : }
     511             : 
     512           0 : void CCmpRallyPointRenderer::ConstructOverlayLines(size_t index)
     513             : {
     514             :     // We need to create a new SOverlayTexturedLine every time we want to change the coordinates after having passed it to the
     515             :     // renderer, because it does some fancy vertex buffering thing and caches them internally instead of recomputing them on every
     516             :     // pass (which is only sensible).
     517           0 :     while (index >= m_TexturedOverlayLines.size())
     518             :     {
     519           0 :         std::vector<SOverlayTexturedLine> tmp;
     520           0 :         m_TexturedOverlayLines.push_back(tmp);
     521           0 :     }
     522           0 :     m_TexturedOverlayLines[index].clear();
     523             : 
     524           0 :     if (m_Path[index].size() < 2)
     525             :         return;
     526             : 
     527           0 :     SOverlayTexturedLine::LineCapType dashesLineCapType = SOverlayTexturedLine::LINECAP_ROUND; // line caps to use for the dashed segments (and any other segment's edges that border it)
     528             : 
     529             : 
     530           0 :     for(const SVisibilitySegment& segment : m_VisibilitySegments[index])
     531             :     {
     532           0 :         if (segment.m_Visible)
     533             :         {
     534             :             // Does this segment border on the building or rally point flag on either side?
     535           0 :             bool bordersBuilding = (segment.m_EndIndex == m_Path[index].size() - 1);
     536           0 :             bool bordersFlag = (segment.m_StartIndex == 0);
     537             : 
     538             :             // Construct solid textured overlay line along a subset of the full path points from startPointIdx to endPointIdx
     539           0 :             SOverlayTexturedLine overlayLine;
     540           0 :             overlayLine.m_Thickness = m_LineThickness;
     541           0 :             overlayLine.m_SimContext = &GetSimContext();
     542           0 :             overlayLine.m_TextureBase = m_Texture;
     543           0 :             overlayLine.m_TextureMask = m_TextureMask;
     544           0 :             overlayLine.m_Color = m_LineColor;
     545           0 :             overlayLine.m_Closed = false;
     546             :             // We should take care to only use m_LineXCap for the actual end points at the building and the rally point; any intermediate
     547             :             // end points (i.e., that border a dashed segment) should have the dashed cap
     548             :             // the path line is actually in reverse order as well, so let's swap out the start and end caps
     549           0 :             overlayLine.m_StartCapType = (bordersFlag ? m_LineEndCapType : dashesLineCapType);
     550           0 :             overlayLine.m_EndCapType = (bordersBuilding ? m_LineStartCapType : dashesLineCapType);
     551           0 :             overlayLine.m_AlwaysVisible = true;
     552             : 
     553             :             // Push overlay line coordinates
     554           0 :             ENSURE(segment.m_EndIndex > segment.m_StartIndex);
     555             :             // End index is inclusive here
     556           0 :             for (size_t j = segment.m_StartIndex; j <= segment.m_EndIndex; ++j)
     557           0 :                 overlayLine.m_Coords.push_back(m_Path[index][j]);
     558             : 
     559           0 :             m_TexturedOverlayLines[index].push_back(overlayLine);
     560           0 :         }
     561             :         else
     562             :         {
     563             :             // Construct dashed line from startPointIdx to endPointIdx; add textured overlay lines for it to the render list
     564           0 :             std::vector<CVector2D> straightLine;
     565           0 :             straightLine.push_back(m_Path[index][segment.m_StartIndex]);
     566           0 :             straightLine.push_back(m_Path[index][segment.m_EndIndex]);
     567             : 
     568             :             // We always want to the dashed line to end at either point with a full dash (i.e. not a cleared space), so that the dashed
     569             :             // area is visually obvious. This requires some calculations to see what size we should make the dashes and clears for them
     570             :             // to fit exactly.
     571             : 
     572           0 :             float maxDashSize = 3.f;
     573           0 :             float maxClearSize = 3.f;
     574             : 
     575           0 :             float dashSize = maxDashSize;
     576           0 :             float clearSize = maxClearSize;
     577             :             // Ratio of the dash's length to a (dash + clear) pair's length
     578           0 :             float pairDashRatio = dashSize / (dashSize + clearSize);
     579             : 
     580             :             // Straight-line distance between the points
     581           0 :             float distance = (m_Path[index][segment.m_StartIndex] - m_Path[index][segment.m_EndIndex]).Length();
     582             : 
     583             :             // See how many pairs (dash + clear) of unmodified size can fit into the distance. Then check the remaining distance; if it's not exactly
     584             :             // a dash size's worth (which it probably won't be), then adjust the dash/clear sizes slightly so that it is.
     585           0 :             int numFitUnmodified = floor(distance/(dashSize + clearSize));
     586           0 :             float remainderDistance = distance - (numFitUnmodified * (dashSize + clearSize));
     587             : 
     588             :             // Now we want to make remainderDistance equal exactly one dash size (i.e. maxDashSize) by scaling dashSize and clearSize slightly.
     589             :             // We have (remainderDistance - maxDashSize) of space to distribute over numFitUnmodified instances of (dashSize + clearSize) to make
     590             :             // it fit, so each (dashSize + clearSize) pair needs to adjust its length by (remainderDistance - maxDashSize)/numFitUnmodified
     591             :             // (which will be positive or negative accordingly). This number can then be distributed further proportionally among the dash's
     592             :             // length and the clear's length.
     593             : 
     594             :             // We always want to have at least one dash/clear pair (i.e., "|===|   |===|"); also, we need to avoid division by zero below.
     595           0 :             numFitUnmodified = std::max(1, numFitUnmodified);
     596             : 
     597             :             // Can be either positive or negative
     598           0 :             float pairwiseLengthDifference = (remainderDistance - maxDashSize)/numFitUnmodified;
     599           0 :             dashSize += pairDashRatio * pairwiseLengthDifference;
     600           0 :             clearSize += (1 - pairDashRatio) * pairwiseLengthDifference;
     601             : 
     602             :             // ------------------------------------------------------------------------------------------------
     603             : 
     604           0 :             SDashedLine dashedLine;
     605           0 :             SimRender::ConstructDashedLine(straightLine, dashedLine, dashSize, clearSize);
     606             : 
     607             :             // Build overlay lines for dashes
     608           0 :             size_t numDashes = dashedLine.m_StartIndices.size();
     609           0 :             for (size_t i=0; i < numDashes; i++)
     610             :             {
     611           0 :                 SOverlayTexturedLine dashOverlay;
     612             : 
     613           0 :                 dashOverlay.m_Thickness = m_LineThickness;
     614           0 :                 dashOverlay.m_SimContext = &GetSimContext();
     615           0 :                 dashOverlay.m_TextureBase = m_Texture;
     616           0 :                 dashOverlay.m_TextureMask = m_TextureMask;
     617           0 :                 dashOverlay.m_Color = m_LineDashColor;
     618           0 :                 dashOverlay.m_Closed = false;
     619           0 :                 dashOverlay.m_StartCapType = dashesLineCapType;
     620           0 :                 dashOverlay.m_EndCapType = dashesLineCapType;
     621           0 :                 dashOverlay.m_AlwaysVisible = true;
     622             :                 // TODO: maybe adjust the elevation of the dashes to be a little lower, so that it slides underneath the actual path
     623             : 
     624           0 :                 size_t dashStartIndex = dashedLine.m_StartIndices[i];
     625           0 :                 size_t dashEndIndex = dashedLine.GetEndIndex(i);
     626           0 :                 ENSURE(dashEndIndex > dashStartIndex);
     627             : 
     628           0 :                 for (size_t j = dashStartIndex; j < dashEndIndex; ++j)
     629           0 :                     dashOverlay.m_Coords.push_back(dashedLine.m_Points[j]);
     630             : 
     631           0 :                 m_TexturedOverlayLines[index].push_back(dashOverlay);
     632           0 :             }
     633             : 
     634           0 :         }
     635             :     }
     636             : 
     637             :     //// <DEBUG> //////////////////////////////////////////////
     638           0 :     if (m_EnableDebugNodeOverlay)
     639             :     {
     640           0 :         while (index >= m_DebugNodeOverlays.size())
     641             :         {
     642           0 :             std::vector<SOverlayLine> tmp;
     643           0 :             m_DebugNodeOverlays.push_back(tmp);
     644           0 :         }
     645           0 :         for (size_t j = 0; j < m_Path[index].size(); ++j)
     646             :         {
     647           0 :             SOverlayLine overlayLine;
     648           0 :             overlayLine.m_Color = CColor(1.0f, 1.0f, 1.0f, 1.0f);
     649           0 :             overlayLine.m_Thickness = 1;
     650           0 :             SimRender::ConstructCircleOnGround(GetSimContext(), m_Path[index][j].X, m_Path[index][j].Y, 0.075f, overlayLine, true);
     651           0 :             m_DebugNodeOverlays[index].push_back(overlayLine);
     652           0 :         }
     653             :     }
     654             :     //// </DEBUG> //////////////////////////////////////////////
     655             : }
     656             : 
     657           0 : void CCmpRallyPointRenderer::UpdateOverlayLines()
     658             : {
     659             :     // We should only do this if the rally point is currently being displayed and set inside the world, otherwise it's a massive
     660             :     // waste of time to calculate all this stuff (this method is called every turn)
     661           0 :     if (!m_Displayed || !IsSet())
     662           0 :         return;
     663             : 
     664             :     // See if there have been any changes to the SoD by grabbing the visibility edge points and comparing them to the previous ones
     665           0 :     std::vector<std::vector<SVisibilitySegment> > newVisibilitySegments;
     666           0 :     for (size_t i = 0; i < m_Path.size(); ++i)
     667             :     {
     668           0 :         std::vector<SVisibilitySegment> tmp;
     669           0 :         newVisibilitySegments.push_back(tmp);
     670           0 :         GetVisibilitySegments(newVisibilitySegments[i], i);
     671           0 :     }
     672             : 
     673             :     // Check if the full path changed, then reconstruct all overlay lines, otherwise check if a segment changed and update that.
     674           0 :     if (m_VisibilitySegments.size() != newVisibilitySegments.size())
     675             :     {
     676             :         // Save the new visibility segments to compare against next time
     677           0 :         m_VisibilitySegments = newVisibilitySegments;
     678           0 :         ConstructAllOverlayLines();
     679             :     }
     680             :     else
     681             :     {
     682           0 :         for (size_t i = 0; i < m_VisibilitySegments.size(); ++i)
     683             :         {
     684           0 :             if (m_VisibilitySegments[i] != newVisibilitySegments[i])
     685             :             {
     686             :                 // The visibility segments have changed, reconstruct the overlay lines to match. NOTE: The path itself doesn't
     687             :                 // change, only the overlay lines we construct from it.
     688             :                 // Save the new visibility segments to compare against next time
     689           0 :                 m_VisibilitySegments[i] = newVisibilitySegments[i];
     690           0 :                 ConstructOverlayLines(i);
     691             :             }
     692             :         }
     693             :     }
     694           0 : }
     695             : 
     696           0 : void CCmpRallyPointRenderer::GetClosestsEdgePointFrom(CFixedVector2D& result, CFixedVector2D& start, CmpPtr<ICmpPosition> cmpPosition, CmpPtr<ICmpFootprint> cmpFootprint) const
     697             : {
     698           0 :     ENSURE(cmpPosition);
     699           0 :     ENSURE(cmpFootprint);
     700             : 
     701             :     // Grab the shape and dimensions of the footprint
     702           0 :     entity_pos_t footprintSize0, footprintSize1, footprintHeight;
     703           0 :     ICmpFootprint::EShape footprintShape;
     704           0 :     cmpFootprint->GetShape(footprintShape, footprintSize0, footprintSize1, footprintHeight);
     705             : 
     706             :     // Grab the center of the footprint
     707           0 :     CFixedVector2D center = cmpPosition->GetPosition2D();
     708             : 
     709           0 :     switch (footprintShape)
     710             :     {
     711           0 :         case ICmpFootprint::SQUARE:
     712           0 :         {
     713             :             // In this case, footprintSize0 and 1 indicate the size along the X and Z axes, respectively.
     714             :             // The building's footprint could be rotated any which way, so let's get the rotation around the Y axis
     715             :             // and the rotated unit vectors in the X/Z plane of the shape's footprint
     716             :             // (the Footprint itself holds only the outline, the Position holds the orientation)
     717             : 
     718             :             // Sinus and cosinus of the Y axis rotation angle (aka the yaw)
     719           0 :             fixed s, c;
     720           0 :             fixed a = cmpPosition->GetRotation().Y;
     721           0 :             sincos_approx(a, s, c);
     722             :             // Unit vector along the rotated X axis
     723           0 :             CFixedVector2D u(c, -s);
     724             :             // Unit vector along the rotated Z axis
     725           0 :             CFixedVector2D v(s, c);
     726           0 :             CFixedVector2D halfSize(footprintSize0 / 2, footprintSize1 / 2);
     727             : 
     728           0 :             CFixedVector2D footprintEdgePoint = Geometry::NearestPointOnSquare(start - center, u, v, halfSize);
     729           0 :             result = center + footprintEdgePoint;
     730           0 :             break;
     731             :         }
     732           0 :         case ICmpFootprint::CIRCLE:
     733           0 :         {
     734             :             // In this case, both footprintSize0 and 1 indicate the circle's radius
     735             :             // Transform target to the point nearest on the edge.
     736           0 :             CFixedVector2D centerVec2D(center.X, center.Y);
     737           0 :             CFixedVector2D centerToLast(start - centerVec2D);
     738           0 :             centerToLast.Normalize();
     739           0 :             result = centerVec2D + (centerToLast.Multiply(footprintSize0));
     740           0 :             break;
     741             :         }
     742             :     }
     743           0 : }
     744             : 
     745           0 : void CCmpRallyPointRenderer::ReduceSegmentsByVisibility(std::vector<CVector2D>& coords, unsigned maxSegmentLinks, bool floating) const
     746             : {
     747           0 :     CmpPtr<ICmpPathfinder> cmpPathFinder(GetSystemEntity());
     748           0 :     CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
     749           0 :     CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
     750           0 :     ENSURE(cmpPathFinder && cmpTerrain && cmpWaterManager);
     751             : 
     752           0 :     if (coords.size() < 3)
     753           0 :         return;
     754             : 
     755             :     // The basic idea is this: starting from a base node, keep checking each individual point along the path to see if there's a visible
     756             :     // line between it and the base point. If so, keep going, otherwise, make the last visible point the new base node and start the same
     757             :     // process from there on until the entire line is checked. The output is the array of base nodes.
     758             : 
     759           0 :     std::vector<CVector2D> newCoords;
     760           0 :     StationaryOnlyObstructionFilter obstructionFilter;
     761           0 :     entity_pos_t lineRadius = fixed::FromFloat(m_LineThickness);
     762           0 :     pass_class_t passabilityClass = cmpPathFinder->GetPassabilityClass(m_LinePassabilityClass);
     763             : 
     764             :     // Save the first base node
     765           0 :     newCoords.push_back(coords[0]);
     766             : 
     767           0 :     size_t baseNodeIdx = 0;
     768           0 :     size_t curNodeIdx = 1;
     769             : 
     770           0 :     float baseNodeY;
     771           0 :     entity_pos_t baseNodeX;
     772           0 :     entity_pos_t baseNodeZ;
     773             : 
     774             :     // Set initial base node coords
     775           0 :     baseNodeX = fixed::FromFloat(coords[baseNodeIdx].X);
     776           0 :     baseNodeZ = fixed::FromFloat(coords[baseNodeIdx].Y);
     777           0 :     baseNodeY = cmpTerrain->GetExactGroundLevel(coords[baseNodeIdx].X, coords[baseNodeIdx].Y);
     778           0 :     if (floating)
     779           0 :         baseNodeY = std::max(baseNodeY, cmpWaterManager->GetExactWaterLevel(coords[baseNodeIdx].X, coords[baseNodeIdx].Y));
     780             : 
     781           0 :     while (curNodeIdx < coords.size())
     782             :     {
     783             :         // This needs to be true at all times, otherwise we're checking visibility between a point and itself.
     784           0 :         ENSURE(curNodeIdx > baseNodeIdx);
     785             : 
     786           0 :         entity_pos_t curNodeX = fixed::FromFloat(coords[curNodeIdx].X);
     787           0 :         entity_pos_t curNodeZ = fixed::FromFloat(coords[curNodeIdx].Y);
     788           0 :         float curNodeY = cmpTerrain->GetExactGroundLevel(coords[curNodeIdx].X, coords[curNodeIdx].Y);
     789           0 :         if (floating)
     790           0 :             curNodeY = std::max(curNodeY, cmpWaterManager->GetExactWaterLevel(coords[curNodeIdx].X, coords[curNodeIdx].Y));
     791             : 
     792             :         // Find out whether curNode is visible from baseNode (careful; this is in 2D only; terrain height differences are ignored!)
     793           0 :         bool curNodeVisible = cmpPathFinder->CheckMovement(obstructionFilter, baseNodeX, baseNodeZ, curNodeX, curNodeZ, lineRadius, passabilityClass);
     794             : 
     795             :         // Since height differences are ignored by CheckMovement, let's call two points visible from one another only if they're at
     796             :         // roughly the same terrain elevation
     797             :         // TODO: this could probably use some tuning
     798           0 :         curNodeVisible = curNodeVisible && (fabsf(curNodeY - baseNodeY) < 3.f);
     799           0 :         if (maxSegmentLinks > 0)
     800             :             // Max. amount of node-to-node links to be eliminated (unsigned subtraction is valid because curNodeIdx is always > baseNodeIdx)
     801           0 :             curNodeVisible = curNodeVisible && ((curNodeIdx - baseNodeIdx) <= maxSegmentLinks);
     802             : 
     803           0 :         if (!curNodeVisible)
     804             :         {
     805             :             // Current node is not visible from the base node, so the previous one was the last visible point from baseNode and should
     806             :             // hence become the new base node for further iterations.
     807             : 
     808             :             // If curNodeIdx is adjacent to the current baseNode (which is possible due to steep height differences, e.g. hills), then
     809             :             // we should take care not to stay stuck at the current base node
     810           0 :             if (curNodeIdx > baseNodeIdx + 1)
     811             :             {
     812           0 :                 baseNodeIdx = curNodeIdx - 1;
     813             :             }
     814             :             else
     815             :             {
     816             :                 // curNodeIdx == baseNodeIdx + 1
     817           0 :                 baseNodeIdx = curNodeIdx;
     818             :                 // Move the next candidate node one forward so that we don't test a point against itself in the next iteration
     819           0 :                 ++curNodeIdx;
     820             :             }
     821             : 
     822             :             // Add new base node to output list
     823           0 :             newCoords.push_back(coords[baseNodeIdx]);
     824             : 
     825             :             // Update base node coordinates
     826           0 :             baseNodeX = fixed::FromFloat(coords[baseNodeIdx].X);
     827           0 :             baseNodeZ = fixed::FromFloat(coords[baseNodeIdx].Y);
     828           0 :             baseNodeY = cmpTerrain->GetExactGroundLevel(coords[baseNodeIdx].X, coords[baseNodeIdx].Y);
     829           0 :             if (floating)
     830           0 :                 baseNodeY = std::max(baseNodeY, cmpWaterManager->GetExactWaterLevel(coords[baseNodeIdx].X, coords[baseNodeIdx].Y));
     831             :         }
     832             : 
     833           0 :         ++curNodeIdx;
     834             :     }
     835             : 
     836             :     // We always need to add the last point back to the array; if e.g. all the points up to the last one are all visible from the current
     837             :     // base node, then the loop above just ends and no endpoint is ever added to the list.
     838           0 :     ENSURE(curNodeIdx == coords.size());
     839           0 :     newCoords.push_back(coords[coords.size() - 1]);
     840             : 
     841           0 :     coords.swap(newCoords);
     842             : }
     843             : 
     844           0 : void CCmpRallyPointRenderer::GetVisibilitySegments(std::vector<SVisibilitySegment>& out, size_t index) const
     845             : {
     846           0 :     out.clear();
     847             : 
     848           0 :     if (m_Path[index].size() < 2)
     849           0 :         return;
     850             : 
     851           0 :     CmpPtr<ICmpRangeManager> cmpRangeMgr(GetSystemEntity());
     852             : 
     853           0 :     player_id_t currentPlayer = static_cast<player_id_t>(GetSimContext().GetCurrentDisplayedPlayer());
     854           0 :     CLosQuerier losQuerier(cmpRangeMgr->GetLosQuerier(currentPlayer));
     855             : 
     856             :     // Go through the path node list, comparing each node's visibility with the previous one. If it changes, end the current segment and start
     857             :     // a new one at the next point.
     858             : 
     859           0 :     const float cellSize = static_cast<float>(LOS_TILE_SIZE);
     860           0 :     bool lastVisible = losQuerier.IsExplored(
     861           0 :         (fixed::FromFloat(m_Path[index][0].X / cellSize)).ToInt_RoundToNearest(),
     862           0 :         (fixed::FromFloat(m_Path[index][0].Y / cellSize)).ToInt_RoundToNearest()
     863             :     );
     864             :     // Starting node index of the current segment
     865           0 :     size_t curSegmentStartIndex = 0;
     866             : 
     867           0 :     for (size_t k = 1; k < m_Path[index].size(); ++k)
     868             :     {
     869             :         // Grab tile indices for this coord
     870           0 :         int i = (fixed::FromFloat(m_Path[index][k].X / cellSize)).ToInt_RoundToNearest();
     871           0 :         int j = (fixed::FromFloat(m_Path[index][k].Y / cellSize)).ToInt_RoundToNearest();
     872             : 
     873           0 :         bool nodeVisible = losQuerier.IsExplored(i, j);
     874           0 :         if (nodeVisible != lastVisible)
     875             :         {
     876             :             // Visibility changed; write out the segment that was just completed and get ready for the new one
     877           0 :             out.push_back(SVisibilitySegment(lastVisible, curSegmentStartIndex, k - 1));
     878             : 
     879           0 :             curSegmentStartIndex = k - 1;
     880           0 :             lastVisible = nodeVisible;
     881             :         }
     882             : 
     883             :     }
     884             : 
     885             :     // Terminate the last segment
     886           0 :     out.push_back(SVisibilitySegment(lastVisible, curSegmentStartIndex, m_Path[index].size() - 1));
     887             : 
     888           0 :     MergeVisibilitySegments(out);
     889             : }
     890             : 
     891           0 : void CCmpRallyPointRenderer::MergeVisibilitySegments(std::vector<SVisibilitySegment>& segments)
     892             : {
     893             :     // Scan for single-point segments; if they are inbetween two other segments, delete them and merge the surrounding segments.
     894             :     // If they're at either end of the path, include them in their bordering segment (but only if those bordering segments aren't
     895             :     // themselves single-point segments, because then we would want those to get absorbed by its surrounding ones first).
     896             : 
     897             :     // First scan for absorptions of single-point surrounded segments (i.e. excluding edge segments)
     898           0 :     size_t numSegments = segments.size();
     899             : 
     900             :     // WARNING: FOR LOOP TRICKERY AHEAD!
     901           0 :     for (size_t i = 1; i < numSegments - 1;)
     902             :     {
     903           0 :         SVisibilitySegment& segment = segments[i];
     904           0 :         if (segment.IsSinglePoint())
     905             :         {
     906             :             // Since the segments' visibility alternates, the surrounding ones should have the same visibility
     907           0 :             ENSURE(segments[i-1].m_Visible == segments[i+1].m_Visible);
     908             : 
     909             :             // Make previous segment span all the way across to the next
     910           0 :             segments[i-1].m_EndIndex = segments[i+1].m_EndIndex;
     911             :             // Erase this segment
     912           0 :             segments.erase(segments.begin() + i);
     913             :             // And the next (we removed [i], so [i+1] is now at position [i])
     914           0 :             segments.erase(segments.begin() + i);
     915             :             // We removed 2 segments, so update the loop condition
     916           0 :             numSegments -= 2;
     917             :             // In the next iteration, i should still point to the segment right after the one that got expanded, which is now
     918             :             // at position i; so don't increment i here
     919             :         }
     920             :         else
     921             :         {
     922           0 :             ++i;
     923             :         }
     924             :     }
     925             : 
     926           0 :     ENSURE(numSegments == segments.size());
     927             : 
     928             :     // Check to see if the first segment needs to be merged with its neighbour
     929           0 :     if (segments.size() >= 2 && segments[0].IsSinglePoint())
     930             :     {
     931           0 :         int firstSegmentStartIndex = segments.front().m_StartIndex;
     932           0 :         ENSURE(firstSegmentStartIndex == 0);
     933             :         // At this point, the second segment should never be a single-point segment
     934           0 :         ENSURE(!segments[1].IsSinglePoint());
     935             : 
     936           0 :         segments.erase(segments.begin());
     937           0 :         segments.front().m_StartIndex = firstSegmentStartIndex;
     938             :     }
     939             : 
     940             :     // check to see if the last segment needs to be merged with its neighbour
     941           0 :     if (segments.size() >= 2 && segments[segments.size()-1].IsSinglePoint())
     942             :     {
     943           0 :         int lastSegmentEndIndex = segments.back().m_EndIndex;
     944             :         // At this point, the second-to-last segment should never be a single-point segment
     945           0 :         ENSURE(!segments[segments.size()-2].IsSinglePoint());
     946             : 
     947           0 :         segments.pop_back();
     948           0 :         segments.back().m_EndIndex = lastSegmentEndIndex;
     949             :     }
     950             : 
     951             :     // --------------------------------------------------------------------------------------------------------
     952             :     // At this point, every segment should have at least 2 points
     953           0 :     for (size_t i = 0; i < segments.size(); ++i)
     954             :     {
     955           0 :         ENSURE(!segments[i].IsSinglePoint());
     956           0 :         ENSURE(segments[i].m_EndIndex > segments[i].m_StartIndex);
     957             :     }
     958           0 : }
     959             : 
     960           0 : void CCmpRallyPointRenderer::RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling)
     961             : {
     962             :     // We only get here if the rally point is set and should be displayed
     963           0 :     for(std::vector<SOverlayTexturedLine>& row : m_TexturedOverlayLines)
     964           0 :         for (SOverlayTexturedLine& col : row) {
     965           0 :             if (col.m_Coords.empty())
     966           0 :                 continue;
     967           0 :             if (culling && !col.IsVisibleInFrustum(frustum))
     968           0 :                 continue;
     969           0 :             collector.Submit(&col);
     970             :         }
     971             : 
     972           0 :     if (m_EnableDebugNodeOverlay && !m_DebugNodeOverlays.empty())
     973             :     {
     974           0 :         for (std::vector<SOverlayLine>& row : m_DebugNodeOverlays)
     975           0 :             for (SOverlayLine& col : row)
     976           0 :                 if (!col.m_Coords.empty())
     977           0 :                     collector.Submit(&col);
     978             :     }
     979           0 : }
     980             : 
     981           0 : void CCmpRallyPointRenderer::AddPosition_wrapper(const CFixedVector2D& pos)
     982             : {
     983           0 :     AddPosition(pos, false);
     984           0 : }
     985             : 
     986           0 : void CCmpRallyPointRenderer::SetPosition(const CFixedVector2D& pos)
     987             : {
     988           0 :     if (!(m_RallyPoints.size() == 1 && m_RallyPoints.front() == pos))
     989             :     {
     990           0 :         m_RallyPoints.clear();
     991           0 :         AddPosition(pos, true);
     992             :         // Don't need to UpdateMessageSubscriptions here since AddPosition already calls it
     993             :     }
     994           0 : }
     995             : 
     996           0 : void CCmpRallyPointRenderer::UpdatePosition(std::uint32_t rallyPointId, const CFixedVector2D& pos)
     997             : {
     998           0 :     if (rallyPointId >= m_RallyPoints.size())
     999             :         return;
    1000             : 
    1001           0 :     m_RallyPoints[rallyPointId] = pos;
    1002             : 
    1003           0 :     UpdateMarkers();
    1004             : 
    1005             :     // Compute a new path for the current, and if existing the next rally point
    1006           0 :     RecomputeRallyPointPath_wrapper(rallyPointId);
    1007           0 :     if (rallyPointId + 1 < m_RallyPoints.size())
    1008           0 :         RecomputeRallyPointPath_wrapper(rallyPointId + 1);
    1009             : }
    1010             : 
    1011           0 : void CCmpRallyPointRenderer::SetDisplayed(bool displayed)
    1012             : {
    1013           0 :     if (m_Displayed != displayed)
    1014             :     {
    1015           0 :         m_Displayed = displayed;
    1016             : 
    1017             :         // Set color after all dependent components are deserialized
    1018           0 :         if (displayed && m_LineColor.r < 0)
    1019             :         {
    1020           0 :             UpdateLineColor();
    1021           0 :             ConstructAllOverlayLines();
    1022             :         }
    1023             : 
    1024             :         // Move the markers out of oblivion and back into the real world, or vice-versa
    1025           0 :         UpdateMarkers();
    1026             : 
    1027             :         // Check for changes to the SoD and update the overlay lines accordingly. We need to do this here because this method
    1028             :         // only takes effect when the display flag is active; we need to pick up changes to the SoD that might have occurred
    1029             :         // while this rally point was not being displayed.
    1030           0 :         UpdateOverlayLines();
    1031             : 
    1032           0 :         UpdateMessageSubscriptions();
    1033             :     }
    1034           0 : }
    1035             : 
    1036           0 : void CCmpRallyPointRenderer::Reset()
    1037             : {
    1038           0 :     for (entity_id_t& componentId : m_MarkerEntityIds)
    1039             :     {
    1040           0 :         if (componentId != INVALID_ENTITY)
    1041             :         {
    1042           0 :             GetSimContext().GetComponentManager().DestroyComponentsSoon(componentId);
    1043           0 :             componentId = INVALID_ENTITY;
    1044             :         }
    1045             :     }
    1046           0 :     m_RallyPoints.clear();
    1047           0 :     m_MarkerEntityIds.clear();
    1048           0 :     m_LastOwner = INVALID_PLAYER;
    1049           0 :     m_LastMarkerCount = 0;
    1050           0 :     RecomputeAllRallyPointPaths();
    1051           0 :     UpdateMessageSubscriptions();
    1052           0 : }
    1053             : 
    1054           0 : void CCmpRallyPointRenderer::UpdateColor()
    1055             : {
    1056           0 :     UpdateLineColor();
    1057           0 :     ConstructAllOverlayLines();
    1058           0 : }
    1059             : 
    1060           0 : void CCmpRallyPointRenderer::AddPosition(CFixedVector2D pos, bool recompute)
    1061             : {
    1062           0 :     m_RallyPoints.push_back(pos);
    1063           0 :     UpdateMarkers();
    1064             : 
    1065           0 :     if (recompute)
    1066           0 :         RecomputeAllRallyPointPaths();
    1067             :     else
    1068           0 :         RecomputeRallyPointPath_wrapper(m_RallyPoints.size() - 1);
    1069             : 
    1070           0 :     UpdateMessageSubscriptions();
    1071           0 : }
    1072             : 
    1073           0 : bool CCmpRallyPointRenderer::IsSet() const
    1074             : {
    1075           0 :     return !m_RallyPoints.empty();
    1076             : }

Generated by: LCOV version 1.16