LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpSelectable.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 71 284 25.0 %
Date: 2026-12-02 01:21:50 Functions: 12 23 52.2 %

          Line data    Source code
       1             : /* Copyright (C) 2026 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 "ICmpSelectable.h"
      21             : 
      22             : #include "graphics/Color.h"
      23             : #include "graphics/Overlay.h"
      24             : #include "graphics/Terrain.h"
      25             : #include "graphics/TextureManager.h"
      26             : #include "lib/code_generation.h"
      27             : #include "lib/debug.h"
      28             : #include "lib/path.h"
      29             : #include "maths/BoundingBoxAligned.h"
      30             : #include "maths/Ease.h"
      31             : #include "maths/Frustum.h"
      32             : #include "maths/Vector2D.h"
      33             : #include "maths/Vector3D.h"
      34             : #include "ps/CLogger.h"
      35             : #include "ps/CStrIntern.h"
      36             : #include "ps/Profile.h"
      37             : #include "renderer/Renderer.h"
      38             : #include "renderer/Scene.h"
      39             : #include "renderer/backend/Sampler.h"
      40             : #include "simulation2/MessageTypes.h"
      41             : #include "simulation2/components/ICmpFootprint.h"
      42             : #include "simulation2/components/ICmpOwnership.h"
      43             : #include "simulation2/components/ICmpPlayer.h"
      44             : #include "simulation2/components/ICmpPlayerManager.h"
      45             : #include "simulation2/components/ICmpPosition.h"
      46             : #include "simulation2/components/ICmpTerrain.h"
      47             : #include "simulation2/components/ICmpVisual.h"
      48             : #include "simulation2/components/ICmpWaterManager.h"
      49             : #include "simulation2/helpers/Player.h"
      50             : #include "simulation2/helpers/Position.h"
      51             : #include "simulation2/helpers/Render.h"
      52             : #include "simulation2/system/Component.h"
      53             : #include "simulation2/system/Message.h"
      54             : 
      55             : #include <algorithm>
      56             : #include <cmath>
      57             : #include <cstddef>
      58             : #include <string>
      59             : #include <vector>
      60             : 
      61             : // Minimum alpha value for always visible overlays [0 fully transparent, 1 fully opaque]
      62             : static const float MIN_ALPHA_ALWAYS_VISIBLE = 0.65f;
      63             : // Minimum alpha value for other overlays
      64             : static const float MIN_ALPHA_UNSELECTED = 0.0f;
      65             : // Desaturation value for unselected, always visible overlays (0.33 = 33% desaturated or 66% of original saturation)
      66             : static const float RGB_DESATURATION = 0.333333f;
      67             : 
      68             : class CCmpSelectable final : public ICmpSelectable
      69             : {
      70             : public:
      71             :     enum EShape
      72             :     {
      73             :         FOOTPRINT,
      74             :         CIRCLE,
      75             :         SQUARE
      76             :     };
      77             : 
      78         137 :     static void ClassInit(CComponentManager& componentManager)
      79             :     {
      80         137 :         componentManager.SubscribeToMessageType(MT_OwnershipChanged);
      81         137 :         componentManager.SubscribeToMessageType(MT_PlayerColorChanged);
      82         137 :         componentManager.SubscribeToMessageType(MT_PositionChanged);
      83         137 :         componentManager.SubscribeToMessageType(MT_TerrainChanged);
      84         137 :         componentManager.SubscribeToMessageType(MT_WaterChanged);
      85         137 :     }
      86             : 
      87         372 :     DEFAULT_COMPONENT_ALLOCATOR(Selectable)
      88             : 
      89         186 :     CCmpSelectable()
      90         372 :         : m_DebugBoundingBoxOverlay(NULL), m_DebugSelectionBoxOverlay(NULL),
      91         186 :           m_BuildingOverlay(NULL), m_UnitOverlay(NULL),
      92         186 :           m_FadeBaselineAlpha(0.f), m_FadeDeltaAlpha(0.f), m_FadeProgress(0.f),
      93         372 :           m_Selected(false), m_Cached(false), m_Visible(false)
      94             :     {
      95         186 :         m_Color = CColor(0, 0, 0, m_FadeBaselineAlpha);
      96         186 :     }
      97             : 
      98         372 :     ~CCmpSelectable()
      99         186 :     {
     100         186 :         delete m_DebugBoundingBoxOverlay;
     101         186 :         delete m_DebugSelectionBoxOverlay;
     102         186 :         delete m_BuildingOverlay;
     103         186 :         delete m_UnitOverlay;
     104         372 :     }
     105             : 
     106         137 :     static std::string GetSchema()
     107             :     {
     108         137 :         return
     109             :             "<a:help>Allows this entity to be selected by the player.</a:help>"
     110             :             "<a:example/>"
     111             :             "<optional>"
     112             :                 "<element name='EditorOnly' a:help='If this element is present, the entity is only selectable in Atlas'>"
     113             :                     "<empty/>"
     114             :                 "</element>"
     115             :             "</optional>"
     116             :             "<element name='Overlay' a:help='Specifies the type of overlay to be displayed when this entity is selected.'>"
     117             :                 "<interleave>"
     118             :                     "<optional>"
     119             :                         "<element name='Shape' a:help='Specifies shape of overlay. If not specified, footprint shape will be used.'>"
     120             :                             "<choice>"
     121             :                                 "<element name='Square' a:help='Set the overlay to a square of the given size'>"
     122             :                                     "<attribute name='width' a:help='Size of the overlay along the left/right direction (in meters)'>"
     123             :                                         "<data type='decimal'>"
     124             :                                             "<param name='minExclusive'>0.0</param>"
     125             :                                         "</data>"
     126             :                                     "</attribute>"
     127             :                                     "<attribute name='depth' a:help='Size of the overlay along the front/back direction (in meters)'>"
     128             :                                         "<data type='decimal'>"
     129             :                                             "<param name='minExclusive'>0.0</param>"
     130             :                                         "</data>"
     131             :                                     "</attribute>"
     132             :                                 "</element>"
     133             :                                 "<element name='Circle' a:help='Set the overlay to a circle of the given size'>"
     134             :                                     "<attribute name='radius' a:help='Radius of the overlay (in meters)'>"
     135             :                                         "<data type='decimal'>"
     136             :                                             "<param name='minExclusive'>0.0</param>"
     137             :                                         "</data>"
     138             :                                     "</attribute>"
     139             :                                 "</element>"
     140             :                             "</choice>"
     141             :                         "</element>"
     142             :                     "</optional>"
     143             :                     "<optional>"
     144             :                         "<element name='AlwaysVisible' a:help='If this element is present, the selection overlay will always be visible (with transparency and desaturation)'>"
     145             :                             "<empty/>"
     146             :                         "</element>"
     147             :                     "</optional>"
     148             :                     "<choice>"
     149             :                         "<element name='Texture' a:help='Displays a texture underneath the entity.'>"
     150             :                             "<element name='MainTexture' a:help='Texture to display underneath the entity. Filepath relative to art/textures/selection/.'><text/></element>"
     151             :                             "<element name='MainTextureMask' a:help='Mask texture that controls where to apply player color. Filepath relative to art/textures/selection/.'><text/></element>"
     152             :                         "</element>"
     153             :                         "<element name='Outline' a:help='Traces the outline of the entity with a line texture.'>"
     154             :                             "<element name='LineTexture' a:help='Texture to apply to the line. Filepath relative to art/textures/selection/.'><text/></element>"
     155             :                             "<element name='LineTextureMask' a:help='Texture that controls where to apply player color. Filepath relative to art/textures/selection/.'><text/></element>"
     156             :                             "<element name='LineThickness' a:help='Thickness of the line, in world units.'><ref name='positiveDecimal'/></element>"
     157             :                         "</element>"
     158             :                     "</choice>"
     159             :                 "</interleave>"
     160         137 :             "</element>";
     161             :     }
     162             : 
     163             :     EShape m_Shape;
     164             :     entity_pos_t m_Width; // width/radius
     165             :     entity_pos_t m_Height; // height/radius
     166             : 
     167         186 :     void Init(const CParamNode& paramNode) override
     168             :     {
     169         186 :         m_EditorOnly = paramNode.GetChild("EditorOnly").IsOk();
     170             : 
     171             :         // Certain special units always have their selection overlay shown
     172         186 :         m_AlwaysVisible = paramNode.GetChild("Overlay").GetChild("AlwaysVisible").IsOk();
     173         186 :         if (m_AlwaysVisible)
     174             :         {
     175           0 :             m_AlphaMin = MIN_ALPHA_ALWAYS_VISIBLE;
     176           0 :             m_Color.a = m_AlphaMin;
     177             :         }
     178             :         else
     179         186 :             m_AlphaMin = MIN_ALPHA_UNSELECTED;
     180             : 
     181         186 :         const CParamNode& textureNode = paramNode.GetChild("Overlay").GetChild("Texture");
     182         186 :         const CParamNode& outlineNode = paramNode.GetChild("Overlay").GetChild("Outline");
     183             : 
     184             :         // Save some memory by using interned file paths in these descriptors (almost all actors and
     185             :         // entities have this component, and many use the same textures).
     186         186 :         if (textureNode.IsOk())
     187             :         {
     188             :             // textured quad mode (dynamic, for units)
     189         186 :             m_OverlayDescriptor.m_Type = DYNAMIC_QUAD;
     190         186 :             m_OverlayDescriptor.m_QuadTexture = CStrIntern(TEXTUREBASEPATH + textureNode.GetChild("MainTexture").ToString());
     191         372 :             m_OverlayDescriptor.m_QuadTextureMask = CStrIntern(TEXTUREBASEPATH + textureNode.GetChild("MainTextureMask").ToString());
     192             :         }
     193           0 :         else if (outlineNode.IsOk())
     194             :         {
     195             :             // textured outline mode (static, for buildings)
     196           0 :             m_OverlayDescriptor.m_Type = STATIC_OUTLINE;
     197           0 :             m_OverlayDescriptor.m_LineTexture = CStrIntern(TEXTUREBASEPATH + outlineNode.GetChild("LineTexture").ToString());
     198           0 :             m_OverlayDescriptor.m_LineTextureMask = CStrIntern(TEXTUREBASEPATH + outlineNode.GetChild("LineTextureMask").ToString());
     199           0 :             m_OverlayDescriptor.m_LineThickness = outlineNode.GetChild("LineThickness").ToFloat();
     200             :         }
     201             : 
     202         186 :         const CParamNode& shapeNode = paramNode.GetChild("Overlay").GetChild("Shape");
     203         186 :         if (shapeNode.IsOk())
     204             :         {
     205           0 :             if (shapeNode.GetChild("Square").IsOk())
     206             :             {
     207           0 :                 m_Shape = SQUARE;
     208           0 :                 m_Width = shapeNode.GetChild("Square").GetChild("@width").ToFixed();
     209           0 :                 m_Height = shapeNode.GetChild("Square").GetChild("@depth").ToFixed();
     210             :             }
     211           0 :             else if (shapeNode.GetChild("Circle").IsOk())
     212             :             {
     213           0 :                 m_Shape = CIRCLE;
     214           0 :                 m_Width = m_Height = shapeNode.GetChild("Circle").GetChild("@radius").ToFixed();
     215             :             }
     216             :             else
     217             :             {
     218             :                 // Should not happen
     219           0 :                 m_Shape = FOOTPRINT;
     220           0 :                 LOGWARNING("[Selectable] Selected overlay shape is not implemented.");
     221             :             }
     222             :         }
     223             :         else
     224             :         {
     225         186 :             m_Shape = FOOTPRINT;
     226             :         }
     227             : 
     228         186 :         m_EnabledInterpolate = false;
     229         186 :         m_EnabledRenderSubmit = false;
     230         186 :         UpdateMessageSubscriptions();
     231         186 :     }
     232             : 
     233         186 :     void Deinit() override { }
     234             : 
     235        1032 :     void Serialize(ISerializer&) override
     236             :     {
     237             :         // Nothing to do here (the overlay object is not worth saving, it'll get
     238             :         // reconstructed by the GUI soon enough, I think)
     239        1032 :     }
     240             : 
     241           0 :     void Deserialize(const CParamNode& paramNode, IDeserializer&) override
     242             :     {
     243             :         // Need to call Init to reload the template properties
     244           0 :         Init(paramNode);
     245           0 :     }
     246             : 
     247             :     void HandleMessage(const CMessage& msg, bool /*global*/) override;
     248             : 
     249           0 :     void SetSelectionHighlight(const CColor& color, bool selected) override
     250             :     {
     251           0 :         m_Selected = selected;
     252           0 :         m_Color.r = color.r;
     253           0 :         m_Color.g = color.g;
     254           0 :         m_Color.b = color.b;
     255             : 
     256             :         // Always-visible overlays will be desaturated if their parent unit is deselected.
     257           0 :         if (m_AlwaysVisible && !selected)
     258             :         {
     259           0 :             float max;
     260             : 
     261             :             // Reduce saturation by one-third, the quick-and-dirty way.
     262           0 :             if (m_Color.r > m_Color.b)
     263           0 :                 max = (m_Color.r > m_Color.g) ? m_Color.r : m_Color.g;
     264             :             else
     265           0 :                 max = (m_Color.b > m_Color.g) ? m_Color.b : m_Color.g;
     266             : 
     267           0 :             m_Color.r += (max - m_Color.r) * RGB_DESATURATION;
     268           0 :             m_Color.g += (max - m_Color.g) * RGB_DESATURATION;
     269           0 :             m_Color.b += (max - m_Color.b) * RGB_DESATURATION;
     270             :         }
     271             : 
     272           0 :         SetSelectionHighlightAlpha(color.a);
     273           0 :     }
     274             : 
     275           0 :     void SetSelectionHighlightAlpha(float alpha) override
     276             :     {
     277           0 :         alpha = std::max(m_AlphaMin, alpha);
     278             : 
     279             :         // set up fading from the current value (as the baseline) to the target value
     280           0 :         m_FadeBaselineAlpha = m_Color.a;
     281           0 :         m_FadeDeltaAlpha = alpha - m_FadeBaselineAlpha;
     282           0 :         m_FadeProgress = 0.f;
     283             : 
     284           0 :         UpdateMessageSubscriptions();
     285           0 :     }
     286             : 
     287           0 :     void SetVisibility(bool visible) override
     288             :     {
     289           0 :         m_Visible = visible;
     290           0 :         UpdateMessageSubscriptions();
     291           0 :     }
     292             : 
     293           0 :     bool IsEditorOnly() const override
     294             :     {
     295           0 :         return m_EditorOnly;
     296             :     }
     297             : 
     298             :     void RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling);
     299             : 
     300             :     /**
     301             :      * Draw a textured line overlay.
     302             :      */
     303             :     void UpdateTexturedLineOverlay(const SOverlayDescriptor* overlayDescriptor, SOverlayTexturedLine& overlay, float frameOffset);
     304             : 
     305             :     /**
     306             :      * Called from the interpolation handler; responsible for ensuring the dynamic overlay (provided we're
     307             :      * using one) is up-to-date and ready to be submitted to the next rendering run.
     308             :      */
     309             :     void UpdateDynamicOverlay(float frameOffset);
     310             : 
     311             :     /// Explicitly invalidates the static overlay.
     312             :     void InvalidateStaticOverlay();
     313             : 
     314             :     /**
     315             :      * Subscribe/unsubscribe to MT_Interpolate, MT_RenderSubmit, depending on
     316             :      * whether we will do any actual work when receiving them. (This is to avoid
     317             :      * the performance cost of receiving messages in the typical case when the
     318             :      * entity is not selected.)
     319             :      *
     320             :      * Must be called after changing m_Visible, m_FadeDeltaAlpha, m_Color.a
     321             :      */
     322             :     void UpdateMessageSubscriptions();
     323             : 
     324             :     /**
     325             :      * Set the color of the current owner.
     326             :      */
     327             :     void UpdateColor() override;
     328             : 
     329             : private:
     330             :     SOverlayDescriptor m_OverlayDescriptor;
     331             :     SOverlayTexturedLine* m_BuildingOverlay;
     332             :     SOverlayQuad* m_UnitOverlay;
     333             : 
     334             :     CBoundingBoxAligned m_UnitOverlayBoundingBox;
     335             : 
     336             :     SOverlayLine* m_DebugBoundingBoxOverlay;
     337             :     SOverlayLine* m_DebugSelectionBoxOverlay;
     338             : 
     339             :     bool m_EnabledInterpolate;
     340             :     bool m_EnabledRenderSubmit;
     341             : 
     342             :     // Whether the selectable will be rendered.
     343             :     bool m_Visible;
     344             :     // Whether the entity is only selectable in Atlas editor
     345             :     bool m_EditorOnly;
     346             :     // Whether the selection overlay is always visible
     347             :     bool m_AlwaysVisible;
     348             :     /// Whether the parent entity is selected (caches GUI's selection state).
     349             :     bool m_Selected;
     350             :     /// Current selection overlay color. Alpha component is subject to fading.
     351             :     CColor m_Color;
     352             :     /// Whether the selectable's player color has been cached for rendering.
     353             :     bool m_Cached;
     354             :     /// Minimum value for current selection overlay alpha.
     355             :     float m_AlphaMin;
     356             :     /// Baseline alpha value to start fading from. Constant during a single fade.
     357             :     float m_FadeBaselineAlpha;
     358             :     /// Delta between target and baseline alpha. Constant during a single fade. Can be positive or negative.
     359             :     float m_FadeDeltaAlpha;
     360             :     /// Linear time progress of the fade, between 0 and m_FadeDuration.
     361             :     float m_FadeProgress;
     362             : 
     363             :     /// Total duration of a single fade, in seconds. Assumed constant for now; feel free to change this into
     364             :     /// a member variable if you need to adjust it per component.
     365             :     static const float FADE_DURATION;
     366             :     static const char* TEXTUREBASEPATH;
     367             : };
     368             : 
     369             : const float CCmpSelectable::FADE_DURATION = 0.3f;
     370             : const char* CCmpSelectable::TEXTUREBASEPATH = "art/textures/selection/";
     371             : 
     372        8139 : void CCmpSelectable::HandleMessage(const CMessage& msg, bool /*global*/)
     373             : {
     374        8139 :     switch (msg.GetType())
     375             :     {
     376           0 :     case MT_Interpolate:
     377           0 :     {
     378           0 :         PROFILE("Selectable::Interpolate");
     379             : 
     380           0 :         const CMessageInterpolate& msgData = static_cast<const CMessageInterpolate&> (msg);
     381             : 
     382           0 :         if (m_FadeDeltaAlpha != 0.f)
     383             :         {
     384           0 :             m_FadeProgress += msgData.deltaRealTime;
     385           0 :             if (m_FadeProgress >= FADE_DURATION)
     386             :             {
     387           0 :                 const float targetAlpha = m_FadeBaselineAlpha + m_FadeDeltaAlpha;
     388             : 
     389             :                 // stop the fade
     390           0 :                 m_Color.a = targetAlpha;
     391           0 :                 m_FadeBaselineAlpha = targetAlpha;
     392           0 :                 m_FadeDeltaAlpha = 0.f;
     393           0 :                 m_FadeProgress = FADE_DURATION; // will need to be reset to start the next fade again
     394             :             }
     395             :             else
     396             :             {
     397           0 :                 m_Color.a = Ease::QuartOut(m_FadeProgress, m_FadeBaselineAlpha, m_FadeDeltaAlpha, FADE_DURATION);
     398             :             }
     399             :         }
     400             : 
     401             :         // update dynamic overlay only when visible
     402           0 :         if (m_Color.a > 0)
     403           0 :             UpdateDynamicOverlay(msgData.offset);
     404             : 
     405           0 :         UpdateMessageSubscriptions();
     406             : 
     407           0 :         break;
     408           0 :     }
     409         216 :     case MT_OwnershipChanged:
     410         216 :     {
     411         216 :         const CMessageOwnershipChanged& msgData = static_cast<const CMessageOwnershipChanged&> (msg);
     412             : 
     413             :         // Ignore newly constructed entities, as they receive their color upon first selection
     414             :         // Ignore deleted entities because they won't be rendered
     415         216 :         if (msgData.from == INVALID_PLAYER || msgData.to == INVALID_PLAYER)
     416             :             break;
     417             : 
     418           0 :         UpdateColor();
     419           0 :         InvalidateStaticOverlay();
     420           0 :         break;
     421             :     }
     422           0 :     case MT_PlayerColorChanged:
     423           0 :     {
     424           0 :         const CMessagePlayerColorChanged& msgData = static_cast<const CMessagePlayerColorChanged&> (msg);
     425             : 
     426           0 :         CmpPtr<ICmpOwnership> cmpOwnership(GetEntityHandle());
     427           0 :         if (!cmpOwnership || msgData.player != cmpOwnership->GetOwner())
     428             :             break;
     429             : 
     430           0 :         UpdateColor();
     431             :         break;
     432             :     }
     433        7923 :     case MT_PositionChanged:
     434        7923 :     case MT_TerrainChanged:
     435        7923 :     case MT_WaterChanged:
     436        7923 :         InvalidateStaticOverlay();
     437        7923 :         break;
     438           0 :     case MT_RenderSubmit:
     439           0 :     {
     440           0 :         PROFILE("Selectable::RenderSubmit");
     441             : 
     442           0 :         const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
     443           0 :         RenderSubmit(msgData.collector, msgData.frustum, msgData.culling);
     444             : 
     445           0 :         break;
     446           0 :     }
     447             :     }
     448        8139 : }
     449             : 
     450           0 : void CCmpSelectable::UpdateColor()
     451             : {
     452           0 :     CmpPtr<ICmpOwnership> cmpOwnership(GetEntityHandle());
     453             : 
     454           0 :     CmpPtr<ICmpPlayerManager> cmpPlayerManager(GetSystemEntity());
     455           0 :     if (!cmpPlayerManager)
     456           0 :         return;
     457             : 
     458             :     // Default to white if there's no owner (e.g. decorative, editor-only actors)
     459           0 :     CColor color(1.0, 1.0, 1.0, 1.0);
     460             : 
     461           0 :     if (cmpOwnership)
     462             :     {
     463           0 :         CmpPtr<ICmpPlayer> cmpPlayer(GetSimContext(), cmpPlayerManager->GetPlayerByID(cmpOwnership->GetOwner()));
     464           0 :         if (cmpPlayer)
     465           0 :             color = cmpPlayer->GetDisplayedColor();
     466             :     }
     467             : 
     468             :     // Update the highlight color, while keeping the current alpha target value intact
     469             :     // (i.e. baseline + delta), so that any ongoing fades simply continue with the new color.
     470           0 :     color.a = m_FadeBaselineAlpha + m_FadeDeltaAlpha;
     471             : 
     472           0 :     SetSelectionHighlight(color, m_Selected);
     473             : }
     474             : 
     475         186 : void CCmpSelectable::UpdateMessageSubscriptions()
     476             : {
     477         186 :     bool needInterpolate = false;
     478         186 :     bool needRenderSubmit = false;
     479             : 
     480         186 :     if (m_FadeDeltaAlpha != 0.f || m_Color.a > 0)
     481           0 :         needInterpolate = true;
     482             : 
     483         186 :     if (m_Visible && m_Color.a > 0)
     484         186 :         needRenderSubmit = true;
     485             : 
     486         186 :     if (needInterpolate != m_EnabledInterpolate)
     487             :     {
     488           0 :         GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_Interpolate, this, needInterpolate);
     489           0 :         m_EnabledInterpolate = needInterpolate;
     490             :     }
     491             : 
     492         186 :     if (needRenderSubmit != m_EnabledRenderSubmit)
     493             :     {
     494           0 :         GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_RenderSubmit, this, needRenderSubmit);
     495           0 :         m_EnabledRenderSubmit = needRenderSubmit;
     496             :     }
     497         186 : }
     498             : 
     499        7923 : void CCmpSelectable::InvalidateStaticOverlay()
     500             : {
     501        7923 :     SAFE_DELETE(m_BuildingOverlay);
     502        7923 : }
     503             : 
     504           0 : void CCmpSelectable::UpdateTexturedLineOverlay(const SOverlayDescriptor* overlayDescriptor, SOverlayTexturedLine& overlay, float frameOffset)
     505             : {
     506           0 :     if (!CRenderer::IsInitialised())
     507           0 :         return;
     508             : 
     509           0 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     510           0 :     if (!cmpPosition || !cmpPosition->IsInWorld())
     511           0 :         return;
     512             : 
     513           0 :     ICmpFootprint::EShape fpShape = ICmpFootprint::CIRCLE;
     514           0 :     if (m_Shape == FOOTPRINT)
     515             :     {
     516           0 :         CmpPtr<ICmpFootprint> cmpFootprint(GetEntityHandle());
     517           0 :         if (!cmpFootprint)
     518           0 :             return;
     519           0 :         entity_pos_t h;
     520           0 :         cmpFootprint->GetShape(fpShape, m_Width, m_Height, h);
     521             :     }
     522           0 :     float rotY;
     523           0 :     CVector2D origin;
     524           0 :     cmpPosition->GetInterpolatedPosition2D(frameOffset, origin.X, origin.Y, rotY);
     525             : 
     526           0 :     overlay.m_SimContext = &GetSimContext();
     527           0 :     overlay.m_Color = m_Color;
     528           0 :     overlay.CreateOverlayTexture(overlayDescriptor);
     529             : 
     530           0 :     if (m_Shape == SQUARE || (m_Shape == FOOTPRINT && fpShape == ICmpFootprint::SQUARE))
     531           0 :         SimRender::ConstructTexturedLineBox(overlay, origin, cmpPosition->GetRotation(), m_Width.ToFloat(), m_Height.ToFloat());
     532             :     else
     533           0 :         SimRender::ConstructTexturedLineCircle(overlay, origin, m_Width.ToFloat());
     534             : }
     535             : 
     536           0 : void CCmpSelectable::UpdateDynamicOverlay(float frameOffset)
     537             : {
     538             :     // Dynamic overlay lines are allocated once and never deleted. Since they are expected to change frequently,
     539             :     // they are assumed dirty on every call to this function, and we should therefore use this function more
     540             :     // thoughtfully than calling it right before every frame render.
     541             : 
     542           0 :     if (m_OverlayDescriptor.m_Type != DYNAMIC_QUAD)
     543           0 :         return;
     544             : 
     545           0 :     if (!CRenderer::IsInitialised())
     546             :         return;
     547             : 
     548           0 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     549           0 :     if (!cmpPosition || !cmpPosition->IsInWorld())
     550           0 :         return;
     551             : 
     552           0 :     ICmpFootprint::EShape fpShape = ICmpFootprint::CIRCLE;
     553           0 :     if (m_Shape == FOOTPRINT)
     554             :     {
     555           0 :         CmpPtr<ICmpFootprint> cmpFootprint(GetEntityHandle());
     556           0 :         if (!cmpFootprint)
     557           0 :             return;
     558           0 :         entity_pos_t h;
     559           0 :         cmpFootprint->GetShape(fpShape, m_Width, m_Height, h);
     560             :     }
     561             : 
     562           0 :     float rotY;
     563           0 :     CVector2D position;
     564           0 :     cmpPosition->GetInterpolatedPosition2D(frameOffset, position.X, position.Y, rotY);
     565             : 
     566           0 :     CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
     567           0 :     CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
     568           0 :     ENSURE(cmpWaterManager && cmpTerrain);
     569             : 
     570           0 :     CTerrain* terrain = cmpTerrain->GetCTerrain();
     571           0 :     ENSURE(terrain);
     572             : 
     573             :     // ---------------------------------------------------------------------------------
     574             : 
     575           0 :     if (!m_UnitOverlay)
     576             :     {
     577           0 :         m_UnitOverlay = new SOverlayQuad;
     578             : 
     579             :         // Assuming we don't need the capability of swapping textures on-demand.
     580           0 :         CTextureProperties texturePropsBase(m_OverlayDescriptor.m_QuadTexture.c_str());
     581           0 :         texturePropsBase.SetAddressMode(
     582             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_BORDER,
     583             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
     584           0 :         texturePropsBase.SetAnisotropicFilter(true);
     585             : 
     586           0 :         CTextureProperties texturePropsMask(m_OverlayDescriptor.m_QuadTextureMask.c_str());
     587           0 :         texturePropsMask.SetAddressMode(
     588             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_BORDER,
     589             :             Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
     590           0 :         texturePropsMask.SetAnisotropicFilter(true);
     591             : 
     592           0 :         m_UnitOverlay->m_Texture = g_Renderer.GetTextureManager().CreateTexture(texturePropsBase);
     593           0 :         m_UnitOverlay->m_TextureMask = g_Renderer.GetTextureManager().CreateTexture(texturePropsMask);
     594           0 :     }
     595             : 
     596           0 :     m_UnitOverlay->m_Color = m_Color;
     597             : 
     598             :     // TODO: some code duplication here :< would be nice to factor out getting the corner points of an
     599             :     // entity based on its footprint sizes (and regardless of whether it's a circle or a square)
     600             : 
     601           0 :     float s = sinf(-rotY);
     602           0 :     float c = cosf(-rotY);
     603           0 :     CVector2D unitX(c, s);
     604           0 :     CVector2D unitZ(-s, c);
     605             : 
     606           0 :     float halfSizeX = m_Width.ToFloat();
     607           0 :     float halfSizeZ = m_Height.ToFloat();
     608           0 :     if (m_Shape == SQUARE || (m_Shape == FOOTPRINT && fpShape == ICmpFootprint::SQUARE))
     609             :     {
     610           0 :         halfSizeX /= 2.0f;
     611           0 :         halfSizeZ /= 2.0f;
     612             :     }
     613             : 
     614           0 :     std::vector<CVector2D> points;
     615           0 :     points.push_back(CVector2D(position + unitX *(-halfSizeX)   + unitZ *  halfSizeZ));  // top left
     616           0 :     points.push_back(CVector2D(position + unitX *(-halfSizeX)   + unitZ *(-halfSizeZ))); // bottom left
     617           0 :     points.push_back(CVector2D(position + unitX *  halfSizeX    + unitZ *(-halfSizeZ))); // bottom right
     618           0 :     points.push_back(CVector2D(position + unitX *  halfSizeX    + unitZ *  halfSizeZ));  // top right
     619             : 
     620           0 :     m_UnitOverlayBoundingBox = CBoundingBoxAligned();
     621           0 :     for (size_t i = 0; i < 4; ++i)
     622             :     {
     623           0 :         float quadY = std::max(
     624           0 :             terrain->GetExactGroundLevel(points[i].X, points[i].Y),
     625           0 :             cmpWaterManager->GetExactWaterLevel(points[i].X, points[i].Y)
     626           0 :         );
     627             : 
     628           0 :         m_UnitOverlay->m_Corners[i] = CVector3D(points[i].X, quadY, points[i].Y);
     629           0 :         m_UnitOverlayBoundingBox += m_UnitOverlay->m_Corners[i];
     630             :     }
     631             : }
     632             : 
     633           0 : void CCmpSelectable::RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling)
     634             : {
     635           0 :     if (m_Visible && m_Color.a > 0)
     636             :     {
     637           0 :         if (!m_Cached)
     638             :         {
     639           0 :             UpdateColor();
     640           0 :             m_Cached = true;
     641             :         }
     642             : 
     643           0 :         switch (m_OverlayDescriptor.m_Type)
     644             :         {
     645           0 :             case STATIC_OUTLINE:
     646           0 :                 {
     647           0 :                     if (!m_BuildingOverlay)
     648             :                     {
     649             :                         // Static overlays are allocated once and not updated until they are explicitly deleted again
     650             :                         // (see InvalidateStaticOverlay). Since they are expected to change rarely (if ever) during
     651             :                         // normal gameplay, this saves us doing all the work below on each frame.
     652           0 :                         m_BuildingOverlay = new SOverlayTexturedLine;
     653           0 :                         UpdateTexturedLineOverlay(&m_OverlayDescriptor, *m_BuildingOverlay, 0);
     654             :                     }
     655           0 :                     m_BuildingOverlay->m_Color = m_Color; // done separately so alpha changes don't require a full update call
     656           0 :                     if (culling && !m_BuildingOverlay->IsVisibleInFrustum(frustum))
     657             :                         break;
     658           0 :                     collector.Submit(m_BuildingOverlay);
     659             :                 }
     660           0 :                 break;
     661           0 :             case DYNAMIC_QUAD:
     662           0 :                 {
     663           0 :                     if (culling && !frustum.IsBoxVisible(m_UnitOverlayBoundingBox))
     664             :                         break;
     665           0 :                     if (m_UnitOverlay)
     666           0 :                         collector.Submit(m_UnitOverlay);
     667             :                 }
     668             :                 break;
     669             :             default:
     670             :                 break;
     671             :         }
     672             :     }
     673             : 
     674             :     // Render bounding box debug overlays if we have a positive target alpha value. This ensures
     675             :     // that the debug overlays respond immediately to deselection without delay from fading out.
     676           0 :     if (m_FadeBaselineAlpha + m_FadeDeltaAlpha > 0)
     677             :     {
     678           0 :         if (ICmpSelectable::ms_EnableDebugOverlays)
     679             :         {
     680             :             // allocate debug overlays on-demand
     681           0 :             if (!m_DebugBoundingBoxOverlay) m_DebugBoundingBoxOverlay = new SOverlayLine;
     682           0 :             if (!m_DebugSelectionBoxOverlay) m_DebugSelectionBoxOverlay = new SOverlayLine;
     683             : 
     684           0 :             CmpPtr<ICmpVisual> cmpVisual(GetEntityHandle());
     685           0 :             if (cmpVisual)
     686             :             {
     687           0 :                 SimRender::ConstructBoxOutline(cmpVisual->GetBounds(), *m_DebugBoundingBoxOverlay);
     688           0 :                 m_DebugBoundingBoxOverlay->m_Thickness = 0.1f;
     689           0 :                 m_DebugBoundingBoxOverlay->m_Color = CColor(1.f, 0.f, 0.f, 1.f);
     690             : 
     691           0 :                 SimRender::ConstructBoxOutline(cmpVisual->GetSelectionBox(), *m_DebugSelectionBoxOverlay);
     692           0 :                 m_DebugSelectionBoxOverlay->m_Thickness = 0.1f;
     693           0 :                 m_DebugSelectionBoxOverlay->m_Color = CColor(0.f, 1.f, 0.f, 1.f);
     694             : 
     695           0 :                 collector.Submit(m_DebugBoundingBoxOverlay);
     696           0 :                 collector.Submit(m_DebugSelectionBoxOverlay);
     697             :             }
     698             :         }
     699             :         else
     700             :         {
     701             :             // reclaim debug overlay line memory when no longer debugging (and make sure to set to zero after deletion)
     702           0 :             if (m_DebugBoundingBoxOverlay) SAFE_DELETE(m_DebugBoundingBoxOverlay);
     703           0 :             if (m_DebugSelectionBoxOverlay) SAFE_DELETE(m_DebugSelectionBoxOverlay);
     704             :         }
     705             :     }
     706           0 : }
     707             : 
     708         274 : REGISTER_COMPONENT_TYPE(Selectable)

Generated by: LCOV version 1.16