LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpObstruction.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 120 372 32.3 %
Date: 2026-12-02 01:21:50 Functions: 15 40 37.5 %

          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 "ICmpObstruction.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "maths/Fixed.h"
      24             : #include "maths/FixedVector2D.h"
      25             : #include "maths/FixedVector3D.h"
      26             : #include "ps/CLogger.h"
      27             : #include "simulation2/MessageTypes.h"
      28             : #include "simulation2/components/ICmpObstructionManager.h"
      29             : #include "simulation2/components/ICmpPathfinder.h"
      30             : #include "simulation2/components/ICmpPosition.h"
      31             : #include "simulation2/components/ICmpTerrain.h"
      32             : #include "simulation2/components/ICmpUnitMotion.h"
      33             : #include "simulation2/components/ICmpWaterManager.h"
      34             : #include "simulation2/helpers/Pathfinding.h"
      35             : #include "simulation2/helpers/Position.h"
      36             : #include "simulation2/serialization/SerializeTemplates.h"
      37             : #include "simulation2/serialization/SerializedTypes.h"
      38             : #include "simulation2/system/Component.h"
      39             : #include "simulation2/system/Entity.h"
      40             : #include "simulation2/system/Message.h"
      41             : 
      42             : #include <algorithm>
      43             : #include <cstddef>
      44             : #include <cstdint>
      45             : #include <map>
      46             : #include <string>
      47             : #include <type_traits>
      48             : #include <utility>
      49             : #include <vector>
      50             : 
      51             : template<>
      52             : struct SerializeHelper<ICmpObstructionManager::tag_t>
      53             : {
      54             :     template<typename S>
      55           0 :     void operator()(S& serialize, const char* /*name*/,
      56             :         Serialize::qualify<S, ICmpObstructionManager::tag_t> value)
      57             :     {
      58           0 :         serialize.NumberU32_Unbounded("tag", value.n);
      59             :     }
      60             : };
      61             : 
      62             : /**
      63             :  * Obstruction implementation. This keeps the ICmpPathfinder's model of the world updated when the
      64             :  * entities move and die, with shapes derived from ICmpFootprint.
      65             :  */
      66         195 : class CCmpObstruction final : public ICmpObstruction
      67             : {
      68             : public:
      69         137 :     static void ClassInit(CComponentManager& componentManager)
      70             :     {
      71         137 :         componentManager.SubscribeToMessageType(MT_PositionChanged);
      72         137 :         componentManager.SubscribeToMessageType(MT_Destroy);
      73             :     }
      74             : 
      75         390 :     DEFAULT_COMPONENT_ALLOCATOR(Obstruction)
      76             : 
      77             :     typedef ICmpObstructionManager::tag_t tag_t;
      78             :     typedef ICmpObstructionManager::flags_t flags_t;
      79             : 
      80             :     // Template state:
      81             : 
      82             :     EObstructionType m_Type;
      83             : 
      84             :     entity_pos_t m_Size0; // radius or width
      85             :     entity_pos_t m_Size1; // radius or depth
      86             :     flags_t m_TemplateFlags;
      87             :     entity_pos_t m_Clearance;
      88             : 
      89             :     typedef struct {
      90             :         entity_pos_t dx, dz;
      91             :         entity_angle_t da;
      92             :         entity_pos_t size0, size1;
      93             :         flags_t flags;
      94           0 :     } Shape;
      95             : 
      96             :     std::vector<Shape> m_Shapes;
      97             : 
      98             :     // Dynamic state:
      99             : 
     100             :     /// Whether the obstruction is actively obstructing or just an inactive placeholder.
     101             :     bool m_Active;
     102             :     /// Whether the entity associated with this obstruction is currently moving. Only applicable for
     103             :     /// UNIT-type obstructions.
     104             :     bool m_Moving;
     105             :     /// Whether an obstruction's control group should be kept consistent and
     106             :     /// used to set control groups for entities that collide with it.
     107             :     bool m_ControlPersist;
     108             : 
     109             :     // WORKAROUND: While processing Destroy messages, the obstruction component may receive messages
     110             :     // that make it re-enable the obstruction, thus leaving behind dangling obstructions.
     111             :     // To avoid that, if this is true, _never_ reactivate the obstruction.
     112             :     bool m_IsDestroyed = false;
     113             : 
     114             :     /**
     115             :      * Primary control group identifier. Indicates to which control group this entity's shape belongs.
     116             :      * Typically used in combination with obstruction test filters to have member shapes ignore each
     117             :      * other during obstruction tests. Defaults to the entity's ID. Must never be set to INVALID_ENTITY.
     118             :      */
     119             :     entity_id_t m_ControlGroup;
     120             : 
     121             :     /**
     122             :      * Optional secondary control group identifier. Similar to m_ControlGroup; if set to a valid value,
     123             :      * then this field identifies an additional, secondary control group to which this entity's shape
     124             :      * belongs. Set to INVALID_ENTITY to not assign any secondary group. Defaults to INVALID_ENTITY.
     125             :      *
     126             :      * These are only necessary in case it is not sufficient for an entity to belong to only one control
     127             :      * group. Otherwise, they can be ignored.
     128             :      */
     129             :     entity_id_t m_ControlGroup2;
     130             : 
     131             :     /// Identifier of this entity's obstruction shape, as registered in the obstruction manager. Contains
     132             :     /// structure, but should be treated as opaque here.
     133             :     tag_t m_Tag;
     134             :     std::vector<tag_t> m_ClusterTags;
     135             : 
     136             :     /// Set of flags affecting the behaviour of this entity's obstruction shape.
     137             :     flags_t m_Flags;
     138             : 
     139         137 :     static std::string GetSchema()
     140             :     {
     141         137 :         return
     142             :             "<a:example/>"
     143             :             "<a:help>Causes this entity to obstruct the motion of other units.</a:help>"
     144             :             "<choice>"
     145             :                 "<element name='Static'>"
     146             :                     "<attribute name='width'>"
     147             :                         "<data type='decimal'>"
     148             :                             "<param name='minInclusive'>1.5</param>"
     149             :                         "</data>"
     150             :                     "</attribute>"
     151             :                     "<attribute name='depth'>"
     152             :                         "<data type='decimal'>"
     153             :                             "<param name='minInclusive'>1.5</param>"
     154             :                         "</data>"
     155             :                     "</attribute>"
     156             :                 "</element>"
     157             :                 "<element name='Unit'>"
     158             :                     "<empty/>"
     159             :                 "</element>"
     160             :                 "<element name='Obstructions'>"
     161             :                     "<zeroOrMore>"
     162             :                         "<element>"
     163             :                             "<anyName/>"
     164             :                             "<optional>"
     165             :                                 "<attribute name='x'>"
     166             :                                     "<data type='decimal'/>"
     167             :                                 "</attribute>"
     168             :                             "</optional>"
     169             :                             "<optional>"
     170             :                                 "<attribute name='z'>"
     171             :                                     "<data type='decimal'/>"
     172             :                                 "</attribute>"
     173             :                             "</optional>"
     174             :                             "<attribute name='width'>"
     175             :                                 "<data type='decimal'>"
     176             :                                     "<param name='minInclusive'>1.5</param>"
     177             :                                 "</data>"
     178             :                             "</attribute>"
     179             :                             "<attribute name='depth'>"
     180             :                                 "<data type='decimal'>"
     181             :                                     "<param name='minInclusive'>1.5</param>"
     182             :                                 "</data>"
     183             :                             "</attribute>"
     184             :                         "</element>"
     185             :                     "</zeroOrMore>"
     186             :                 "</element>"
     187             :             "</choice>"
     188             :             "<element name='Active' a:help='If false, this entity will be ignored in collision tests by other units but can still perform its own collision tests'>"
     189             :                 "<data type='boolean'/>"
     190             :             "</element>"
     191             :             "<element name='BlockMovement' a:help='Whether units should be allowed to walk through this entity'>"
     192             :                 "<data type='boolean'/>"
     193             :             "</element>"
     194             :             "<element name='BlockPathfinding' a:help='Whether the long-distance pathfinder should avoid paths through this entity. This should only be set for large stationary obstructions'>"
     195             :                 "<data type='boolean'/>"
     196             :             "</element>"
     197             :             "<element name='BlockFoundation' a:help='Whether players should be unable to place building foundations on top of this entity. If true, BlockConstruction should be true too'>"
     198             :                 "<data type='boolean'/>"
     199             :             "</element>"
     200             :             "<element name='BlockConstruction' a:help='Whether players should be unable to begin constructing buildings placed on top of this entity'>"
     201             :                 "<data type='boolean'/>"
     202             :             "</element>"
     203             :             "<element name='DeleteUponConstruction' a:help='Whether this entity should be deleted when construction on a buildings placed on top of this entity is started.'>"
     204             :                 "<data type='boolean'/>"
     205             :             "</element>"
     206             :             "<element name='DisableBlockMovement' a:help='If true, BlockMovement will be overridden and treated as false. (This is a special case to handle foundations)'>"
     207             :                 "<data type='boolean'/>"
     208             :             "</element>"
     209             :             "<element name='DisableBlockPathfinding' a:help='If true, BlockPathfinding will be overridden and treated as false. (This is a special case to handle foundations)'>"
     210             :                 "<data type='boolean'/>"
     211             :             "</element>"
     212             :             "<optional>"
     213             :                 "<element name='ControlPersist' a:help='If present, the control group of this entity will be given to entities that are colliding with it.'>"
     214             :                     "<empty/>"
     215             :                 "</element>"
     216         137 :             "</optional>";
     217             :     }
     218             : 
     219         195 :     void Init(const CParamNode& paramNode) override
     220             :     {
     221             :         // The minimum obstruction size is the navcell size * sqrt(2)
     222             :         // This is enforced in the schema as a minimum of 1.5
     223         195 :         fixed minObstruction = (Pathfinding::NAVCELL_SIZE.Square() * 2).Sqrt();
     224         195 :         m_TemplateFlags = 0;
     225         195 :         if (paramNode.GetChild("BlockMovement").ToBool())
     226         189 :             m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_MOVEMENT;
     227         195 :         if (paramNode.GetChild("BlockPathfinding").ToBool())
     228           0 :             m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_PATHFINDING;
     229         195 :         if (paramNode.GetChild("BlockFoundation").ToBool())
     230           0 :             m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_FOUNDATION;
     231         195 :         if (paramNode.GetChild("BlockConstruction").ToBool())
     232         195 :             m_TemplateFlags |= ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION;
     233         195 :         if (paramNode.GetChild("DeleteUponConstruction").ToBool())
     234           6 :             m_TemplateFlags |= ICmpObstructionManager::FLAG_DELETE_UPON_CONSTRUCTION;
     235             : 
     236         195 :         m_Flags = m_TemplateFlags;
     237         195 :         if (paramNode.GetChild("DisableBlockMovement").ToBool())
     238           0 :             m_Flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT);
     239         195 :         if (paramNode.GetChild("DisableBlockPathfinding").ToBool())
     240           0 :             m_Flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING);
     241             : 
     242         195 :         if (paramNode.GetChild("Unit").IsOk())
     243             :         {
     244         189 :             m_Type = UNIT;
     245             : 
     246         189 :             CmpPtr<ICmpUnitMotion> cmpUnitMotion(GetEntityHandle());
     247         189 :             if (cmpUnitMotion)
     248           0 :                 m_Clearance = cmpUnitMotion->GetUnitClearance();
     249             :         }
     250           6 :         else if (paramNode.GetChild("Static").IsOk())
     251             :         {
     252           6 :             m_Type = STATIC;
     253           6 :             m_Size0 = paramNode.GetChild("Static").GetChild("@width").ToFixed();
     254           6 :             m_Size1 = paramNode.GetChild("Static").GetChild("@depth").ToFixed();
     255           6 :             ENSURE(m_Size0 > minObstruction);
     256           6 :             ENSURE(m_Size1 > minObstruction);
     257             :         }
     258             :         else
     259             :         {
     260           0 :             m_Type = CLUSTER;
     261           0 :             CFixedVector2D max = CFixedVector2D(fixed::FromInt(0), fixed::FromInt(0));
     262           0 :             CFixedVector2D min = CFixedVector2D(fixed::FromInt(0), fixed::FromInt(0));
     263           0 :             const CParamNode::ChildrenMap& clusterMap = paramNode.GetChild("Obstructions").GetChildren();
     264           0 :             for(CParamNode::ChildrenMap::const_iterator it = clusterMap.begin(); it != clusterMap.end(); ++it)
     265             :             {
     266           0 :                 Shape b;
     267           0 :                 b.size0 = it->second.GetChild("@width").ToFixed();
     268           0 :                 b.size1 = it->second.GetChild("@depth").ToFixed();
     269           0 :                 ENSURE(b.size0 > minObstruction);
     270           0 :                 ENSURE(b.size1 > minObstruction);
     271           0 :                 b.dx = it->second.GetChild("@x").ToFixed();
     272           0 :                 b.dz = it->second.GetChild("@z").ToFixed();
     273           0 :                 b.da = entity_angle_t::FromInt(0);
     274           0 :                 b.flags = m_Flags;
     275           0 :                 m_Shapes.push_back(b);
     276           0 :                 max.X = std::max(max.X, b.dx + b.size0/2);
     277           0 :                 max.Y = std::max(max.Y, b.dz + b.size1/2);
     278           0 :                 min.X = std::min(min.X, b.dx - b.size0/2);
     279           0 :                 min.Y = std::min(min.Y, b.dz - b.size1/2);
     280             :             }
     281           0 :             m_Size0 = fixed::FromInt(2).Multiply(std::max(max.X, -min.X));
     282           0 :             m_Size1 = fixed::FromInt(2).Multiply(std::max(max.Y, -min.Y));
     283             :         }
     284             : 
     285         195 :         m_Active = paramNode.GetChild("Active").ToBool();
     286         195 :         m_ControlPersist = paramNode.GetChild("ControlPersist").IsOk();
     287             : 
     288         195 :         m_Tag = tag_t();
     289         195 :         if (m_Type == CLUSTER)
     290           0 :             m_ClusterTags.clear();
     291         195 :         m_Moving = false;
     292         195 :         m_ControlGroup = GetEntityId();
     293         195 :         m_ControlGroup2 = INVALID_ENTITY;
     294         195 :     }
     295             : 
     296         195 :     void Deinit() override
     297             :     {
     298         195 :     }
     299             : 
     300             :     template<typename S>
     301        1032 :     void SerializeCommon(S& serialize)
     302             :     {
     303        1032 :         serialize.Bool("active", m_Active);
     304        1032 :         serialize.Bool("moving", m_Moving);
     305        1032 :         serialize.NumberU32_Unbounded("control group", m_ControlGroup);
     306        1032 :         serialize.NumberU32_Unbounded("control group 2", m_ControlGroup2);
     307        1032 :         serialize.NumberU32_Unbounded("tag", m_Tag.n);
     308        1032 :         serialize.NumberU8_Unbounded("flags", m_Flags);
     309        1032 :         if (m_Type == CLUSTER)
     310           0 :             Serializer(serialize, "cluster tags", m_ClusterTags);
     311        1032 :         if (m_Type == UNIT)
     312        1020 :             serialize.NumberFixed_Unbounded("clearance", m_Clearance);
     313        1032 :     }
     314             : 
     315        1032 :     void Serialize(ISerializer& serialize) override
     316             :     {
     317        1032 :         SerializeCommon(serialize);
     318        1032 :     }
     319             : 
     320           0 :     void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
     321             :     {
     322           0 :         Init(paramNode);
     323             : 
     324           0 :         SerializeCommon(deserialize);
     325           0 :     }
     326             : 
     327        7971 :     void HandleMessage(const CMessage& msg, bool /*global*/) override
     328             :     {
     329        7971 :         switch (msg.GetType())
     330             :         {
     331        7941 :         case MT_PositionChanged:
     332        7941 :         {
     333        7941 :             if (!m_Active || m_IsDestroyed)
     334             :                 break;
     335             : 
     336        7902 :             const CMessagePositionChanged& data = static_cast<const CMessagePositionChanged&> (msg);
     337             : 
     338        7902 :             if (!data.inWorld && !m_Tag.valid())
     339             :                 break; // nothing needs to change
     340             : 
     341        7902 :             CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     342        7902 :             if (!cmpObstructionManager)
     343             :                 break; // error
     344             : 
     345        7902 :             if (data.inWorld && m_Tag.valid())
     346             :             {
     347        7716 :                 cmpObstructionManager->MoveShape(m_Tag, data.x, data.z, data.a);
     348             : 
     349        7716 :                 if (m_Type == CLUSTER)
     350             :                 {
     351           0 :                     for (size_t i = 0; i < m_Shapes.size(); ++i)
     352             :                     {
     353           0 :                         Shape& b = m_Shapes[i];
     354           0 :                         fixed s, c;
     355           0 :                         sincos_approx(data.a, s, c);
     356           0 :                         cmpObstructionManager->MoveShape(m_ClusterTags[i], data.x + b.dx.Multiply(c) + b.dz.Multiply(s), data.z + b.dz.Multiply(c) - b.dx.Multiply(s), data.a + b.da);
     357             :                     }
     358             :                 }
     359             :             }
     360         186 :             else if (data.inWorld && !m_Tag.valid())
     361             :             {
     362             :                 // Need to create a new pathfinder shape:
     363         186 :                 if (m_Type == STATIC)
     364           6 :                     m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(),
     365           6 :                         data.x, data.z, data.a, m_Size0, m_Size1, m_Flags, m_ControlGroup, m_ControlGroup2);
     366         180 :                 else if (m_Type == UNIT)
     367         360 :                     m_Tag = cmpObstructionManager->AddUnitShape(GetEntityId(),
     368         360 :                         data.x, data.z, m_Clearance, (flags_t)(m_Flags | (m_Moving ? ICmpObstructionManager::FLAG_MOVING : 0)), m_ControlGroup);
     369             :                 else
     370           0 :                     AddClusterShapes(data.x, data.z, data.a);
     371             :             }
     372           0 :             else if (!data.inWorld && m_Tag.valid())
     373             :             {
     374           0 :                 cmpObstructionManager->RemoveShape(m_Tag);
     375           0 :                 m_Tag = tag_t();
     376           0 :                 if(m_Type == CLUSTER)
     377           0 :                     RemoveClusterShapes();
     378             :             }
     379             :             break;
     380             :         }
     381          30 :         case MT_Destroy:
     382          30 :         {
     383             :             // Mark the obstruction as destroyed to prevent reactivating it after this point
     384          30 :             m_IsDestroyed = true;
     385          30 :             m_Active = false;
     386             : 
     387          30 :             if (m_Tag.valid())
     388             :             {
     389          30 :                 CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     390          30 :                 if (!cmpObstructionManager)
     391             :                     break; // error
     392             : 
     393          30 :                 cmpObstructionManager->RemoveShape(m_Tag);
     394          30 :                 m_Tag = tag_t();
     395          30 :                 if(m_Type == CLUSTER)
     396           0 :                     RemoveClusterShapes();
     397             :             }
     398             :             break;
     399             :         }
     400             :         }
     401        7971 :     }
     402             : 
     403           0 :     void SetActive(bool active) override
     404             :     {
     405           0 :         if (active && !m_Active && !m_IsDestroyed)
     406             :         {
     407           0 :             m_Active = true;
     408             : 
     409             :             // Construct the obstruction shape
     410             : 
     411           0 :             CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     412           0 :             if (!cmpObstructionManager)
     413           0 :                 return; // error
     414             : 
     415           0 :             CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     416           0 :             if (!cmpPosition)
     417             :                 return; // error
     418             : 
     419           0 :             if (!cmpPosition->IsInWorld())
     420             :                 return; // don't need an obstruction
     421             : 
     422             :             // TODO: code duplication from message handlers
     423           0 :             CFixedVector2D pos = cmpPosition->GetPosition2D();
     424           0 :             if (m_Type == STATIC)
     425           0 :                 m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(),
     426           0 :                     pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, m_Flags, m_ControlGroup, m_ControlGroup2);
     427           0 :             else if (m_Type == UNIT)
     428           0 :                 m_Tag = cmpObstructionManager->AddUnitShape(GetEntityId(),
     429           0 :                     pos.X, pos.Y, m_Clearance, (flags_t)(m_Flags | (m_Moving ? ICmpObstructionManager::FLAG_MOVING : 0)), m_ControlGroup);
     430             :             else
     431           0 :                 AddClusterShapes(pos.X, pos.Y, cmpPosition->GetRotation().Y);
     432             : 
     433             :             // Used by UnitMotion to activate/deactivate pushing
     434           0 :             if (m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT)
     435             :             {
     436           0 :                 CMessageMovementObstructionChanged msg;
     437           0 :                 GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
     438           0 :             }
     439           0 :         }
     440           0 :         else if (!active && m_Active)
     441             :         {
     442           0 :             m_Active = false;
     443             : 
     444             :             // Delete the obstruction shape
     445             : 
     446             :             // TODO: code duplication from message handlers
     447           0 :             if (m_Tag.valid())
     448             :             {
     449           0 :                 CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     450           0 :                 if (!cmpObstructionManager)
     451           0 :                     return; // error
     452             : 
     453           0 :                 cmpObstructionManager->RemoveShape(m_Tag);
     454           0 :                 m_Tag = tag_t();
     455           0 :                 if (m_Type == CLUSTER)
     456           0 :                     RemoveClusterShapes();
     457             :             }
     458             : 
     459             :             // Used by UnitMotion to activate/deactivate pushing
     460           0 :             if (m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT)
     461             :             {
     462           0 :                 CMessageMovementObstructionChanged msg;
     463           0 :                 GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
     464           0 :             }
     465             :         }
     466             :         // else we didn't change the active status
     467             :     }
     468             : 
     469           0 :     void SetDisableBlockMovementPathfinding(bool movementDisabled, bool pathfindingDisabled, int32_t shape) override
     470             :     {
     471           0 :         flags_t *flags = NULL;
     472           0 :         if (shape == -1)
     473           0 :             flags = &m_Flags;
     474           0 :         else if (m_Type == CLUSTER && shape < (int32_t)m_Shapes.size())
     475           0 :             flags = &m_Shapes[shape].flags;
     476             :         else
     477             :             return; // error
     478             : 
     479             :         // Remove the blocking / pathfinding flags or
     480             :         // Add the blocking / pathfinding flags if the template had enabled them
     481           0 :         if (movementDisabled)
     482           0 :             *flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT);
     483             :         else
     484           0 :             *flags |= (flags_t)(m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT);
     485           0 :         if (pathfindingDisabled)
     486           0 :             *flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING);
     487             :         else
     488           0 :             *flags |= (flags_t)(m_TemplateFlags & ICmpObstructionManager::FLAG_BLOCK_PATHFINDING);
     489             : 
     490             :         // Reset the shape with the new flags (kind of inefficiently - we
     491             :         // should have a ICmpObstructionManager::SetFlags function or something)
     492           0 :         if (m_Active)
     493             :         {
     494           0 :             SetActive(false);
     495           0 :             SetActive(true);
     496             :         }
     497             :     }
     498             : 
     499         189 :     bool GetBlockMovementFlag(bool templateOnly) const override
     500             :     {
     501         189 :         return m_Active && ((templateOnly ? m_TemplateFlags : m_Flags) & ICmpObstructionManager::FLAG_BLOCK_MOVEMENT) != 0;
     502             :     }
     503             : 
     504           0 :     EObstructionType GetObstructionType() const override
     505             :     {
     506           0 :         return m_Type;
     507             :     }
     508             : 
     509        8508 :     ICmpObstructionManager::tag_t GetObstruction() const override
     510             :     {
     511        8508 :         return m_Tag;
     512             :     }
     513             : 
     514           0 :     bool GetPreviousObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const override
     515             :     {
     516           0 :         return GetObstructionSquare(out, true);
     517             :     }
     518             : 
     519       50148 :     bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out) const override
     520             :     {
     521       50148 :         return GetObstructionSquare(out, false);
     522             :     }
     523             : 
     524       50148 :     bool GetObstructionSquare(ICmpObstructionManager::ObstructionSquare& out, bool previousPosition) const
     525             :     {
     526       50148 :         CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     527       50148 :         if (!cmpPosition)
     528             :             return false; // error
     529             : 
     530       50148 :         CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     531       50148 :         if (!cmpObstructionManager)
     532             :             return false; // error
     533             : 
     534       50148 :         if (!cmpPosition->IsInWorld())
     535             :             return false; // no obstruction square
     536             : 
     537       50148 :         CFixedVector2D pos;
     538       50148 :         if (previousPosition)
     539           0 :             pos = cmpPosition->GetPreviousPosition2D();
     540             :         else
     541       50148 :             pos = cmpPosition->GetPosition2D();
     542       50148 :         if (m_Type == UNIT)
     543       50100 :             out = cmpObstructionManager->GetUnitShapeObstruction(pos.X, pos.Y, m_Clearance);
     544             :         else
     545          48 :             out = cmpObstructionManager->GetStaticShapeObstruction(pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1);
     546             :         return true;
     547             :     }
     548             : 
     549         186 :     entity_pos_t GetSize() const override
     550             :     {
     551         186 :         if (m_Type == UNIT)
     552         180 :             return m_Clearance;
     553             :         else
     554           6 :             return CFixedVector2D(m_Size0 / 2, m_Size1 / 2).Length();
     555             :     }
     556             : 
     557           0 :     CFixedVector2D GetStaticSize() const override
     558             :     {
     559           0 :         return m_Type == STATIC ? CFixedVector2D(m_Size0, m_Size1) : CFixedVector2D();
     560             :     }
     561             : 
     562         189 :     void SetUnitClearance(const entity_pos_t& clearance) override
     563             :     {
     564             :         // This doesn't send a MovementObstructionChanged message
     565             :         // because it's a just a workaround init order, and used in UnitMotion directly.
     566         189 :         if (m_Type == UNIT)
     567         189 :             m_Clearance = clearance;
     568         189 :     }
     569             : 
     570           0 :     bool IsControlPersistent() const override
     571             :     {
     572           0 :         return m_ControlPersist;
     573             :     }
     574             : 
     575           0 :     bool CheckShorePlacement() const override
     576             :     {
     577           0 :         ICmpObstructionManager::ObstructionSquare s;
     578           0 :         if (!GetObstructionSquare(s))
     579             :             return false;
     580             : 
     581           0 :         CFixedVector2D front = CFixedVector2D(s.x, s.z) + s.v.Multiply(s.hh);
     582           0 :         CFixedVector2D  back = CFixedVector2D(s.x, s.z) - s.v.Multiply(s.hh);
     583             : 
     584           0 :         CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
     585           0 :         CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
     586           0 :         if (!cmpTerrain || !cmpWaterManager)
     587             :             return false;
     588             : 
     589             :         // Keep these constants in agreement with the pathfinder.
     590           0 :         return cmpWaterManager->GetWaterLevel(front.X, front.Y) - cmpTerrain->GetGroundLevel(front.X, front.Y) > fixed::FromInt(1) &&
     591           0 :                cmpWaterManager->GetWaterLevel( back.X,  back.Y) - cmpTerrain->GetGroundLevel( back.X,  back.Y) < fixed::FromInt(2);
     592             :     }
     593             : 
     594           0 :     EFoundationCheck CheckFoundation(const std::string& className) const override
     595             :     {
     596           0 :         return  CheckFoundation(className, false);
     597             :     }
     598             : 
     599           0 :     EFoundationCheck CheckFoundation(const std::string& className, bool onlyCenterPoint) const override
     600             :     {
     601           0 :         CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     602           0 :         if (!cmpPosition)
     603             :             return FOUNDATION_CHECK_FAIL_ERROR; // error
     604             : 
     605           0 :         if (!cmpPosition->IsInWorld())
     606             :             return FOUNDATION_CHECK_FAIL_NO_OBSTRUCTION; // no obstruction
     607             : 
     608           0 :         CFixedVector2D pos = cmpPosition->GetPosition2D();
     609             : 
     610           0 :         CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
     611           0 :         if (!cmpPathfinder)
     612             :             return FOUNDATION_CHECK_FAIL_ERROR; // error
     613             : 
     614             :         // required precondition to use SkipControlGroupsRequireFlagObstructionFilter
     615           0 :         if (m_ControlGroup == INVALID_ENTITY)
     616             :         {
     617           0 :             LOGERROR("[CmpObstruction] Cannot test for foundation obstructions; primary control group must be valid");
     618           0 :             return FOUNDATION_CHECK_FAIL_ERROR;
     619             :         }
     620             : 
     621             :         // Get passability class
     622           0 :         pass_class_t passClass = cmpPathfinder->GetPassabilityClass(className);
     623             : 
     624             :         // Ignore collisions within the same control group, or with other non-foundation-blocking shapes.
     625             :         // Note that, since the control group for each entity defaults to the entity's ID, this is typically
     626             :         // equivalent to only ignoring the entity's own shape and other non-foundation-blocking shapes.
     627           0 :         SkipControlGroupsRequireFlagObstructionFilter filter(m_ControlGroup, m_ControlGroup2,
     628           0 :             ICmpObstructionManager::FLAG_BLOCK_FOUNDATION);
     629             : 
     630           0 :         if (m_Type == UNIT)
     631           0 :             return cmpPathfinder->CheckUnitPlacement(filter, pos.X, pos.Y, m_Clearance, passClass, onlyCenterPoint);
     632             :         else
     633           0 :             return cmpPathfinder->CheckBuildingPlacement(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, GetEntityId(), passClass, onlyCenterPoint);
     634           0 :     }
     635             : 
     636           0 :     bool CheckDuplicateFoundation() const override
     637             :     {
     638           0 :         CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     639           0 :         if (!cmpPosition)
     640             :             return false; // error
     641             : 
     642           0 :         if (!cmpPosition->IsInWorld())
     643             :             return false; // no obstruction
     644             : 
     645           0 :         CFixedVector2D pos = cmpPosition->GetPosition2D();
     646             : 
     647           0 :         CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     648           0 :         if (!cmpObstructionManager)
     649             :             return false; // error
     650             : 
     651             :         // required precondition to use SkipControlGroupsRequireFlagObstructionFilter
     652           0 :         if (m_ControlGroup == INVALID_ENTITY)
     653             :         {
     654           0 :             LOGERROR("[CmpObstruction] Cannot test for foundation obstructions; primary control group must be valid");
     655           0 :             return false;
     656             :         }
     657             : 
     658             :         // Ignore collisions with entities unless they block foundations and match both control groups.
     659           0 :         SkipTagRequireControlGroupsAndFlagObstructionFilter filter(m_Tag, m_ControlGroup, m_ControlGroup2,
     660           0 :             ICmpObstructionManager::FLAG_BLOCK_FOUNDATION);
     661             : 
     662           0 :         if (m_Type == UNIT)
     663           0 :             return !cmpObstructionManager->TestUnitShape(filter, pos.X, pos.Y, m_Clearance, NULL);
     664             :         else
     665           0 :             return !cmpObstructionManager->TestStaticShape(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, NULL );
     666           0 :     }
     667             : 
     668           0 :     std::vector<entity_id_t> GetEntitiesByFlags(flags_t flags) const override
     669             :     {
     670           0 :         std::vector<entity_id_t> ret;
     671             : 
     672           0 :         CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     673           0 :         if (!cmpObstructionManager)
     674             :             return ret; // error
     675             : 
     676             :         // Ignore collisions within the same control group, or with other shapes that don't match the filter.
     677             :         // Note that, since the control group for each entity defaults to the entity's ID, this is typically
     678             :         // equivalent to only ignoring the entity's own shape and other shapes that don't match the filter.
     679           0 :         SkipControlGroupsRequireFlagObstructionFilter filter(false, m_ControlGroup, m_ControlGroup2, flags);
     680             : 
     681           0 :         ICmpObstructionManager::ObstructionSquare square;
     682           0 :         if (!GetObstructionSquare(square))
     683             :             return ret; // error
     684             : 
     685           0 :         cmpObstructionManager->GetUnitsOnObstruction(square, ret, filter, false);
     686           0 :         cmpObstructionManager->GetStaticObstructionsOnObstruction(square, ret, filter);
     687             : 
     688             :         return ret;
     689           0 :     }
     690             : 
     691           0 :     std::vector<entity_id_t> GetEntitiesBlockingMovement() const override
     692             :     {
     693           0 :         return GetEntitiesByFlags(ICmpObstructionManager::FLAG_BLOCK_MOVEMENT);
     694             :     }
     695             : 
     696           0 :     std::vector<entity_id_t> GetEntitiesBlockingConstruction() const override
     697             :     {
     698           0 :         return GetEntitiesByFlags(ICmpObstructionManager::FLAG_BLOCK_CONSTRUCTION);
     699             :     }
     700             : 
     701           0 :     std::vector<entity_id_t> GetEntitiesDeletedUponConstruction() const override
     702             :     {
     703           0 :         return GetEntitiesByFlags(ICmpObstructionManager::FLAG_DELETE_UPON_CONSTRUCTION);
     704             :     }
     705             : 
     706        8118 :     void SetMovingFlag(bool enabled) override
     707             :     {
     708        8118 :         m_Moving = enabled;
     709             : 
     710        8118 :         if (m_Tag.valid() && m_Type == UNIT)
     711             :         {
     712        8118 :             CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     713        8118 :             if (cmpObstructionManager)
     714        8118 :                 cmpObstructionManager->SetUnitMovingFlag(m_Tag, m_Moving);
     715             :         }
     716        8118 :     }
     717             : 
     718           0 :     void SetControlGroup(entity_id_t group) override
     719             :     {
     720           0 :         m_ControlGroup = group;
     721           0 :         UpdateControlGroups();
     722           0 :     }
     723             : 
     724           0 :     void SetControlGroup2(entity_id_t group2) override
     725             :     {
     726           0 :         m_ControlGroup2 = group2;
     727           0 :         UpdateControlGroups();
     728           0 :     }
     729             : 
     730           0 :     entity_id_t GetControlGroup() const override
     731             :     {
     732           0 :         return m_ControlGroup;
     733             :     }
     734             : 
     735           0 :     entity_id_t GetControlGroup2() const override
     736             :     {
     737           0 :         return m_ControlGroup2;
     738             :     }
     739             : 
     740           0 :     void UpdateControlGroups()
     741             :     {
     742           0 :         if (m_Tag.valid())
     743             :         {
     744           0 :             CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     745           0 :             if (cmpObstructionManager)
     746             :             {
     747           0 :                 if (m_Type == UNIT)
     748             :                 {
     749           0 :                     cmpObstructionManager->SetUnitControlGroup(m_Tag, m_ControlGroup);
     750             :                 }
     751           0 :                 else if (m_Type == STATIC)
     752             :                 {
     753           0 :                     cmpObstructionManager->SetStaticControlGroup(m_Tag, m_ControlGroup, m_ControlGroup2);
     754             :                 }
     755             :                 else
     756             :                 {
     757           0 :                     cmpObstructionManager->SetStaticControlGroup(m_Tag, m_ControlGroup, m_ControlGroup2);
     758           0 :                     for (size_t i = 0; i < m_ClusterTags.size(); ++i)
     759             :                     {
     760           0 :                         cmpObstructionManager->SetStaticControlGroup(m_ClusterTags[i], m_ControlGroup, m_ControlGroup2);
     761             :                     }
     762             :                 }
     763             :             }
     764             :         }
     765           0 :     }
     766             : 
     767           0 :     void ResolveFoundationCollisions() const override
     768             :     {
     769           0 :         if (m_Type == UNIT)
     770           0 :             return;
     771             : 
     772           0 :         CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     773           0 :         if (!cmpObstructionManager)
     774             :             return;
     775             : 
     776           0 :         CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     777           0 :         if (!cmpPosition)
     778             :             return; // error
     779             : 
     780           0 :         if (!cmpPosition->IsInWorld())
     781             :             return; // no obstruction
     782             : 
     783           0 :         CFixedVector2D pos = cmpPosition->GetPosition2D();
     784             : 
     785             :         // Ignore collisions within the same control group, or with other non-foundation-blocking shapes.
     786             :         // Note that, since the control group for each entity defaults to the entity's ID, this is typically
     787             :         // equivalent to only ignoring the entity's own shape and other non-foundation-blocking shapes.
     788           0 :         SkipControlGroupsRequireFlagObstructionFilter filter(m_ControlGroup, m_ControlGroup2,
     789           0 :             ICmpObstructionManager::FLAG_BLOCK_FOUNDATION);
     790             : 
     791           0 :         std::vector<entity_id_t> collisions;
     792           0 :         if (cmpObstructionManager->TestStaticShape(filter, pos.X, pos.Y, cmpPosition->GetRotation().Y, m_Size0, m_Size1, &collisions))
     793             :         {
     794           0 :             std::vector<entity_id_t> persistentEnts, normalEnts;
     795             : 
     796           0 :             if (m_ControlPersist)
     797           0 :                 persistentEnts.push_back(m_ControlGroup);
     798             :             else
     799           0 :                 normalEnts.push_back(GetEntityId());
     800             : 
     801           0 :             for (std::vector<entity_id_t>::iterator it = collisions.begin(); it != collisions.end(); ++it)
     802             :             {
     803           0 :                 entity_id_t ent = *it;
     804           0 :                 if (ent == INVALID_ENTITY)
     805           0 :                     continue;
     806             : 
     807           0 :                 CmpPtr<ICmpObstruction> cmpObstruction(GetSimContext(), ent);
     808           0 :                 if (!cmpObstruction->IsControlPersistent())
     809           0 :                     normalEnts.push_back(ent);
     810             :                 else
     811           0 :                     persistentEnts.push_back(cmpObstruction->GetControlGroup());
     812             :             }
     813             : 
     814             :             // The collision can't be resolved without usable persistent control groups.
     815           0 :             if (persistentEnts.empty())
     816           0 :                 return;
     817             : 
     818             :             // Attempt to replace colliding entities' control groups with a persistent one.
     819           0 :             for (const entity_id_t normalEnt : normalEnts)
     820             :             {
     821           0 :                 CmpPtr<ICmpObstruction> cmpObstruction(GetSimContext(), normalEnt);
     822           0 :                 for (const entity_id_t persistent : persistentEnts)
     823             :                 {
     824           0 :                     entity_id_t group = cmpObstruction->GetControlGroup();
     825             : 
     826             :                     // Only clobber 'default' control groups.
     827           0 :                     if (group == normalEnt)
     828           0 :                         cmpObstruction->SetControlGroup(persistent);
     829           0 :                     else if (cmpObstruction->GetControlGroup2() == INVALID_ENTITY && group != persistent)
     830           0 :                         cmpObstruction->SetControlGroup2(persistent);
     831             :                 }
     832             :             }
     833           0 :         }
     834           0 :     }
     835             : protected:
     836             : 
     837           0 :     inline void AddClusterShapes(entity_pos_t x, entity_pos_t z, entity_angle_t a)
     838             :     {
     839           0 :         CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     840           0 :         if (!cmpObstructionManager)
     841           0 :             return; // error
     842             : 
     843           0 :         flags_t flags = m_Flags;
     844             :         // Disable block movement and block pathfinding for the obstruction shape
     845           0 :         flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_MOVEMENT);
     846           0 :         flags &= (flags_t)(~ICmpObstructionManager::FLAG_BLOCK_PATHFINDING);
     847             : 
     848           0 :         m_Tag = cmpObstructionManager->AddStaticShape(GetEntityId(),
     849             :             x, z, a, m_Size0, m_Size1, flags, m_ControlGroup, m_ControlGroup2);
     850             : 
     851           0 :         fixed s, c;
     852           0 :         sincos_approx(a, s, c);
     853             : 
     854           0 :         for (size_t i = 0; i < m_Shapes.size(); ++i)
     855             :         {
     856           0 :             Shape& b = m_Shapes[i];
     857           0 :             tag_t tag = cmpObstructionManager->AddStaticShape(GetEntityId(),
     858           0 :                 x + b.dx.Multiply(c) + b.dz.Multiply(s), z + b.dz.Multiply(c) - b.dx.Multiply(s), a + b.da, b.size0, b.size1, b.flags, m_ControlGroup, m_ControlGroup2);
     859           0 :             m_ClusterTags.push_back(tag);
     860             :         }
     861             :     }
     862             : 
     863           0 :     inline void RemoveClusterShapes()
     864             :     {
     865           0 :         CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
     866           0 :         if (!cmpObstructionManager)
     867           0 :             return; // error
     868             : 
     869           0 :         for (size_t i = 0; i < m_ClusterTags.size(); ++i)
     870             :         {
     871           0 :             if (m_ClusterTags[i].valid())
     872             :             {
     873           0 :                 cmpObstructionManager->RemoveShape(m_ClusterTags[i]);
     874             :             }
     875             :         }
     876           0 :         m_ClusterTags.clear();
     877             :     }
     878             : 
     879             : };
     880             : 
     881         411 : REGISTER_COMPONENT_TYPE(Obstruction)

Generated by: LCOV version 1.16