LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpUnitMotion.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 529 770 68.7 %
Date: 2026-12-02 01:21:50 Functions: 42 71 59.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             : #ifndef INCLUDED_CCMPUNITMOTION
      19             : #define INCLUDED_CCMPUNITMOTION
      20             : 
      21             : #include "graphics/Color.h"
      22             : #include "graphics/Overlay.h"
      23             : #include "lib/debug.h"
      24             : #include "maths/Fixed.h"
      25             : #include "maths/FixedVector2D.h"
      26             : #include "maths/FixedVector3D.h"
      27             : #include "maths/MathUtil.h"
      28             : #include "ps/CLogger.h"
      29             : #include "ps/Profile.h"
      30             : #include "renderer/Scene.h"
      31             : #include "simulation2/MessageTypes.h"
      32             : #include "simulation2/components/CCmpUnitMotionManager.h"
      33             : #include "simulation2/components/ICmpObstruction.h"
      34             : #include "simulation2/components/ICmpObstructionManager.h"
      35             : #include "simulation2/components/ICmpPathfinder.h"
      36             : #include "simulation2/components/ICmpPosition.h"
      37             : #include "simulation2/components/ICmpUnitMotion.h"
      38             : #include "simulation2/components/ICmpUnitMotionManager.h"
      39             : #include "simulation2/components/ICmpValueModificationManager.h"
      40             : #include "simulation2/components/ICmpVisual.h"
      41             : #include "simulation2/helpers/PathGoal.h"
      42             : #include "simulation2/helpers/Pathfinding.h"
      43             : #include "simulation2/helpers/Position.h"
      44             : #include "simulation2/helpers/Render.h"
      45             : #include "simulation2/serialization/SerializeTemplates.h"
      46             : #include "simulation2/serialization/SerializedPathfinder.h"
      47             : #include "simulation2/serialization/SerializedTypes.h"
      48             : #include "simulation2/system/Component.h"
      49             : #include "simulation2/system/Entity.h"
      50             : #include "simulation2/system/Message.h"
      51             : 
      52             : #include <algorithm>
      53             : #include <cstddef>
      54             : #include <cstdint>
      55             : #include <string>
      56             : #include <utility>
      57             : #include <vector>
      58             : 
      59             : // NB: this implementation of ICmpUnitMotion is very tightly coupled with UnitMotionManager.
      60             : // As such, both are compiled in the same TU.
      61             : 
      62             : // For debugging; units will start going straight to the target
      63             : // instead of calling the pathfinder
      64             : #define DISABLE_PATHFINDER 0
      65             : 
      66             : namespace
      67             : {
      68             : /**
      69             :  * Min/Max range to restrict short path queries to. (Larger ranges are (much) slower,
      70             :  * smaller ranges might miss some legitimate routes around large obstacles.)
      71             :  * NB: keep the max-range in sync with the vertex pathfinder "move the search space" heuristic.
      72             :  */
      73             : constexpr entity_pos_t SHORT_PATH_MIN_SEARCH_RANGE = entity_pos_t::FromInt(12 * Pathfinding::NAVCELL_SIZE_INT);
      74             : constexpr entity_pos_t SHORT_PATH_MAX_SEARCH_RANGE = entity_pos_t::FromInt(56 * Pathfinding::NAVCELL_SIZE_INT);
      75             : constexpr entity_pos_t SHORT_PATH_SEARCH_RANGE_INCREMENT = entity_pos_t::FromInt(4 * Pathfinding::NAVCELL_SIZE_INT);
      76             : constexpr std::uint8_t SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY = 1;
      77             : 
      78             : /**
      79             :  * When using the short-pathfinder to rejoin a long-path waypoint, aim for a circle of this radius around the waypoint.
      80             :  */
      81             : constexpr entity_pos_t SHORT_PATH_LONG_WAYPOINT_RANGE = entity_pos_t::FromInt(4 * Pathfinding::NAVCELL_SIZE_INT);
      82             : 
      83             : /**
      84             :  * Minimum distance to goal for a long path request
      85             :  */
      86             : constexpr entity_pos_t LONG_PATH_MIN_DIST = entity_pos_t::FromInt(16 * Pathfinding::NAVCELL_SIZE_INT);
      87             : 
      88             : /**
      89             :  * If we are this close to our target entity/point, then think about heading
      90             :  * for it in a straight line instead of pathfinding.
      91             :  */
      92             : constexpr entity_pos_t DIRECT_PATH_RANGE = entity_pos_t::FromInt(24 * Pathfinding::NAVCELL_SIZE_INT);
      93             : 
      94             : /**
      95             :  * To avoid recomputing paths too often, have some leeway for target range checks
      96             :  * based on our distance to the target. Increase that incertainty by one navcell
      97             :  * for every this many tiles of distance.
      98             :  */
      99             : constexpr entity_pos_t TARGET_UNCERTAINTY_MULTIPLIER = entity_pos_t::FromInt(8 * Pathfinding::NAVCELL_SIZE_INT);
     100             : 
     101             : /**
     102             :  * When following a known imperfect path (i.e. a path that won't take us in range of our goal
     103             :  * we still recompute a new path every N turn to adapt to moving targets (for example, ships that must pickup
     104             :  * units may easily end up in this state, they still need to adjust to moving units).
     105             :  * This is rather arbitrary and mostly for simplicity & optimisation (a better recomputing algorithm
     106             :  * would not need this).
     107             :  */
     108             : constexpr std::uint8_t KNOWN_IMPERFECT_PATH_RESET_COUNTDOWN = 12;
     109             : 
     110             : /**
     111             :  * When we fail to move this many turns in a row, inform other components that the move will fail.
     112             :  * Experimentally, this number needs to be somewhat high or moving groups of units will lead to stuck units.
     113             :  * However, too high means units will look idle for a long time when they are failing to move.
     114             :  * TODO: if UnitMotion could send differentiated "unreachable" and "currently stuck" failing messages,
     115             :  * this could probably be lowered.
     116             :  */
     117             : constexpr std::uint8_t MAX_FAILED_MOVEMENTS = 35;
     118             : 
     119             : /**
     120             :  * When computing paths but failing to move, we want to occasionally alternate pathfinder systems
     121             :  * to avoid getting stuck (the short pathfinder can unstuck the long-range one and vice-versa, depending).
     122             :  */
     123             : constexpr std::uint8_t ALTERNATE_PATH_TYPE_DELAY = 3;
     124             : constexpr std::uint8_t ALTERNATE_PATH_TYPE_EVERY = 6;
     125             : 
     126             : /**
     127             :  * Units can occasionally get stuck near corners. The cause is a mismatch between CheckMovement and the short pathfinder.
     128             :  * The problem is the short pathfinder finds an impassable path when units are right on an obstruction edge.
     129             :  * Fixing this math mismatch is perhaps possible, but fixing it in UM is rather easy: just try backing up a bit
     130             :  * and that will probably un-stuck the unit. This is the 'failed movement' turn on which to try that.
     131             :  */
     132             : constexpr std::uint8_t BACKUP_HACK_DELAY = 10;
     133             : 
     134             : /**
     135             :  * After this many failed computations, start sending "VERY_OBSTRUCTED" messages instead.
     136             :  * Should probably be larger than ALTERNATE_PATH_TYPE_DELAY.
     137             :  */
     138             : constexpr std::uint8_t VERY_OBSTRUCTED_THRESHOLD = 10;
     139             : 
     140             : struct PathColorPalette
     141             : {
     142             :     CColor longPath;
     143             :     CColor shortPath;
     144             : };
     145             : 
     146             : constexpr PathColorPalette REGULAR_UNIT_PALETTE{{1, 1, 1, 1}, {1, 0, 0, 1}};
     147             : constexpr PathColorPalette FORMATION_CONTROLLER_PALETTE{{0, 0, 1, 1}, {0, 1, 0, 1}};
     148             : } // anonymous namespace
     149             : 
     150         189 : class CCmpUnitMotion final : public ICmpUnitMotion
     151             : {
     152             :     friend class CCmpUnitMotionManager;
     153             : public:
     154         137 :     static void ClassInit(CComponentManager& componentManager)
     155             :     {
     156         137 :         componentManager.SubscribeToMessageType(MT_Create);
     157         137 :         componentManager.SubscribeToMessageType(MT_Destroy);
     158         137 :         componentManager.SubscribeToMessageType(MT_PathResult);
     159         137 :         componentManager.SubscribeToMessageType(MT_OwnershipChanged);
     160         137 :         componentManager.SubscribeToMessageType(MT_ValueModification);
     161         137 :         componentManager.SubscribeToMessageType(MT_MovementObstructionChanged);
     162         137 :         componentManager.SubscribeToMessageType(MT_Deserialized);
     163         137 :     }
     164             : 
     165         378 :     DEFAULT_COMPONENT_ALLOCATOR(UnitMotion)
     166             : 
     167             :     bool m_DebugOverlayEnabled;
     168             :     std::vector<SOverlayLine> m_DebugOverlayLongPathLines;
     169             :     std::vector<SOverlayLine> m_DebugOverlayShortPathLines;
     170             : 
     171             :     // Template state:
     172             : 
     173             :     bool m_IsFormationController;
     174             : 
     175             :     fixed m_TemplateWalkSpeed, m_TemplateRunMultiplier, m_TemplateAcceleration, m_TemplateWeight;
     176             :     pass_class_t m_PassClass;
     177             :     std::string m_PassClassName;
     178             : 
     179             :     // Dynamic state:
     180             : 
     181             :     entity_pos_t m_Clearance;
     182             : 
     183             :     // cached for efficiency
     184             :     fixed m_WalkSpeed, m_RunMultiplier;
     185             : 
     186             :     bool m_FacePointAfterMove;
     187             : 
     188             :     // Whether the unit participates in pushing.
     189             :     bool m_Pushing = false;
     190             : 
     191             :     // Whether the unit blocks movement (& is blocked by movement blockers)
     192             :     // Cached from ICmpObstruction.
     193             :     bool m_BlockMovement = false;
     194             : 
     195             :     // Internal counter used when recovering from obstructed movement.
     196             :     // Most notably, increases the search range of the vertex pathfinder.
     197             :     // See HandleObstructedMove() for more details.
     198             :     std::uint8_t m_FailedMovements = 0;
     199             : 
     200             :     // If > 0, PathingUpdateNeeded returns false always.
     201             :     // This exists because the goal may be unreachable to the short/long pathfinder.
     202             :     // In such cases, we would compute inacceptable paths and PathingUpdateNeeded would trigger every turn,
     203             :     // which would be quite bad for performance.
     204             :     // To avoid that, when we know the new path is imperfect, treat it as OK and follow it anyways.
     205             :     // When reaching the end, we'll go through HandleObstructedMove and reset regardless.
     206             :     // To still recompute now and then (the target may be moving), this is a countdown decremented on each frame.
     207             :     std::uint8_t m_FollowKnownImperfectPathCountdown = 0;
     208             : 
     209             :     struct Ticket {
     210             :         std::uint32_t m_Ticket = 0; // asynchronous request ID we're waiting for, or 0 if none
     211             :         enum Type {
     212             :             SHORT_PATH,
     213             :             LONG_PATH
     214             :         } m_Type = SHORT_PATH; // Pick some default value to avoid UB.
     215             : 
     216        1155 :         void clear() { m_Ticket = 0; }
     217             :     } m_ExpectedPathTicket;
     218             : 
     219             :     struct MoveRequest {
     220             :         enum Type {
     221             :             NONE,
     222             :             POINT,
     223             :             ENTITY,
     224             :             OFFSET
     225             :         } m_Type = NONE;
     226             :         entity_id_t m_Entity = INVALID_ENTITY;
     227             :         CFixedVector2D m_Position;
     228             :         entity_pos_t m_MinRange, m_MaxRange;
     229             : 
     230             :         // For readability
     231           0 :         CFixedVector2D GetOffset() const { return m_Position; };
     232             : 
     233         282 :         MoveRequest() = default;
     234          60 :         MoveRequest(CFixedVector2D pos, entity_pos_t minRange, entity_pos_t maxRange) : m_Type(POINT), m_Position(pos), m_MinRange(minRange), m_MaxRange(maxRange) {};
     235         357 :         MoveRequest(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) : m_Type(ENTITY), m_Entity(target), m_MinRange(minRange), m_MaxRange(maxRange) {};
     236           0 :         MoveRequest(entity_id_t target, CFixedVector2D offset) : m_Type(OFFSET), m_Entity(target), m_Position(offset) {};
     237             :     } m_MoveRequest;
     238             : 
     239             :     // If this is not INVALID_ENTITY, the unit is a formation member.
     240             :     entity_id_t m_FormationController = INVALID_ENTITY;
     241             : 
     242             :     // If the entity moves, it will do so at m_WalkSpeed * m_SpeedMultiplier.
     243             :     fixed m_SpeedMultiplier;
     244             :     // This caches the resulting speed from m_WalkSpeed * m_SpeedMultiplier for convenience.
     245             :     fixed m_Speed;
     246             : 
     247             :     // Mean speed over the last turn.
     248             :     fixed m_LastTurnSpeed;
     249             : 
     250             :     // The speed achieved at the end of the current turn.
     251             :     fixed m_CurrentSpeed;
     252             : 
     253             :     fixed m_InstantTurnAngle;
     254             : 
     255             :     fixed m_Acceleration;
     256             : 
     257             :     // Currently active paths (storing waypoints in reverse order).
     258             :     // The last item in each path is the point we're currently heading towards.
     259             :     WaypointPath m_LongPath;
     260             :     WaypointPath m_ShortPath;
     261             : 
     262         137 :     static std::string GetSchema()
     263             :     {
     264         137 :         return
     265             :             "<a:help>Provides the unit with the ability to move around the world by itself.</a:help>"
     266             :             "<a:example>"
     267             :                 "<WalkSpeed>7.0</WalkSpeed>"
     268             :                 "<PassabilityClass>default</PassabilityClass>"
     269             :             "</a:example>"
     270             :             "<element name='FormationController'>"
     271             :                 "<data type='boolean'/>"
     272             :             "</element>"
     273             :             "<element name='WalkSpeed' a:help='Basic movement speed (in meters per second).'>"
     274             :                 "<ref name='positiveDecimal'/>"
     275             :             "</element>"
     276             :             "<optional>"
     277             :                 "<element name='RunMultiplier' a:help='How much faster the unit goes when running (as a multiple of walk speed).'>"
     278             :                     "<ref name='positiveDecimal'/>"
     279             :                 "</element>"
     280             :             "</optional>"
     281             :             "<element name='InstantTurnAngle' a:help='Angle we can turn instantly. Any value greater than pi will disable turning times. Avoid zero since it stops the entity every turn.'>"
     282             :                 "<ref name='positiveDecimal'/>"
     283             :             "</element>"
     284             :             "<element name='Acceleration' a:help='Acceleration (in meters per second^2).'>"
     285             :                 "<ref name='positiveDecimal'/>"
     286             :             "</element>"
     287             :             "<element name='PassabilityClass' a:help='Identifies the terrain passability class (values are defined in special/pathfinder.xml).'>"
     288             :                 "<text/>"
     289             :             "</element>"
     290             :             "<element name='Weight' a:help='Makes this unit both push harder and harder to push. 10 is considered the base value.'>"
     291             :                 "<ref name='positiveDecimal'/>"
     292             :             "</element>"
     293             :             "<optional>"
     294             :                 "<element name='DisablePushing'>"
     295             :                     "<data type='boolean'/>"
     296             :                 "</element>"
     297         137 :             "</optional>";
     298             :     }
     299             : 
     300         189 :     void Init(const CParamNode& paramNode) override
     301             :     {
     302         189 :         m_IsFormationController = paramNode.GetChild("FormationController").ToBool();
     303             : 
     304         189 :         m_FacePointAfterMove = true;
     305             : 
     306         189 :         m_WalkSpeed = m_TemplateWalkSpeed = m_Speed = paramNode.GetChild("WalkSpeed").ToFixed();
     307         189 :         m_SpeedMultiplier = fixed::FromInt(1);
     308         189 :         m_LastTurnSpeed = m_CurrentSpeed = fixed::Zero();
     309             : 
     310         189 :         m_RunMultiplier = m_TemplateRunMultiplier = fixed::FromInt(1);
     311         189 :         if (paramNode.GetChild("RunMultiplier").IsOk())
     312         189 :             m_RunMultiplier = m_TemplateRunMultiplier = paramNode.GetChild("RunMultiplier").ToFixed();
     313             : 
     314         189 :         m_InstantTurnAngle = paramNode.GetChild("InstantTurnAngle").ToFixed();
     315             : 
     316         189 :         m_Acceleration = m_TemplateAcceleration = paramNode.GetChild("Acceleration").ToFixed();
     317             : 
     318         189 :         m_TemplateWeight = paramNode.GetChild("Weight").ToFixed();
     319             : 
     320         189 :         m_PassClassName = paramNode.GetChild("PassabilityClass").ToString();
     321         189 :         SetPassabilityData(m_PassClassName);
     322             : 
     323         189 :         CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
     324         189 :         if (cmpObstruction)
     325         189 :             m_BlockMovement = cmpObstruction->GetBlockMovementFlag(true);
     326             : 
     327         378 :         SetParticipateInPushing(!paramNode.GetChild("DisablePushing").IsOk() || !paramNode.GetChild("DisablePushing").ToBool());
     328             : 
     329         189 :         m_DebugOverlayEnabled = false;
     330         189 :     }
     331             : 
     332         189 :     void Deinit() override
     333             :     {
     334         189 :     }
     335             : 
     336             :     template<typename S>
     337        1020 :     void SerializeCommon(S& serialize)
     338             :     {
     339             :         // m_Clearance and m_PassClass are constructed from this.
     340        1020 :         serialize.StringASCII("pass class", m_PassClassName, 0, 64);
     341             : 
     342        1020 :         serialize.NumberU32_Unbounded("ticket", m_ExpectedPathTicket.m_Ticket);
     343        1020 :         Serializer(serialize, "ticket type", m_ExpectedPathTicket.m_Type, Ticket::Type::LONG_PATH);
     344             : 
     345        1020 :         serialize.NumberU8_Unbounded("failed movements", m_FailedMovements);
     346        1020 :         serialize.NumberU8_Unbounded("followknownimperfectpath", m_FollowKnownImperfectPathCountdown);
     347             : 
     348        1020 :         Serializer(serialize, "target type", m_MoveRequest.m_Type, MoveRequest::Type::OFFSET);
     349        1020 :         serialize.NumberU32_Unbounded("target entity", m_MoveRequest.m_Entity);
     350        1020 :         serialize.NumberFixed_Unbounded("target pos x", m_MoveRequest.m_Position.X);
     351        1020 :         serialize.NumberFixed_Unbounded("target pos y", m_MoveRequest.m_Position.Y);
     352        1020 :         serialize.NumberFixed_Unbounded("target min range", m_MoveRequest.m_MinRange);
     353        1020 :         serialize.NumberFixed_Unbounded("target max range", m_MoveRequest.m_MaxRange);
     354             : 
     355        1020 :         serialize.NumberU32_Unbounded("formation controller", m_FormationController);
     356             : 
     357        1020 :         serialize.NumberFixed_Unbounded("speed multiplier", m_SpeedMultiplier);
     358             : 
     359        1020 :         serialize.NumberFixed_Unbounded("last turn speed", m_LastTurnSpeed);
     360        1020 :         serialize.NumberFixed_Unbounded("current speed", m_CurrentSpeed);
     361             : 
     362        1020 :         serialize.NumberFixed_Unbounded("instant turn angle", m_InstantTurnAngle);
     363             : 
     364        1020 :         serialize.NumberFixed_Unbounded("acceleration", m_Acceleration);
     365             : 
     366        1020 :         serialize.Bool("facePointAfterMove", m_FacePointAfterMove);
     367        1020 :         serialize.Bool("pushing", m_Pushing);
     368             : 
     369        1020 :         Serializer(serialize, "long path", m_LongPath.m_Waypoints);
     370        1020 :         Serializer(serialize, "short path", m_ShortPath.m_Waypoints);
     371        1020 :     }
     372             : 
     373        1020 :     void Serialize(ISerializer& serialize) override
     374             :     {
     375        1020 :         SerializeCommon(serialize);
     376        1020 :     }
     377             : 
     378           0 :     void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
     379             :     {
     380           0 :         Init(paramNode);
     381             : 
     382           0 :         SerializeCommon(deserialize);
     383             : 
     384           0 :         SetPassabilityData(m_PassClassName);
     385             : 
     386           0 :         CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
     387           0 :         if (cmpObstruction)
     388           0 :             m_BlockMovement = cmpObstruction->GetBlockMovementFlag(false);
     389           0 :     }
     390             : 
     391        1569 :     void HandleMessage(const CMessage& msg, bool /*global*/) override
     392             :     {
     393        1569 :         switch (msg.GetType())
     394             :         {
     395           0 :         case MT_RenderSubmit:
     396           0 :         {
     397           0 :             PROFILE("UnitMotion::RenderSubmit");
     398           0 :             const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
     399           0 :             RenderSubmit(msgData.collector);
     400           0 :             break;
     401           0 :         }
     402         951 :         case MT_PathResult:
     403         951 :         {
     404         951 :             const CMessagePathResult& msgData = static_cast<const CMessagePathResult&> (msg);
     405         951 :             PathResult(msgData.ticket, msgData.path);
     406         951 :             break;
     407             :         }
     408         189 :         case MT_Create:
     409         189 :         {
     410         189 :             if (!ENTITY_IS_LOCAL(GetEntityId()))
     411         360 :                 CmpPtr<ICmpUnitMotionManager>(GetSystemEntity())->Register(this, GetEntityId(), m_IsFormationController);
     412             :             break;
     413             :         }
     414          30 :         case MT_Destroy:
     415          30 :         {
     416          30 :             if (!ENTITY_IS_LOCAL(GetEntityId()))
     417          60 :                 CmpPtr<ICmpUnitMotionManager>(GetSystemEntity())->Unregister(GetEntityId());
     418             :             break;
     419             :         }
     420           0 :         case MT_MovementObstructionChanged:
     421           0 :         {
     422           0 :             CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
     423           0 :             if (cmpObstruction)
     424           0 :                 m_BlockMovement = cmpObstruction->GetBlockMovementFlag(false);
     425             :             break;
     426             :         }
     427         180 :         case MT_ValueModification:
     428         180 :         {
     429         180 :             const CMessageValueModification& msgData = static_cast<const CMessageValueModification&> (msg);
     430         180 :             if (msgData.component != L"UnitMotion")
     431             :                 break;
     432         219 :             [[fallthrough]];
     433             :         }
     434         219 :         case MT_OwnershipChanged:
     435         219 :         {
     436         219 :             OnValueModification();
     437         219 :             break;
     438             :         }
     439           0 :         case MT_Deserialized:
     440           0 :         {
     441           0 :             OnValueModification();
     442           0 :             break;
     443             :         }
     444             :         }
     445        1569 :     }
     446             : 
     447           0 :     void UpdateMessageSubscriptions()
     448             :     {
     449           0 :         bool needRender = m_DebugOverlayEnabled;
     450           0 :         GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_RenderSubmit, this, needRender);
     451           0 :     }
     452             : 
     453       16317 :     bool IsMoveRequested() const override
     454             :     {
     455       16317 :         return m_MoveRequest.m_Type != MoveRequest::NONE;
     456             :     }
     457             : 
     458        6969 :     bool IsMovingAsFormation() const override
     459             :     {
     460           0 :         return IsFormationMember() && m_MoveRequest.m_Type == MoveRequest::OFFSET;
     461             :     }
     462             : 
     463           0 :     fixed GetSpeedMultiplier() const override
     464             :     {
     465           0 :         return m_SpeedMultiplier;
     466             :     }
     467             : 
     468         600 :     void SetSpeedMultiplier(fixed multiplier) override
     469             :     {
     470         381 :         m_SpeedMultiplier = std::min(multiplier, m_RunMultiplier);
     471         600 :         m_Speed = m_SpeedMultiplier.Multiply(GetWalkSpeed());
     472         381 :     }
     473             : 
     474           0 :     fixed GetSpeed() const override
     475             :     {
     476           0 :         return m_Speed;
     477             :     }
     478             : 
     479         600 :     fixed GetWalkSpeed() const override
     480             :     {
     481         219 :         return m_WalkSpeed;
     482             :     }
     483             : 
     484          99 :     fixed GetRunMultiplier() const override
     485             :     {
     486          99 :         return m_RunMultiplier;
     487             :     }
     488             : 
     489          36 :     CFixedVector2D EstimateFuturePosition(const fixed dt) const override
     490             :     {
     491          36 :         CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     492          36 :         if (!cmpPosition || !cmpPosition->IsInWorld())
     493           0 :             return CFixedVector2D();
     494             : 
     495             :         // TODO: formation members should perhaps try to use the controller's position.
     496             : 
     497          36 :         CFixedVector2D pos = cmpPosition->GetPosition2D();
     498          36 :         entity_angle_t angle = cmpPosition->GetRotation().Y;
     499          36 :         fixed speed = m_CurrentSpeed;
     500             :         // Copy the path so we don't change it.
     501          36 :         WaypointPath shortPath = m_ShortPath;
     502          36 :         WaypointPath longPath = m_LongPath;
     503             : 
     504          36 :         PerformMove(dt, cmpPosition->GetTurnRate(), shortPath, longPath, pos, speed, angle, 0);
     505          36 :         return pos;
     506          72 :     }
     507             : 
     508           0 :     fixed GetAcceleration() const override
     509             :     {
     510           0 :         return m_Acceleration;
     511             :     }
     512             : 
     513           0 :     void SetAcceleration(fixed acceleration) override
     514             :     {
     515           0 :         m_Acceleration = acceleration;
     516           0 :     }
     517             : 
     518          78 :     entity_pos_t GetWeight() const
     519             :     {
     520          78 :         return m_TemplateWeight;
     521             :     }
     522             : 
     523           0 :     pass_class_t GetPassabilityClass() const override
     524             :     {
     525           0 :         return m_PassClass;
     526             :     }
     527             : 
     528           0 :     std::string GetPassabilityClassName() const override
     529             :     {
     530           0 :         return m_PassClassName;
     531             :     }
     532             : 
     533           0 :     void SetPassabilityClassName(const std::string& passClassName) override
     534             :     {
     535           0 :         if (!m_IsFormationController)
     536             :         {
     537           0 :             LOGWARNING("Only formation controllers can change their passability class");
     538           0 :             return;
     539             :         }
     540           0 :         SetPassabilityData(passClassName);
     541             :     }
     542             : 
     543        8118 :     fixed GetCurrentSpeed() const override
     544             :     {
     545        8118 :         return m_CurrentSpeed;
     546             :     }
     547             : 
     548           0 :     void SetCurrentSpeed(const fixed& speed) override
     549             :     {
     550           0 :         m_CurrentSpeed = speed;
     551             : 
     552           0 :         if (speed == fixed::Zero())
     553           0 :             m_LastTurnSpeed = fixed::Zero();
     554             :         else
     555           0 :             m_LastTurnSpeed = speed;
     556           0 :     }
     557             : 
     558           0 :     void SetFacePointAfterMove(bool facePointAfterMove) override
     559             :     {
     560           0 :         m_FacePointAfterMove = facePointAfterMove;
     561           0 :     }
     562             : 
     563           0 :     bool GetFacePointAfterMove() const override
     564             :     {
     565           0 :         return m_FacePointAfterMove;
     566             :     }
     567             : 
     568           0 :     void SetDebugOverlay(bool enabled) override
     569             :     {
     570           0 :         m_DebugOverlayEnabled = enabled;
     571           0 :         UpdateMessageSubscriptions();
     572           0 :     }
     573             : 
     574          60 :     bool MoveToPointRange(entity_pos_t x, entity_pos_t z, entity_pos_t minRange, entity_pos_t maxRange) override
     575             :     {
     576          60 :         return MoveTo(MoveRequest(CFixedVector2D(x, z), minRange, maxRange));
     577             :     }
     578             : 
     579         357 :     bool MoveToTargetRange(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) override
     580             :     {
     581         357 :         return MoveTo(MoveRequest(target, minRange, maxRange));
     582             :     }
     583             : 
     584           0 :     void MoveToFormationOffset(entity_id_t controller, entity_pos_t x, entity_pos_t z) override
     585             :     {
     586             :         // Pass the controller to the move request anyways.
     587           0 :         MoveTo(MoveRequest(controller, CFixedVector2D(x, z)));
     588           0 :     }
     589             : 
     590           0 :     void SetMemberOfFormation(entity_id_t controller) override
     591             :     {
     592           0 :         m_FormationController = controller;
     593           0 :     }
     594             : 
     595           0 :     std::optional<CFixedVector2D> GetFormationOffset() const override
     596             :     {
     597           0 :         if (m_MoveRequest.m_Type != MoveRequest::OFFSET)
     598           0 :             return std::nullopt;
     599             : 
     600           0 :         return m_MoveRequest.m_Position;
     601             :     }
     602             : 
     603             :     bool IsTargetRangeReachable(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) override;
     604             : 
     605             :     void FaceTowardsPoint(entity_pos_t x, entity_pos_t z) override;
     606             : 
     607             :     /**
     608             :      * Clears the current MoveRequest - the unit will stop and no longer try and move.
     609             :      * This should never be called from UnitMotion, since MoveToX orders are given
     610             :      * by other components - these components should also decide when to stop.
     611             :      */
     612         282 :     void StopMoving() override
     613             :     {
     614         282 :         if (m_FacePointAfterMove)
     615             :         {
     616         282 :             CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     617         282 :             if (cmpPosition && cmpPosition->IsInWorld())
     618             :             {
     619         282 :                 CFixedVector2D targetPos;
     620         282 :                 if (ComputeTargetPosition(targetPos))
     621         273 :                     FaceTowardsPointFromPos(cmpPosition->GetPosition2D(), targetPos.X, targetPos.Y);
     622             :             }
     623             :         }
     624             : 
     625         282 :         m_MoveRequest = MoveRequest();
     626         282 :         m_ExpectedPathTicket.clear();
     627         282 :         m_LongPath.m_Waypoints.clear();
     628         282 :         m_ShortPath.m_Waypoints.clear();
     629         282 :     }
     630             : 
     631           0 :     entity_pos_t GetUnitClearance() const override
     632             :     {
     633           0 :         return m_Clearance;
     634             :     }
     635             : 
     636             : private:
     637       38463 :     bool IsFormationMember() const
     638             :     {
     639           0 :         return m_FormationController != INVALID_ENTITY;
     640             :     }
     641             : 
     642           0 :     bool IsFormationControllerMoving() const
     643             :     {
     644           0 :         CmpPtr<ICmpUnitMotion> cmpControllerMotion(GetSimContext(), m_FormationController);
     645           0 :         return cmpControllerMotion && cmpControllerMotion->IsMoveRequested();
     646             :     }
     647             : 
     648       14652 :     entity_id_t GetGroup() const
     649             :     {
     650       14652 :         return IsFormationMember() ? m_FormationController : GetEntityId();
     651             :     }
     652             : 
     653         189 :     void SetParticipateInPushing(bool pushing)
     654             :     {
     655         189 :         CmpPtr<ICmpUnitMotionManager> cmpUnitMotionManager(GetSystemEntity());
     656         189 :         m_Pushing = pushing && cmpUnitMotionManager->IsPushingActivated();
     657         189 :     }
     658             : 
     659         189 :     void SetPassabilityData(const std::string& passClassName)
     660             :     {
     661         189 :         m_PassClassName = passClassName;
     662         189 :         CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
     663         189 :         if (cmpPathfinder)
     664             :         {
     665         189 :             m_PassClass = cmpPathfinder->GetPassabilityClass(passClassName);
     666         189 :             m_Clearance = cmpPathfinder->GetClearance(m_PassClass);
     667             : 
     668         189 :             CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
     669         189 :             if (cmpObstruction)
     670         189 :                 cmpObstruction->SetUnitClearance(m_Clearance);
     671             :         }
     672         189 :     }
     673             : 
     674             :     /**
     675             :      * Warns other components that our current movement will likely fail (e.g. we won't be able to reach our target)
     676             :      * This should only be called before the actual movement in a given turn, or units might both move and try to do things
     677             :      * on the same turn, leading to gliding units.
     678             :      */
     679           0 :     void MoveFailed()
     680             :     {
     681             :         // Don't notify if we are a formation member in a moving formation - we can occasionally be stuck for a long time
     682             :         // if our current offset is unreachable, but we don't want to end up stuck.
     683             :         // (If the formation controller has stopped moving however, we can safely message).
     684           0 :         if (IsFormationMember() && IsFormationControllerMoving())
     685           0 :             return;
     686             : 
     687           0 :         CMessageMotionUpdate msg(CMessageMotionUpdate::LIKELY_FAILURE);
     688           0 :         GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
     689           0 :     }
     690             : 
     691             :     /**
     692             :      * Warns other components that our current movement is likely over (i.e. we probably reached our destination)
     693             :      * This should only be called before the actual movement in a given turn, or units might both move and try to do things
     694             :      * on the same turn, leading to gliding units.
     695             :      */
     696         252 :     void MoveSucceeded()
     697             :     {
     698             :         // Don't notify if we are a formation member in a moving formation - we can occasionally be stuck for a long time
     699             :         // if our current offset is unreachable, but we don't want to end up stuck.
     700             :         // (If the formation controller has stopped moving however, we can safely message).
     701         252 :         if (IsFormationMember() && IsFormationControllerMoving())
     702           0 :             return;
     703             : 
     704         252 :         CMessageMotionUpdate msg(CMessageMotionUpdate::LIKELY_SUCCESS);
     705         252 :         GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
     706         252 :     }
     707             : 
     708             :     /**
     709             :      * Warns other components that our current movement was obstructed (i.e. we failed to move this turn).
     710             :      * This should only be called before the actual movement in a given turn, or units might both move and try to do things
     711             :      * on the same turn, leading to gliding units.
     712             :      */
     713         240 :     void MoveObstructed()
     714             :     {
     715             :         // Don't notify if we are a formation member in a moving formation - we can occasionally be stuck for a long time
     716             :         // if our current offset is unreachable, but we don't want to end up stuck.
     717             :         // (If the formation controller has stopped moving however, we can safely message).
     718         240 :         if (IsFormationMember() && IsFormationControllerMoving())
     719           0 :             return;
     720             : 
     721         240 :         CMessageMotionUpdate msg(m_FailedMovements >= VERY_OBSTRUCTED_THRESHOLD ?
     722         240 :             CMessageMotionUpdate::VERY_OBSTRUCTED : CMessageMotionUpdate::OBSTRUCTED);
     723         240 :         GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
     724         240 :     }
     725             : 
     726             :     /**
     727             :      * Increment the number of failed movements and notify other components if required.
     728             :      * @returns true if the failure was notified, false otherwise.
     729             :      */
     730         570 :     bool IncrementFailedMovementsAndMaybeNotify()
     731             :     {
     732         570 :         m_FailedMovements++;
     733         570 :         if (m_FailedMovements >= MAX_FAILED_MOVEMENTS)
     734             :         {
     735           0 :             MoveFailed();
     736           0 :             m_FailedMovements = 0;
     737           0 :             return true;
     738             :         }
     739             :         return false;
     740             :     }
     741             : 
     742             :     /**
     743             :      * If path would take us farther away from the goal than pos currently is, return false, else return true.
     744             :      */
     745             :     bool RejectFartherPaths(const PathGoal& goal, const WaypointPath& path, const CFixedVector2D& pos) const;
     746             : 
     747        1659 :     bool ShouldAlternatePathfinder() const
     748             :     {
     749        1659 :         return (m_FailedMovements == ALTERNATE_PATH_TYPE_DELAY) || ((m_FailedMovements - ALTERNATE_PATH_TYPE_DELAY) % ALTERNATE_PATH_TYPE_EVERY == 0);
     750             :     }
     751             : 
     752         705 :     bool InShortPathRange(const PathGoal& goal, const CFixedVector2D& pos) const
     753             :     {
     754        1410 :         return goal.DistanceToPoint(pos) < LONG_PATH_MIN_DIST;
     755             :     }
     756             : 
     757          78 :     entity_pos_t ShortPathSearchRange() const
     758             :     {
     759          78 :         std::uint8_t multiple = m_FailedMovements < SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY ? 0 :
     760             :             m_FailedMovements - SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY;
     761          78 :         fixed searchRange = SHORT_PATH_MIN_SEARCH_RANGE + SHORT_PATH_SEARCH_RANGE_INCREMENT * multiple;
     762          78 :         if (searchRange > SHORT_PATH_MAX_SEARCH_RANGE)
     763             :             searchRange = SHORT_PATH_MAX_SEARCH_RANGE;
     764          78 :         return searchRange;
     765             :     }
     766             : 
     767             :     /**
     768             :      * Handle the result of an asynchronous path query.
     769             :      */
     770             :     void PathResult(std::uint32_t ticket, const WaypointPath& path);
     771             : 
     772         219 :     void OnValueModification()
     773             :     {
     774         219 :         CmpPtr<ICmpValueModificationManager> cmpValueModificationManager(GetSystemEntity());
     775         219 :         if (!cmpValueModificationManager)
     776         219 :             return;
     777             : 
     778         219 :         m_WalkSpeed = cmpValueModificationManager->ApplyModifications(L"UnitMotion/WalkSpeed", m_TemplateWalkSpeed, GetEntityId());
     779         219 :         m_RunMultiplier = cmpValueModificationManager->ApplyModifications(L"UnitMotion/RunMultiplier", m_TemplateRunMultiplier, GetEntityId());
     780             : 
     781             :         // For MT_Deserialize compute m_Speed from the serialized m_SpeedMultiplier.
     782             :         // For MT_ValueModification and MT_OwnershipChanged, adjust m_SpeedMultiplier if needed
     783             :         // (in case then new m_RunMultiplier value is lower than the old).
     784         219 :         SetSpeedMultiplier(m_SpeedMultiplier);
     785             :     }
     786             : 
     787             :     /**
     788             :      * Check if we are at destination early in the turn, this both lets units react faster
     789             :      * and ensure that distance comparisons are done while units are not being moved
     790             :      * (otherwise they won't be commutative).
     791             :      */
     792             :     void OnTurnStart();
     793             : 
     794             :     void PreMove(CCmpUnitMotionManager::MotionState& state);
     795             :     void Move(CCmpUnitMotionManager::MotionState& state, fixed dt);
     796             :     void PostMove(CCmpUnitMotionManager::MotionState& state, fixed dt);
     797             : 
     798             :     bool PossiblyAtDestination() const override;
     799             : 
     800             :     /**
     801             :      * Process the move the unit will do this turn.
     802             :      * This does not send actually change the position.
     803             :      * @returns true if the move was obstructed.
     804             :      */
     805             :     bool PerformMove(fixed dt, const fixed& turnRate, WaypointPath& shortPath, WaypointPath& longPath, CFixedVector2D& pos, fixed& speed, entity_angle_t& angle, uint8_t pushingPressure) const;
     806             : 
     807             :     /**
     808             :      * Update other components on our speed.
     809             :      * (For performance, this should try to avoid sending messages).
     810             :      */
     811             :     void UpdateMovementState(entity_pos_t speed, entity_pos_t meanSpeed);
     812             : 
     813             :     /**
     814             :      * React if our move was obstructed.
     815             :      * @param moved - true if the unit still managed to move.
     816             :      * @returns true if the obstruction required handling, false otherwise.
     817             :      */
     818             :     bool HandleObstructedMove(bool moved);
     819             : 
     820             :     /**
     821             :      * Returns true if the target position is valid. False otherwise.
     822             :      * (this may indicate that the target is e.g. out of the world/dead).
     823             :      * NB: for code-writing convenience, if we have no target, this returns true.
     824             :      */
     825             :     bool TargetHasValidPosition(const MoveRequest& moveRequest) const;
     826        7686 :     bool TargetHasValidPosition() const
     827             :     {
     828        7686 :         return TargetHasValidPosition(m_MoveRequest);
     829             :     }
     830             : 
     831             :     /**
     832             :      * Computes the current location of our target entity (plus offset).
     833             :      * Returns false if no target entity or no valid position.
     834             :      */
     835             :     bool ComputeTargetPosition(CFixedVector2D& out, const MoveRequest& moveRequest) const;
     836       16335 :     bool ComputeTargetPosition(CFixedVector2D& out) const
     837             :     {
     838         282 :         return ComputeTargetPosition(out, m_MoveRequest);
     839             :     }
     840             : 
     841             :     /**
     842             :      * Attempts to replace the current path with a straight line to the target,
     843             :      * if it's close enough and the route is not obstructed.
     844             :      */
     845             :     bool TryGoingStraightToTarget(const CFixedVector2D& from, bool updatePaths);
     846             : 
     847             :     /**
     848             :      * Returns whether our we need to recompute a path to reach our target.
     849             :      */
     850             :     bool PathingUpdateNeeded(const CFixedVector2D& from) const;
     851             : 
     852             :     /**
     853             :      * Rotate to face towards the target point, given the current pos
     854             :      */
     855             :     void FaceTowardsPointFromPos(const CFixedVector2D& pos, entity_pos_t x, entity_pos_t z);
     856             : 
     857             :     /**
     858             :      * Units in 'pushing' mode are marked as 'moving' in the obstruction manager.
     859             :      * Units in 'pushing' mode should skip them in checkMovement (to enable pushing).
     860             :      * However, units for which pushing is deactivated should collide against everyone.
     861             :      * Units that don't block movement never participate in pushing, but they also
     862             :      * shouldn't collide with pushing units.
     863             :      */
     864       14652 :     bool ShouldCollideWithMovingUnits() const
     865             :     {
     866           0 :         return !m_Pushing && m_BlockMovement;
     867             :     }
     868             : 
     869             :     /**
     870             :      * Returns an appropriate obstruction filter for use with path requests.
     871             :      */
     872         867 :     ControlGroupMovementObstructionFilter GetObstructionFilter() const
     873             :     {
     874         867 :         return ControlGroupMovementObstructionFilter(ShouldCollideWithMovingUnits(), GetGroup());
     875             :     }
     876             :     /**
     877             :      * Filter a specific tag on top of the existing control groups.
     878             :      */
     879       13785 :     SkipTagAndControlGroupObstructionFilter GetObstructionFilter(const ICmpObstructionManager::tag_t& tag) const
     880             :     {
     881       17088 :         return SkipTagAndControlGroupObstructionFilter(tag, ShouldCollideWithMovingUnits(), GetGroup());
     882             :     }
     883             : 
     884             :     /**
     885             :      * Decide whether to approximate the given range from a square target as a circle,
     886             :      * rather than as a square.
     887             :      */
     888             :     bool ShouldTreatTargetAsCircle(entity_pos_t range, entity_pos_t circleRadius) const;
     889             : 
     890             :     /**
     891             :      * Create a PathGoal from a move request.
     892             :      * @returns true if the goal was successfully created.
     893             :      */
     894             :     bool ComputeGoal(PathGoal& out, const MoveRequest& moveRequest) const;
     895             : 
     896             :     /**
     897             :      * Compute a path to the given goal from the given position.
     898             :      * Might go in a straight line immediately, or might start an asynchronous path request.
     899             :      */
     900             :     void ComputePathToGoal(const CFixedVector2D& from, const PathGoal& goal);
     901             : 
     902             :     /**
     903             :      * Start an asynchronous long path query.
     904             :      */
     905             :     void RequestLongPath(const CFixedVector2D& from, const PathGoal& goal);
     906             : 
     907             :     /**
     908             :      * Start an asynchronous short path query.
     909             :      * @param extendRange - if true, extend the search range to at least the distance to the goal.
     910             :      */
     911             :     void RequestShortPath(const CFixedVector2D& from, const PathGoal& goal, bool extendRange);
     912             : 
     913             :     /**
     914             :      * General handler for MoveTo interface functions.
     915             :      */
     916             :     bool MoveTo(MoveRequest request);
     917             : 
     918             :     /**
     919             :      * Convert a path into a renderable list of lines
     920             :      */
     921             :     void RenderPath(const WaypointPath& path, std::vector<SOverlayLine>& lines, CColor color);
     922             : 
     923             :     void RenderSubmit(SceneCollector& collector);
     924             : };
     925             : 
     926         274 : REGISTER_COMPONENT_TYPE(UnitMotion)
     927             : 
     928         873 : bool CCmpUnitMotion::RejectFartherPaths(const PathGoal& goal, const WaypointPath& path, const CFixedVector2D& pos) const
     929             : {
     930         873 :     if (path.m_Waypoints.empty())
     931             :         return false;
     932             : 
     933             :     // Reject the new path if it does not lead us closer to the target's position.
     934         873 :     if (goal.DistanceToPoint(pos) <= goal.DistanceToPoint(CFixedVector2D(path.m_Waypoints.front().x, path.m_Waypoints.front().z)))
     935             :         return true;
     936             : 
     937             :     return false;
     938             : }
     939             : 
     940         951 : void CCmpUnitMotion::PathResult(std::uint32_t ticket, const WaypointPath& path)
     941             : {
     942             :     // Ignore obsolete path requests
     943         951 :     if (ticket != m_ExpectedPathTicket.m_Ticket || m_MoveRequest.m_Type == MoveRequest::NONE)
     944          78 :         return;
     945             : 
     946         873 :     Ticket::Type ticketType = m_ExpectedPathTicket.m_Type;
     947         873 :     m_ExpectedPathTicket.clear();
     948             : 
     949             :     // If we not longer have a position, we won't be able to do much.
     950             :     // Fail in the next Move() call.
     951         873 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     952         873 :     if (!cmpPosition || !cmpPosition->IsInWorld())
     953           0 :         return;
     954         873 :     CFixedVector2D pos = cmpPosition->GetPosition2D();
     955             : 
     956             :     // Assume all long paths were towards the goal, and assume short paths were if there are no long waypoints.
     957         873 :     bool pathedTowardsGoal = ticketType == Ticket::LONG_PATH || m_LongPath.m_Waypoints.empty();
     958             : 
     959             :     // Check if we need to run the short-path hack (warning: tricky control flow).
     960         873 :     bool shortPathHack = false;
     961         873 :     if (path.m_Waypoints.empty())
     962             :     {
     963             :         // No waypoints means pathing failed. If this was a long-path, try the short-path hack.
     964           0 :         if (!pathedTowardsGoal)
     965             :             return;
     966           0 :         shortPathHack = ticketType == Ticket::LONG_PATH;
     967             :     }
     968         873 :     else if (PathGoal goal; pathedTowardsGoal && ComputeGoal(goal, m_MoveRequest) && RejectFartherPaths(goal, path, pos))
     969             :     {
     970             :         // Reject paths that would take the unit further away from the goal.
     971             :         // This assumes that we prefer being closer 'as the crow flies' to unreachable goals.
     972             :         // This is a hack of sorts around units 'dancing' between two positions (see e.g. #3144),
     973             :         // but never actually failing to move, ergo never actually informing unitAI that it succeeds/fails.
     974             :         // (for short paths, only do so if aiming directly for the goal
     975             :         // as sub-goals may be farther than we are).
     976             : 
     977             :         // If this was a long-path and we no longer have waypoints, try the short-path hack.
     978           0 :         if (!m_LongPath.m_Waypoints.empty())
     979           0 :             return;
     980           0 :         shortPathHack = ticketType == Ticket::LONG_PATH;
     981             :     }
     982             : 
     983             :     // Short-path hack: if the long-range pathfinder doesn't find an acceptable path, push a fake waypoint at the goal.
     984             :     // This means HandleObstructedMove will use the short-pathfinder to try and reach it,
     985             :     // and that may find a path as the vertex pathfinder is more precise.
     986         873 :     if (shortPathHack)
     987             :     {
     988             :         // If we're resorting to the short-path hack, the situation is dire. Most likely, the goal is unreachable.
     989             :         // We want to find a path or fail fast. Bump failed movements so the short pathfinder will run at max-range
     990             :         // right away. This is safe from a performance PoV because it can only happen if the target is unreachable to
     991             :         // the long-range pathfinder, which is rare, and since the entity will fail to move if the goal is actually unreachable,
     992             :         // the failed movements will be increased to MAX anyways, so just shortcut.
     993           0 :         m_FailedMovements = MAX_FAILED_MOVEMENTS - 2;
     994             : 
     995           0 :         CFixedVector2D targetPos;
     996           0 :         if (ComputeTargetPosition(targetPos))
     997           0 :             m_LongPath.m_Waypoints.emplace_back(Waypoint{ targetPos.X, targetPos.Y });
     998           0 :         return;
     999             :     }
    1000             : 
    1001         873 :     if (ticketType == Ticket::LONG_PATH)
    1002             :     {
    1003         873 :         m_LongPath = path;
    1004             :         // Long paths don't properly follow diagonals because of JPS/the grid. Since units now take time turning,
    1005             :         // they can actually slow down substantially if they have to do a one navcell diagonal movement,
    1006             :         // which is somewhat common at the beginning of a new path.
    1007             :         // For that reason, if the first waypoint is really close, check if we can't go directly to the second.
    1008         873 :         if (m_LongPath.m_Waypoints.size() >= 2)
    1009             :         {
    1010         867 :             const Waypoint& firstWpt = m_LongPath.m_Waypoints.back();
    1011         867 :             if (CFixedVector2D(firstWpt.x - pos.X, firstWpt.z - pos.Y).CompareLength(Pathfinding::NAVCELL_SIZE * 4) <= 0)
    1012             :             {
    1013         867 :                 CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
    1014         867 :                 ENSURE(cmpPathfinder);
    1015         867 :                 const Waypoint& secondWpt = m_LongPath.m_Waypoints[m_LongPath.m_Waypoints.size() - 2];
    1016        1734 :                 if (cmpPathfinder->CheckMovement(GetObstructionFilter(), pos.X, pos.Y, secondWpt.x, secondWpt.z, m_Clearance, m_PassClass))
    1017         867 :                     m_LongPath.m_Waypoints.pop_back();
    1018             :             }
    1019             : 
    1020             :         }
    1021             :     }
    1022             :     else
    1023           0 :         m_ShortPath = path;
    1024             : 
    1025         873 :     m_FollowKnownImperfectPathCountdown = 0;
    1026             : 
    1027         873 :     if (!pathedTowardsGoal)
    1028             :         return;
    1029             : 
    1030             :     // Performance hack: If we were pathing towards the goal and this new path won't put us in range,
    1031             :     // it's highly likely that we are going somewhere unreachable.
    1032             :     // However, Move() will try to recompute the path every turn, which can be quite slow.
    1033             :     // To avoid this, act as if our current path leads us to the correct destination.
    1034             :     // NB: for short-paths, the problem might be that the search space is too small
    1035             :     // but we'll still follow this path until the en and try again then.
    1036             :     // Because we reject farther paths, it works out.
    1037         873 :     if (PathingUpdateNeeded(pos))
    1038             :     {
    1039             :         // Inform other components early, as they might have better behaviour than waiting for the path to carry out.
    1040             :         // Send OBSTRUCTED at first - moveFailed is likely to trigger path recomputation and we might end up
    1041             :         // recomputing too often for nothing.
    1042         240 :         if (!IncrementFailedMovementsAndMaybeNotify())
    1043         240 :             MoveObstructed();
    1044             :         // We'll automatically recompute a path when this reaches 0, as a way to improve behaviour.
    1045             :         // (See D665 - this is needed because the target may be moving, and we should adjust to that).
    1046         240 :         m_FollowKnownImperfectPathCountdown = KNOWN_IMPERFECT_PATH_RESET_COUNTDOWN;
    1047             :     }
    1048             : }
    1049             : 
    1050        7938 : void CCmpUnitMotion::OnTurnStart()
    1051             : {
    1052        7938 :     if (PossiblyAtDestination())
    1053         252 :         MoveSucceeded();
    1054        7686 :     else if (!TargetHasValidPosition())
    1055             :     {
    1056             :         // Scrap waypoints - we don't know where to go.
    1057             :         // If the move request remains unchanged and the target again has a valid position later on,
    1058             :         // moving will be resumed.
    1059             :         // Units may want to move to move to the target's last known position,
    1060             :         // but that should be decided by UnitAI (handling MoveFailed), not UnitMotion.
    1061           0 :         m_LongPath.m_Waypoints.clear();
    1062           0 :         m_ShortPath.m_Waypoints.clear();
    1063             : 
    1064           0 :         MoveFailed();
    1065             :     }
    1066        7938 : }
    1067             : 
    1068        8118 : void CCmpUnitMotion::PreMove(CCmpUnitMotionManager::MotionState& state)
    1069             : {
    1070        8118 :     state.ignore = !m_Pushing || !m_BlockMovement;
    1071             : 
    1072        8118 :     state.wasObstructed = false;
    1073        8118 :     state.wentStraight = false;
    1074             : 
    1075             :     // If we were idle and will still be, no need for an update.
    1076        8118 :     state.needUpdate = state.cmpPosition->IsInWorld() &&
    1077        8118 :         (m_CurrentSpeed != fixed::Zero() || m_LastTurnSpeed != fixed::Zero() || m_MoveRequest.m_Type != MoveRequest::NONE);
    1078             : 
    1079        8118 :     if (!m_BlockMovement)
    1080        8118 :         return;
    1081             : 
    1082        8118 :     state.controlGroup = IsFormationMember() ? m_FormationController : INVALID_ENTITY;
    1083             : 
    1084             :     // Update moving flag, this is an internal construct used for pushing,
    1085             :     // so it does not really reflect whether the unit is actually moving or not.
    1086        8118 :     state.isMoving = m_Pushing && m_MoveRequest.m_Type != MoveRequest::NONE;
    1087        8118 :     CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
    1088        8118 :     if (cmpObstruction)
    1089        8118 :         cmpObstruction->SetMovingFlag(state.isMoving);
    1090             : }
    1091             : 
    1092        7278 : void CCmpUnitMotion::Move(CCmpUnitMotionManager::MotionState& state, fixed dt)
    1093             : {
    1094        7278 :     PROFILE("Move");
    1095             : 
    1096             :     // If we're chasing a potentially-moving unit and are currently close
    1097             :     // enough to its current position, and we can head in a straight line
    1098             :     // to it, then throw away our current path and go straight to it.
    1099        7278 :     state.wentStraight = TryGoingStraightToTarget(state.initialPos, true);
    1100             : 
    1101        7278 :     state.wasObstructed = PerformMove(dt, state.cmpPosition->GetTurnRate(), m_ShortPath, m_LongPath, state.pos, state.speed, state.angle, state.pushingPressure);
    1102        7278 : }
    1103             : 
    1104        7278 : void CCmpUnitMotion::PostMove(CCmpUnitMotionManager::MotionState& state, fixed dt)
    1105             : {
    1106             :     // Update our speed over this turn so that the visual actor shows the correct animation.
    1107        7278 :     if (state.pos == state.initialPos)
    1108             :     {
    1109         330 :         if (state.angle != state.initialAngle)
    1110           0 :             state.cmpPosition->TurnTo(state.angle);
    1111         330 :         UpdateMovementState(fixed::Zero(), fixed::Zero());
    1112             :     }
    1113             :     else
    1114             :     {
    1115             :         // Update the Position component after our movement (if we actually moved anywhere)
    1116        6948 :         CFixedVector2D offset = state.pos - state.initialPos;
    1117        6948 :         state.cmpPosition->MoveAndTurnTo(state.pos.X, state.pos.Y, state.angle);
    1118             : 
    1119             :         // Calculate the mean speed over this past turn.
    1120        6948 :         UpdateMovementState(state.speed, offset.Length() / dt);
    1121             :     }
    1122             : 
    1123        7608 :     if (state.wasObstructed && HandleObstructedMove(state.pos != state.initialPos))
    1124             :         return;
    1125        7200 :     else if (!state.wasObstructed && state.pos != state.initialPos)
    1126        6948 :         m_FailedMovements = 0;
    1127             : 
    1128        7200 :     const bool needPathUpdate{PathingUpdateNeeded(state.pos)};
    1129             : 
    1130             :     // If we're following a long-path, check if we might run into units in advance, to smoothe motion.
    1131        7200 :     if (!needPathUpdate && !state.wasObstructed && m_LongPath.m_Waypoints.size() >= 1 && m_ShortPath.m_Waypoints.empty())
    1132             :     {
    1133        3303 :         ICmpObstructionManager::tag_t specificIgnore;
    1134        3303 :         if (m_MoveRequest.m_Type == MoveRequest::ENTITY)
    1135             :         {
    1136         765 :             CmpPtr<ICmpObstruction> cmpTargetObstruction(GetSimContext(), m_MoveRequest.m_Entity);
    1137         765 :             if (cmpTargetObstruction)
    1138         765 :                 specificIgnore = cmpTargetObstruction->GetObstruction();
    1139             :         }
    1140        3303 :         CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
    1141        6606 :         if (cmpObstructionManager && cmpObstructionManager->TestUnitLine(GetObstructionFilter(specificIgnore),
    1142        3303 :             state.pos.X, state.pos.Y, m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z, m_Clearance, true))
    1143             :         {
    1144             :             // We will run into something: request a new short path.
    1145             :             // If we have several waypoints left, aim for the one after next directly.
    1146             :             // (This is mostly because the obstruction might be at the waypoint, and the end is kind of treated specially).
    1147             :             // Else just path to the goal.
    1148           0 :             if (m_LongPath.m_Waypoints.size() > 1) {
    1149           0 :                 fixed radius = Pathfinding::NAVCELL_SIZE * 2;
    1150           0 :                 m_LongPath.m_Waypoints.pop_back();
    1151           0 :                 PathGoal subgoal = { PathGoal::CIRCLE, m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z, radius };
    1152           0 :                 RequestShortPath(state.pos, subgoal, false);
    1153             :             } else {
    1154             :                 // If we only have one waypoint left, request a short path to the waypoint itself.
    1155           0 :                 PathGoal goal;
    1156           0 :                 if (ComputeGoal(goal, m_MoveRequest))
    1157           0 :                     RequestShortPath(state.pos, goal, false);
    1158             :             }
    1159             :         }
    1160             :     }
    1161             : 
    1162             :     // If we moved straight, and didn't quite finish the path, reset - we'll update it next turn if still OK.
    1163        7200 :     if (state.wentStraight && !state.wasObstructed)
    1164        3186 :         m_ShortPath.m_Waypoints.clear();
    1165             : 
    1166             :     // We may need to recompute our path sometimes (e.g. if our target moves).
    1167             :     // Since we request paths asynchronously anyways, this does not need to be done before moving.
    1168        7200 :     if (!state.wentStraight && needPathUpdate)
    1169             :     {
    1170         459 :         PathGoal goal;
    1171         459 :         if (ComputeGoal(goal, m_MoveRequest))
    1172         459 :             ComputePathToGoal(state.pos, goal);
    1173         459 :     }
    1174        6741 :     else if (m_FollowKnownImperfectPathCountdown > 0)
    1175        2538 :         --m_FollowKnownImperfectPathCountdown;
    1176             : }
    1177             : 
    1178       13221 : bool CCmpUnitMotion::PossiblyAtDestination() const
    1179             : {
    1180       13221 :     if (m_MoveRequest.m_Type == MoveRequest::NONE)
    1181             :         return false;
    1182             : 
    1183       12144 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
    1184       12144 :     ENSURE(cmpObstructionManager);
    1185             : 
    1186       12144 :     switch (m_MoveRequest.m_Type)
    1187             :     {
    1188        3108 :     case MoveRequest::POINT:
    1189        3108 :         return cmpObstructionManager->IsInPointRange(
    1190             :             GetEntityId(), m_MoveRequest.m_Position.X, m_MoveRequest.m_Position.Y,
    1191             :             m_MoveRequest.m_MinRange, m_MoveRequest.m_MaxRange, false);
    1192             : 
    1193        9036 :     case MoveRequest::ENTITY:
    1194        9036 :         return cmpObstructionManager->IsInTargetRange(
    1195        9036 :             GetEntityId(), m_MoveRequest.m_Entity,
    1196             :             m_MoveRequest.m_MinRange, m_MoveRequest.m_MaxRange, false);
    1197             : 
    1198           0 :     case MoveRequest::OFFSET:
    1199           0 :     {
    1200           0 :         CmpPtr<ICmpUnitMotion> cmpControllerMotion(GetSimContext(), m_MoveRequest.m_Entity);
    1201           0 :         if (cmpControllerMotion && cmpControllerMotion->IsMoveRequested())
    1202             :             return false;
    1203             : 
    1204           0 :         CFixedVector2D targetPos;
    1205           0 :         ComputeTargetPosition(targetPos);
    1206           0 :         CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1207           0 :         return (targetPos - cmpPosition->GetPosition2D()).CompareLength(Pathfinding::NAVCELL_SIZE) <= 0;
    1208             :     }
    1209             : 
    1210             :     default:
    1211             :         return false;
    1212             :     }
    1213             : }
    1214             : 
    1215        7314 : bool CCmpUnitMotion::PerformMove(fixed dt, const fixed& turnRate, WaypointPath& shortPath, WaypointPath& longPath, CFixedVector2D& pos, fixed& speed, entity_angle_t& angle, uint8_t pushingPressure) const
    1216             : {
    1217             :     // If there are no waypoint, behave as though we were obstructed and let HandleObstructedMove handle it.
    1218        7314 :     if (shortPath.m_Waypoints.empty() && longPath.m_Waypoints.empty())
    1219             :         return true;
    1220             : 
    1221             :     // Wrap the angle to (-Pi, Pi].
    1222        6969 :     while (angle > entity_angle_t::Pi())
    1223           0 :         angle -= entity_angle_t::Pi() * 2;
    1224        6969 :     while (angle < -entity_angle_t::Pi())
    1225           0 :         angle += entity_angle_t::Pi() * 2;
    1226             : 
    1227        6969 :     CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
    1228        6969 :     ENSURE(cmpPathfinder);
    1229             : 
    1230        6969 :     fixed basicSpeed = m_Speed;
    1231             :     // If in formation, run to keep up; otherwise just walk.
    1232        6969 :     if (IsMovingAsFormation())
    1233           0 :         basicSpeed = m_Speed.Multiply(m_RunMultiplier);
    1234             : 
    1235             :     // If pushing pressure is applied, slow the unit down.
    1236        6969 :     if (pushingPressure)
    1237             :     {
    1238             :         // Values below this pressure don't slow the unit down (avoids slowing groups down).
    1239           0 :         constexpr int pressureMinThreshold = 10;
    1240             : 
    1241             :         // Lower speed up to a floor to prevent units from getting stopped.
    1242             :         // This helped pushing particularly for fast units, since they'll end up slowing down.
    1243           0 :         constexpr int maxPressure = CCmpUnitMotionManager::MAX_PRESSURE - pressureMinThreshold - 80;
    1244           0 :         constexpr entity_pos_t floorSpeed = entity_pos_t::FromFraction(3, 2);
    1245           0 :         static_assert(maxPressure > 0);
    1246             : 
    1247           0 :         uint8_t slowdown = maxPressure - std::min(maxPressure, std::max(0, pushingPressure - pressureMinThreshold));
    1248           0 :         basicSpeed = basicSpeed.Multiply(fixed::FromInt(slowdown) / maxPressure);
    1249             :         // NB: lowering this too much will make the units behave a lot like viscous fluid
    1250             :         // when the density becomes extreme. While perhaps realistic (and kind of neat),
    1251             :         // it's not very helpful for gameplay. Empirically, a value of 1.5 avoids most of the effect
    1252             :         // while still slowing down movement significantly, and seems like a good balance.
    1253             :         // Min with the template speed to allow units that are explicitly absurdly slow.
    1254           0 :         basicSpeed = std::max(std::min(m_TemplateWalkSpeed, floorSpeed), basicSpeed);
    1255             :     }
    1256             : 
    1257             :     // TODO: would be nice to support terrain-dependent speed again.
    1258        6969 :     fixed maxSpeed = basicSpeed;
    1259             : 
    1260        6969 :     fixed timeLeft = dt;
    1261        6969 :     fixed zero = fixed::Zero();
    1262             : 
    1263        6969 :     ICmpObstructionManager::tag_t specificIgnore;
    1264        6969 :     if (m_MoveRequest.m_Type == MoveRequest::ENTITY)
    1265             :     {
    1266        4230 :         CmpPtr<ICmpObstruction> cmpTargetObstruction(GetSimContext(), m_MoveRequest.m_Entity);
    1267        4230 :         if (cmpTargetObstruction)
    1268        4230 :             specificIgnore = cmpTargetObstruction->GetObstruction();
    1269             :     }
    1270             : 
    1271        7086 :     while (timeLeft > zero)
    1272             :     {
    1273             :         // If we ran out of path, we have to stop.
    1274        7086 :         if (shortPath.m_Waypoints.empty() && longPath.m_Waypoints.empty())
    1275             :             break;
    1276             : 
    1277        6969 :         CFixedVector2D target;
    1278        6969 :         if (shortPath.m_Waypoints.empty())
    1279        3783 :             target = CFixedVector2D(longPath.m_Waypoints.back().x, longPath.m_Waypoints.back().z);
    1280             :         else
    1281        3186 :             target = CFixedVector2D(shortPath.m_Waypoints.back().x, shortPath.m_Waypoints.back().z);
    1282             : 
    1283        6969 :         CFixedVector2D offset = target - pos;
    1284             : 
    1285        6969 :         if (turnRate > zero && !offset.IsZero())
    1286             :         {
    1287        6969 :             fixed angleDiff = angle - atan2_approx(offset.X, offset.Y);
    1288        6969 :             fixed absoluteAngleDiff = angleDiff.Absolute();
    1289        6969 :             if (absoluteAngleDiff > entity_angle_t::Pi())
    1290           0 :                 absoluteAngleDiff = entity_angle_t::Pi() * 2 - absoluteAngleDiff;
    1291             : 
    1292             :             // We only rotate to the instantTurnAngle angle. The rest we rotate during movement.
    1293        6969 :             if (absoluteAngleDiff > m_InstantTurnAngle)
    1294             :             {
    1295             :                 // Stop moving when rotating this far.
    1296           0 :                 speed = zero;
    1297             : 
    1298           0 :                 fixed maxRotation = turnRate.Multiply(timeLeft);
    1299             : 
    1300             :                 // Figure out whether rotating will increase or decrease the angle, and how far we need to rotate in that direction.
    1301           0 :                 int direction = (entity_angle_t::Zero() < angleDiff && angleDiff <= entity_angle_t::Pi()) || angleDiff < -entity_angle_t::Pi() ? -1 : 1;
    1302             : 
    1303             :                 // Can't rotate far enough, just rotate in the correct direction.
    1304           0 :                 if (absoluteAngleDiff - m_InstantTurnAngle > maxRotation)
    1305             :                 {
    1306           0 :                     angle += maxRotation * direction;
    1307           0 :                     if (angle * direction > entity_angle_t::Pi())
    1308           0 :                         angle -= entity_angle_t::Pi() * 2 * direction;
    1309           0 :                     break;
    1310             :                 }
    1311             :                 // Rotate towards the next waypoint and continue moving.
    1312           0 :                 angle = atan2_approx(offset.X, offset.Y);
    1313           0 :                 timeLeft = std::min(maxRotation, maxRotation - absoluteAngleDiff + m_InstantTurnAngle) / turnRate;
    1314             :             }
    1315             :             else
    1316             :             {
    1317             :                 // Modify the speed depending on the angle difference.
    1318        6969 :                 fixed sin, cos;
    1319        6969 :                 sincos_approx(angleDiff, sin, cos);
    1320        6969 :                 speed = speed.Multiply(cos);
    1321        6969 :                 angle = atan2_approx(offset.X, offset.Y);
    1322             :             }
    1323             :         }
    1324             : 
    1325             :         // Work out how far we can travel in timeLeft.
    1326        6969 :         fixed accelTime = std::min(timeLeft, (maxSpeed - speed) / m_Acceleration);
    1327        6969 :         fixed accelDist = speed.Multiply(accelTime) + accelTime.Square().Multiply(m_Acceleration) / 2;
    1328        6969 :         fixed maxdist = accelDist + maxSpeed.Multiply(timeLeft - accelTime);
    1329             : 
    1330             :         // If the target is close, we can move there directly.
    1331        6969 :         fixed offsetLength = offset.Length();
    1332        6969 :         if (offsetLength <= maxdist)
    1333             :         {
    1334         234 :             if (cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), pos.X, pos.Y, target.X, target.Y, m_Clearance, m_PassClass))
    1335             :             {
    1336         117 :                 pos = target;
    1337             : 
    1338             :                 // Spend the rest of the time heading towards the next waypoint.
    1339             :                 // Either we still need to accelerate after, or we have reached maxSpeed.
    1340             :                 // The former is much less likely than the latter: usually we can reach
    1341             :                 // maxSpeed within one waypoint. So the Sqrt is not too bad.
    1342         117 :                 if (offsetLength <= accelDist)
    1343             :                 {
    1344           0 :                     fixed requiredTime = (-speed + (speed.Square() + offsetLength.Multiply(m_Acceleration).Multiply(fixed::FromInt(2))).Sqrt()) / m_Acceleration;
    1345           0 :                     timeLeft -= requiredTime;
    1346           0 :                     speed += m_Acceleration.Multiply(requiredTime);
    1347             :                 }
    1348             :                 else
    1349             :                 {
    1350         117 :                     timeLeft -= accelTime + (offsetLength - accelDist) / maxSpeed;
    1351         117 :                     speed = maxSpeed;
    1352             :                 }
    1353             : 
    1354         117 :                 if (shortPath.m_Waypoints.empty())
    1355           0 :                     longPath.m_Waypoints.pop_back();
    1356             :                 else
    1357         117 :                     shortPath.m_Waypoints.pop_back();
    1358             : 
    1359         117 :                 continue;
    1360         117 :             }
    1361             :             else
    1362             :             {
    1363             :                 // Error - path was obstructed.
    1364           0 :                 return true;
    1365             :             }
    1366             :         }
    1367             :         else
    1368             :         {
    1369             :             // Not close enough, so just move in the right direction.
    1370        6852 :             offset.Normalize(maxdist);
    1371        6852 :             target = pos + offset;
    1372             : 
    1373        6852 :             speed = std::min(maxSpeed, speed + m_Acceleration.Multiply(timeLeft));
    1374             : 
    1375       13704 :             if (cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), pos.X, pos.Y, target.X, target.Y, m_Clearance, m_PassClass))
    1376        6852 :                 pos = target;
    1377             :             else
    1378             :                 return true;
    1379             : 
    1380        6852 :             break;
    1381             :         }
    1382             :     }
    1383             :     return false;
    1384             : }
    1385             : 
    1386        7278 : void CCmpUnitMotion::UpdateMovementState(entity_pos_t speed, entity_pos_t meanSpeed)
    1387             : {
    1388        7278 :     CmpPtr<ICmpVisual> cmpVisual(GetEntityHandle());
    1389        7278 :     if (cmpVisual)
    1390             :     {
    1391        7278 :         if (meanSpeed == fixed::Zero())
    1392         660 :             cmpVisual->SelectMovementAnimation("idle", fixed::FromInt(1));
    1393             :         else
    1394       19593 :             cmpVisual->SelectMovementAnimation(meanSpeed > (m_WalkSpeed / 2).Multiply(m_RunMultiplier + fixed::FromInt(1)) ? "run" : "walk", meanSpeed);
    1395             :     }
    1396             : 
    1397        7278 :     m_LastTurnSpeed = meanSpeed;
    1398        7278 :     m_CurrentSpeed = speed;
    1399        7278 : }
    1400             : 
    1401         330 : bool CCmpUnitMotion::HandleObstructedMove(bool moved)
    1402             : {
    1403         330 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1404         330 :     if (!cmpPosition || !cmpPosition->IsInWorld())
    1405           0 :         return false;
    1406             : 
    1407             :     // We failed to move, inform other components as they might handle it.
    1408             :     // (don't send messages on the first failure, as that would be too noisy).
    1409             :     // Also don't increment above the initial MoveObstructed message if we actually manage to move a little.
    1410         330 :     if (!moved || m_FailedMovements < 2)
    1411             :     {
    1412         330 :         if (!IncrementFailedMovementsAndMaybeNotify() && m_FailedMovements >= 2)
    1413           0 :             MoveObstructed();
    1414             :     }
    1415             : 
    1416         330 :     PathGoal goal;
    1417         330 :     if (!ComputeGoal(goal, m_MoveRequest))
    1418             :         return false;
    1419             : 
    1420             :     // At this point we have a position in the world since ComputeGoal checked for that.
    1421          78 :     CFixedVector2D pos = cmpPosition->GetPosition2D();
    1422             : 
    1423             :     // Assume that we are merely obstructed and the long path is salvageable, so try going around the obstruction.
    1424             :     // This could be a separate function, but it doesn't really make sense to call it outside of here, and I can't find a name.
    1425             :     // I use an IIFE to have nice 'return' semantics still.
    1426          78 :     if ([&]() -> bool {
    1427             :         // If the goal is close enough, we should ignore any remaining long waypoint and just
    1428             :         // short path there directly, as that improves behaviour in general - see D2095).
    1429         156 :         if (InShortPathRange(goal, pos))
    1430             :             return false;
    1431             : 
    1432             :         // On rare occasions, when following a short path, we can end up in a position where
    1433             :         // the short pathfinder thinks we are inside an obstruction (and can leave)
    1434             :         // but the CheckMovement logic doesn't. I believe the cause is a small numerical difference
    1435             :         // in their calculation, but haven't been able to pinpoint it precisely.
    1436             :         // In those cases, the solution is to back away to prevent the short-pathfinder from being confused.
    1437             :         // TODO: this should only be done if we're obstructed by a static entity.
    1438          78 :         if (!m_ShortPath.m_Waypoints.empty() && m_FailedMovements == BACKUP_HACK_DELAY)
    1439             :         {
    1440           0 :             Waypoint next = m_ShortPath.m_Waypoints.back();
    1441           0 :             CFixedVector2D backUp(pos.X - next.x, pos.Y - next.z);
    1442           0 :             backUp.Normalize();
    1443           0 :             next.x = pos.X + backUp.X;
    1444           0 :             next.z = pos.Y + backUp.Y;
    1445           0 :             m_ShortPath.m_Waypoints.push_back(next);
    1446           0 :             return true;
    1447             :         }
    1448             :         // Delete the next waypoint if it's reasonably close,
    1449             :         // because it might be blocked by units and thus unreachable.
    1450             :         // NB: this number is tricky. Make it too high, and units start going down dead ends, which looks odd (#5795)
    1451             :         // Make it too low, and they might get stuck behind other obstructed entities.
    1452             :         // It also has performance implications because it calls the short-pathfinder.
    1453         156 :         fixed skipbeyond = std::max(ShortPathSearchRange() / 3, Pathfinding::NAVCELL_SIZE * 8);
    1454          78 :         if (m_LongPath.m_Waypoints.size() > 1 &&
    1455           0 :             (pos - CFixedVector2D(m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z)).CompareLength(skipbeyond) < 0)
    1456             :         {
    1457           0 :             m_LongPath.m_Waypoints.pop_back();
    1458             :         }
    1459          78 :         else if (ShouldAlternatePathfinder())
    1460             :         {
    1461             :             // Recompute the whole thing occasionally, in case we got stuck in a dead end from removing long waypoints.
    1462           0 :             RequestLongPath(pos, goal);
    1463           0 :             return true;
    1464             :         }
    1465             : 
    1466          78 :         if (m_LongPath.m_Waypoints.empty())
    1467             :             return false;
    1468             : 
    1469             :         // Compute a short path in the general vicinity of the next waypoint, to help pathfinding in crowds.
    1470             :         // The goal here is to manage to move in the general direction of our target, not to be super accurate.
    1471           0 :         fixed radius = Clamp(skipbeyond/3, Pathfinding::NAVCELL_SIZE * 4, Pathfinding::NAVCELL_SIZE * 12);
    1472           0 :         PathGoal subgoal = { PathGoal::CIRCLE, m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z, radius };
    1473           0 :         RequestShortPath(pos, subgoal, false);
    1474             :         return true;
    1475          78 :     }()) return true;
    1476             : 
    1477             :     // If we couldn't use a workaround, try recomputing the entire path.
    1478          78 :     ComputePathToGoal(pos, goal);
    1479             : 
    1480             :     return true;
    1481             : }
    1482             : 
    1483        7686 : bool CCmpUnitMotion::TargetHasValidPosition(const MoveRequest& moveRequest) const
    1484             : {
    1485        7686 :     if (moveRequest.m_Type != MoveRequest::ENTITY)
    1486             :         return true;
    1487             : 
    1488        3921 :     CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), moveRequest.m_Entity);
    1489        3921 :     return cmpPosition && cmpPosition->IsInWorld();
    1490             : }
    1491             : 
    1492       26142 : bool CCmpUnitMotion::ComputeTargetPosition(CFixedVector2D& out, const MoveRequest& moveRequest) const
    1493             : {
    1494       26142 :     if (moveRequest.m_Type == MoveRequest::POINT)
    1495             :     {
    1496        9510 :         out = moveRequest.m_Position;
    1497        9510 :         return true;
    1498             :     }
    1499             : 
    1500       16632 :     CmpPtr<ICmpPosition> cmpTargetPosition(GetSimContext(), moveRequest.m_Entity);
    1501       16632 :     if (!cmpTargetPosition || !cmpTargetPosition->IsInWorld())
    1502         261 :         return false;
    1503             : 
    1504       16371 :     if (moveRequest.m_Type == MoveRequest::OFFSET)
    1505             :     {
    1506             :         // There is an offset, so compute it relative to orientation
    1507           0 :         entity_angle_t angle = cmpTargetPosition->GetRotation().Y;
    1508           0 :         CFixedVector2D offset = moveRequest.GetOffset().Rotate(angle);
    1509           0 :         out = cmpTargetPosition->GetPosition2D() + offset;
    1510             :     }
    1511             :     else
    1512             :     {
    1513       16371 :         out = cmpTargetPosition->GetPosition2D();
    1514             :         // Position is only updated after all units have moved & pushed.
    1515             :         // Therefore, we may need to interpolate the target position, depending on when this call takes place during the turn:
    1516             :         //  - On "Turn Start", we'll check positions directly without interpolation.
    1517             :         //  - During movement, we'll call this for direct-pathing & we need to interpolate
    1518             :         //    (this way, we move where the unit will end up at the end of _this_ turn, making it match on next turn start).
    1519             :         //  - After movement, we'll call this to request paths & we need to interpolate
    1520             :         //    (this way, we'll move where the unit ends up in the end of _next_ turn, making it a match in 2 turns).
    1521             :         // TODO: This does not really aim many turns in advance, with orthogonal trajectories it probably should.
    1522       16371 :         CmpPtr<ICmpUnitMotion> cmpUnitMotion(GetSimContext(), moveRequest.m_Entity);
    1523       16371 :         CmpPtr<ICmpUnitMotionManager> cmpUnitMotionManager(GetSystemEntity());
    1524       42513 :         bool needInterpolation = cmpUnitMotion && cmpUnitMotion->IsMoveRequested() && cmpUnitMotionManager->ComputingMotion();
    1525       12255 :         if (needInterpolation)
    1526             :         {
    1527             :             // Add predicted movement.
    1528       12255 :             CFixedVector2D tempPos = out + (out - cmpTargetPosition->GetPreviousPosition2D());
    1529       12255 :             out = tempPos;
    1530             :         }
    1531             :     }
    1532             :     return true;
    1533             : }
    1534             : 
    1535        8232 : bool CCmpUnitMotion::TryGoingStraightToTarget(const CFixedVector2D& from, bool updatePaths)
    1536             : {
    1537             :     // Assume if we have short paths we want to follow them.
    1538             :     // Exception: offset movement (formations) generally have very short deltas
    1539             :     // and to look good we need them to walk-straight most of the time.
    1540        8232 :     if (!IsFormationMember() && !m_ShortPath.m_Waypoints.empty())
    1541             :         return false;
    1542             : 
    1543        8232 :     CFixedVector2D targetPos;
    1544        8232 :     if (!ComputeTargetPosition(targetPos))
    1545             :         return false;
    1546             : 
    1547        7980 :     CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
    1548        7980 :     if (!cmpPathfinder)
    1549             :         return false;
    1550             : 
    1551             :     // Move the goal to match the target entity's new position
    1552        7980 :     PathGoal goal;
    1553        7980 :     if (!ComputeGoal(goal, m_MoveRequest))
    1554             :         return false;
    1555        7980 :     goal.x = targetPos.X;
    1556        7980 :     goal.z = targetPos.Y;
    1557             :     // (we ignore changes to the target's rotation, since only buildings are
    1558             :     // square and buildings don't move)
    1559             : 
    1560             :     // Find the point on the goal shape that we should head towards
    1561        7980 :     CFixedVector2D goalPos = goal.NearestPointOnGoal(from);
    1562             : 
    1563             :     // Fail if the target is too far away
    1564       12699 :     if ((goalPos - from).CompareLength(DIRECT_PATH_RANGE) > 0)
    1565             :         return false;
    1566             : 
    1567             :     // Check if there's any collisions on that route.
    1568             :     // For entity goals, skip only the specific obstruction tag or with e.g. walls we might ignore too many entities.
    1569        3513 :     ICmpObstructionManager::tag_t specificIgnore;
    1570        3513 :     if (m_MoveRequest.m_Type == MoveRequest::ENTITY)
    1571             :     {
    1572        3513 :         CmpPtr<ICmpObstruction> cmpTargetObstruction(GetSimContext(), m_MoveRequest.m_Entity);
    1573        3513 :         if (cmpTargetObstruction)
    1574        3513 :             specificIgnore = cmpTargetObstruction->GetObstruction();
    1575             :     }
    1576             : 
    1577             :     // Check movement against units - we want to use the short pathfinder to walk around those if needed.
    1578        3513 :     if (specificIgnore.valid())
    1579             :     {
    1580        7026 :         if (!cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), from.X, from.Y, goalPos.X, goalPos.Y, m_Clearance, m_PassClass))
    1581             :             return false;
    1582             :     }
    1583           0 :     else if (!cmpPathfinder->CheckMovement(GetObstructionFilter(), from.X, from.Y, goalPos.X, goalPos.Y, m_Clearance, m_PassClass))
    1584             :         return false;
    1585             : 
    1586        3513 :     if (!updatePaths)
    1587             :         return true;
    1588             : 
    1589             :     // That route is okay, so update our path
    1590        3186 :     m_LongPath.m_Waypoints.clear();
    1591        3186 :     m_ShortPath.m_Waypoints.clear();
    1592        3186 :     m_ShortPath.m_Waypoints.emplace_back(Waypoint{ goalPos.X, goalPos.Y });
    1593        3186 :     return true;
    1594             : }
    1595             : 
    1596        8073 : bool CCmpUnitMotion::PathingUpdateNeeded(const CFixedVector2D& from) const
    1597             : {
    1598        8073 :     if (m_MoveRequest.m_Type == MoveRequest::NONE)
    1599             :         return false;
    1600             : 
    1601        7821 :     CFixedVector2D targetPos;
    1602        7821 :     if (!ComputeTargetPosition(targetPos))
    1603             :         return false;
    1604             : 
    1605        7821 :     if (m_FollowKnownImperfectPathCountdown > 0 && (!m_LongPath.m_Waypoints.empty() || !m_ShortPath.m_Waypoints.empty()))
    1606             :         return false;
    1607             : 
    1608        5283 :     if (PossiblyAtDestination())
    1609             :         return false;
    1610             : 
    1611             :     // Get the obstruction shape and translate it where we estimate the target to be.
    1612        4761 :     ICmpObstructionManager::ObstructionSquare estimatedTargetShape;
    1613        4761 :     if (m_MoveRequest.m_Type == MoveRequest::ENTITY)
    1614             :     {
    1615        4341 :         CmpPtr<ICmpObstruction> cmpTargetObstruction(GetSimContext(), m_MoveRequest.m_Entity);
    1616        4341 :         if (cmpTargetObstruction)
    1617        4341 :             cmpTargetObstruction->GetObstructionSquare(estimatedTargetShape);
    1618             :     }
    1619             : 
    1620        4761 :     estimatedTargetShape.x = targetPos.X;
    1621        4761 :     estimatedTargetShape.z = targetPos.Y;
    1622             : 
    1623        4761 :     CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
    1624        4761 :     ICmpObstructionManager::ObstructionSquare shape;
    1625        4761 :     if (cmpObstruction)
    1626        4761 :         cmpObstruction->GetObstructionSquare(shape);
    1627             : 
    1628             :     // Translate our own obstruction shape to our last waypoint or our current position, lacking that.
    1629        4761 :     if (m_LongPath.m_Waypoints.empty() && m_ShortPath.m_Waypoints.empty())
    1630             :     {
    1631           0 :         shape.x = from.X;
    1632           0 :         shape.z = from.Y;
    1633             :     }
    1634             :     else
    1635             :     {
    1636        4761 :         const Waypoint& lastWaypoint = m_LongPath.m_Waypoints.empty() ? m_ShortPath.m_Waypoints.front() : m_LongPath.m_Waypoints.front();
    1637        4761 :         shape.x = lastWaypoint.x;
    1638        4761 :         shape.z = lastWaypoint.z;
    1639             :     }
    1640             : 
    1641        4761 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
    1642        4761 :     ENSURE(cmpObstructionManager);
    1643             : 
    1644             :     // Increase the ranges with distance, to avoid recomputing every turn against units that are moving and far-away for example.
    1645        4761 :     entity_pos_t distance = (from - CFixedVector2D(estimatedTargetShape.x, estimatedTargetShape.z)).Length();
    1646             : 
    1647             :     // TODO: it could be worth computing this based on time to collision instead of linear distance.
    1648        4761 :     entity_pos_t minRange = std::max(m_MoveRequest.m_MinRange - distance / TARGET_UNCERTAINTY_MULTIPLIER, entity_pos_t::Zero());
    1649        4761 :     entity_pos_t maxRange = m_MoveRequest.m_MaxRange < entity_pos_t::Zero() ? m_MoveRequest.m_MaxRange :
    1650        4761 :         m_MoveRequest.m_MaxRange + distance / TARGET_UNCERTAINTY_MULTIPLIER;
    1651             : 
    1652        4761 :     if (cmpObstructionManager->AreShapesInRange(shape, estimatedTargetShape, minRange, maxRange, false))
    1653             :         return false;
    1654             : 
    1655             :     return true;
    1656             : }
    1657             : 
    1658         510 : void CCmpUnitMotion::FaceTowardsPoint(entity_pos_t x, entity_pos_t z)
    1659             : {
    1660         510 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1661         510 :     if (!cmpPosition || !cmpPosition->IsInWorld())
    1662           0 :         return;
    1663             : 
    1664         510 :     CFixedVector2D pos = cmpPosition->GetPosition2D();
    1665         510 :     FaceTowardsPointFromPos(pos, x, z);
    1666             : }
    1667             : 
    1668         783 : void CCmpUnitMotion::FaceTowardsPointFromPos(const CFixedVector2D& pos, entity_pos_t x, entity_pos_t z)
    1669             : {
    1670         783 :     CFixedVector2D target(x, z);
    1671         783 :     CFixedVector2D offset = target - pos;
    1672        1566 :     if (!offset.IsZero())
    1673             :     {
    1674         783 :         entity_angle_t angle = atan2_approx(offset.X, offset.Y);
    1675             : 
    1676         783 :         CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1677         783 :         if (!cmpPosition)
    1678           0 :             return;
    1679         783 :         cmpPosition->TurnTo(angle);
    1680             :     }
    1681             : }
    1682             : 
    1683             : // The pathfinder cannot go to "rounded rectangles" goals, which are what happens with square targets and a non-null range.
    1684             : // Depending on what the best approximation is, we either pretend the target is a circle or a square.
    1685             : // One needs to be careful that the approximated geometry will be in the range.
    1686        6279 : bool CCmpUnitMotion::ShouldTreatTargetAsCircle(entity_pos_t range, entity_pos_t circleRadius) const
    1687             : {
    1688             :     // Given a square, plus a target range we should reach, the shape at that distance
    1689             :     // is a round-cornered square which we can approximate as either a circle or as a square.
    1690             :     // Previously, we used the shape that minimized the worst-case error.
    1691             :     // However that is unsage in some situations. So let's be less clever and
    1692             :     // just check if our range is at least three times bigger than the circleradius
    1693        6279 :     return (range > circleRadius*3);
    1694             : }
    1695             : 
    1696       10059 : bool CCmpUnitMotion::ComputeGoal(PathGoal& out, const MoveRequest& moveRequest) const
    1697             : {
    1698       10059 :     if (moveRequest.m_Type == MoveRequest::NONE)
    1699             :         return false;
    1700             : 
    1701        9807 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1702        9807 :     if (!cmpPosition || !cmpPosition->IsInWorld())
    1703           0 :         return false;
    1704             : 
    1705        9807 :     CFixedVector2D pos = cmpPosition->GetPosition2D();
    1706             : 
    1707        9807 :     CFixedVector2D targetPosition;
    1708        9807 :     if (!ComputeTargetPosition(targetPosition, moveRequest))
    1709             :         return false;
    1710             : 
    1711        9807 :     ICmpObstructionManager::ObstructionSquare targetObstruction;
    1712        9807 :     if (moveRequest.m_Type == MoveRequest::ENTITY)
    1713             :     {
    1714        6279 :         CmpPtr<ICmpObstruction> cmpTargetObstruction(GetSimContext(), moveRequest.m_Entity);
    1715        6279 :         if (cmpTargetObstruction)
    1716        6279 :             cmpTargetObstruction->GetObstructionSquare(targetObstruction);
    1717             :     }
    1718        9807 :     targetObstruction.x = targetPosition.X;
    1719        9807 :     targetObstruction.z = targetPosition.Y;
    1720             : 
    1721        9807 :     ICmpObstructionManager::ObstructionSquare obstruction;
    1722        9807 :     CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
    1723        9807 :     if (cmpObstruction)
    1724        9807 :         cmpObstruction->GetObstructionSquare(obstruction);
    1725             :     else
    1726             :     {
    1727           0 :         obstruction.x = pos.X;
    1728           0 :         obstruction.z = pos.Y;
    1729             :     }
    1730             : 
    1731        9807 :     CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
    1732        9807 :     ENSURE(cmpObstructionManager);
    1733             : 
    1734        9807 :     out.x = targetObstruction.x;
    1735        9807 :     out.z = targetObstruction.z;
    1736        9807 :     out.hw = targetObstruction.hw;
    1737        9807 :     out.hh = targetObstruction.hh;
    1738        9807 :     out.u = targetObstruction.u;
    1739        9807 :     out.v = targetObstruction.v;
    1740             : 
    1741        9807 :     if (moveRequest.m_MinRange > fixed::Zero() || moveRequest.m_MaxRange > fixed::Zero() ||
    1742        3528 :          targetObstruction.hw > fixed::Zero())
    1743        6279 :         out.type = PathGoal::SQUARE;
    1744             :     else
    1745             :     {
    1746        3528 :         out.type = PathGoal::POINT;
    1747        3528 :         return true;
    1748             :     }
    1749             : 
    1750        6279 :     entity_pos_t distance = cmpObstructionManager->DistanceBetweenShapes(obstruction, targetObstruction);
    1751             : 
    1752        6279 :     entity_pos_t circleRadius = CFixedVector2D(targetObstruction.hw, targetObstruction.hh).Length();
    1753             : 
    1754             :     // TODO: because we cannot move to rounded rectangles, we have to make conservative approximations.
    1755             :     // This means we might end up in a situation where cons(max-range) < min range < max range < cons(min-range)
    1756             :     // When going outside of the min-range or inside the max-range, the unit will still go through the correct range
    1757             :     // but if it moves fast enough, this might not be picked up by PossiblyAtDestination().
    1758             :     // Fixing this involves moving to rounded rectangles, or checking more often in PerformMove().
    1759             :     // In the meantime, one should avoid that 'Speed over a turn' > MaxRange - MinRange, in case where
    1760             :     // min-range is not 0 and max-range is not infinity.
    1761        6279 :     if (distance < moveRequest.m_MinRange)
    1762             :     {
    1763             :         // Distance checks are nearest edge to nearest edge, so we need to account for our clearance
    1764             :         // and we must make sure diagonals also fit so multiply by slightly more than sqrt(2)
    1765         888 :         entity_pos_t goalDistance = moveRequest.m_MinRange + m_Clearance * 3 / 2;
    1766             : 
    1767         888 :         if (ShouldTreatTargetAsCircle(moveRequest.m_MinRange, circleRadius))
    1768             :         {
    1769             :             // We are safely away from the obstruction itself if we are away from the circumscribing circle
    1770         888 :             out.type = PathGoal::INVERTED_CIRCLE;
    1771         888 :             out.hw = circleRadius + goalDistance;
    1772             :         }
    1773             :         else
    1774             :         {
    1775           0 :             out.type = PathGoal::INVERTED_SQUARE;
    1776           0 :             out.hw = targetObstruction.hw + goalDistance;
    1777           0 :             out.hh = targetObstruction.hh + goalDistance;
    1778             :         }
    1779             :     }
    1780        5391 :     else if (moveRequest.m_MaxRange >= fixed::Zero() && distance > moveRequest.m_MaxRange)
    1781             :     {
    1782        5391 :         if (ShouldTreatTargetAsCircle(moveRequest.m_MaxRange, circleRadius))
    1783             :         {
    1784        4929 :             entity_pos_t goalDistance = moveRequest.m_MaxRange;
    1785             :             // We must go in-range of the inscribed circle, not the circumscribing circle.
    1786        4929 :             circleRadius = std::min(targetObstruction.hw, targetObstruction.hh);
    1787             : 
    1788        4929 :             out.type = PathGoal::CIRCLE;
    1789        4929 :             out.hw = circleRadius + goalDistance;
    1790             :         }
    1791             :         else
    1792             :         {
    1793             :             // The target is large relative to our range, so treat it as a square and
    1794             :             // get close enough that the diagonals come within range
    1795             : 
    1796         462 :             entity_pos_t goalDistance = moveRequest.m_MaxRange * 2 / 3; // multiply by slightly less than 1/sqrt(2)
    1797             : 
    1798         462 :             out.type = PathGoal::SQUARE;
    1799         462 :             entity_pos_t delta = std::max(goalDistance, m_Clearance + entity_pos_t::FromInt(4)/16); // ensure it's far enough to not intersect the building itself
    1800         462 :             out.hw = targetObstruction.hw + delta;
    1801         462 :             out.hh = targetObstruction.hh + delta;
    1802             :         }
    1803             :     }
    1804             :     // Do nothing in particular in case we are already in range.
    1805             :     return true;
    1806             : }
    1807             : 
    1808         954 : void CCmpUnitMotion::ComputePathToGoal(const CFixedVector2D& from, const PathGoal& goal)
    1809             : {
    1810             : #if DISABLE_PATHFINDER
    1811             :     {
    1812             :         CmpPtr<ICmpPathfinder> cmpPathfinder (GetSimContext(), SYSTEM_ENTITY);
    1813             :         CFixedVector2D goalPos = m_FinalGoal.NearestPointOnGoal(from);
    1814             :         m_LongPath.m_Waypoints.clear();
    1815             :         m_ShortPath.m_Waypoints.clear();
    1816             :         m_ShortPath.m_Waypoints.emplace_back(Waypoint{ goalPos.X, goalPos.Y });
    1817             :         return;
    1818             :     }
    1819             : #endif
    1820             : 
    1821             :     // If the target is close enough, hope that we'll be able to go straight next turn.
    1822        1908 :     if (!ShouldAlternatePathfinder() && TryGoingStraightToTarget(from, false))
    1823             :     {
    1824             :         // NB: since we may fail to move straight next turn, we should edge our bets.
    1825             :         // Since the 'go straight' logic currently fires only if there's no short path,
    1826             :         // we'll compute a long path regardless to make sure _that_ stays up to date.
    1827             :         // (it's also extremely likely to be very fast to compute, so no big deal).
    1828         327 :         m_ShortPath.m_Waypoints.clear();
    1829         327 :         RequestLongPath(from, goal);
    1830         327 :         return;
    1831             :     }
    1832             : 
    1833             :     // Otherwise we need to compute a path.
    1834             : 
    1835             :     // If it's close then just do a short path, not a long path
    1836             :     // TODO: If it's close on the opposite side of a river then we really
    1837             :     // need a long path, so we shouldn't simply check linear distance
    1838             :     // the check is arbitrary but should be a reasonably small distance.
    1839             :     // We want to occasionally compute a long path if we're computing short-paths, because the short path domain
    1840             :     // is bounded and thus it can't around very large static obstacles.
    1841             :     // Likewise, we want to compile a short-path occasionally when the target is far because we might be stuck
    1842             :     // on a navcell surrounded by impassable navcells, but the short-pathfinder could move us out of there.
    1843         627 :     bool shortPath = InShortPathRange(goal, from);
    1844         627 :     if (ShouldAlternatePathfinder())
    1845           0 :         shortPath = !shortPath;
    1846         627 :     if (shortPath)
    1847             :     {
    1848           0 :         m_LongPath.m_Waypoints.clear();
    1849             :         // Extend the range so that our first path is probably valid.
    1850           0 :         RequestShortPath(from, goal, true);
    1851             :     }
    1852             :     else
    1853             :     {
    1854         627 :         m_ShortPath.m_Waypoints.clear();
    1855         627 :         RequestLongPath(from, goal);
    1856             :     }
    1857             : }
    1858             : 
    1859         954 : void CCmpUnitMotion::RequestLongPath(const CFixedVector2D& from, const PathGoal& goal)
    1860             : {
    1861         954 :     CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
    1862         954 :     if (!cmpPathfinder)
    1863           0 :         return;
    1864             : 
    1865             :     // this is by how much our waypoints will be apart at most.
    1866             :     // this value here seems sensible enough.
    1867         954 :     PathGoal improvedGoal = goal;
    1868         954 :     improvedGoal.maxdist = SHORT_PATH_MIN_SEARCH_RANGE - entity_pos_t::FromInt(1);
    1869             : 
    1870         954 :     cmpPathfinder->SetDebugPath(from.X, from.Y, improvedGoal, m_PassClass);
    1871             : 
    1872         954 :     m_ExpectedPathTicket.m_Type = Ticket::LONG_PATH;
    1873         954 :     m_ExpectedPathTicket.m_Ticket = cmpPathfinder->ComputePathAsync(from.X, from.Y, improvedGoal, m_PassClass, GetEntityId());
    1874             : }
    1875             : 
    1876           0 : void CCmpUnitMotion::RequestShortPath(const CFixedVector2D &from, const PathGoal& goal, bool extendRange)
    1877             : {
    1878           0 :     CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
    1879           0 :     if (!cmpPathfinder)
    1880           0 :         return;
    1881             : 
    1882           0 :     entity_pos_t searchRange = ShortPathSearchRange();
    1883           0 :     if (extendRange)
    1884             :     {
    1885           0 :         CFixedVector2D dist(from.X - goal.x, from.Y - goal.z);
    1886           0 :         if (dist.CompareLength(searchRange - entity_pos_t::FromInt(1)) >= 0)
    1887             :         {
    1888           0 :             searchRange = dist.Length() + fixed::FromInt(1);
    1889           0 :             if (searchRange > SHORT_PATH_MAX_SEARCH_RANGE)
    1890             :                 searchRange = SHORT_PATH_MAX_SEARCH_RANGE;
    1891             :         }
    1892             :     }
    1893             : 
    1894           0 :     m_ExpectedPathTicket.m_Type = Ticket::SHORT_PATH;
    1895           0 :     m_ExpectedPathTicket.m_Ticket = cmpPathfinder->ComputeShortPathAsync(from.X, from.Y, m_Clearance, searchRange, goal, m_PassClass, ShouldCollideWithMovingUnits(), GetGroup(), GetEntityId());
    1896             : }
    1897             : 
    1898         417 : bool CCmpUnitMotion::MoveTo(MoveRequest request)
    1899             : {
    1900         417 :     PROFILE("MoveTo");
    1901             : 
    1902         417 :     if (request.m_MinRange == request.m_MaxRange && !request.m_MinRange.IsZero())
    1903           0 :         LOGWARNING("MaxRange must be larger than MinRange; See CCmpUnitMotion.cpp for more information");
    1904             : 
    1905         417 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1906         417 :     if (!cmpPosition || !cmpPosition->IsInWorld())
    1907           0 :         return false;
    1908             : 
    1909         417 :     PathGoal goal;
    1910         417 :     if (!ComputeGoal(goal, request))
    1911             :         return false;
    1912             : 
    1913         417 :     m_MoveRequest = request;
    1914         417 :     m_FailedMovements = 0;
    1915         417 :     m_FollowKnownImperfectPathCountdown = 0;
    1916             : 
    1917         417 :     ComputePathToGoal(cmpPosition->GetPosition2D(), goal);
    1918         417 :     return true;
    1919         417 : }
    1920             : 
    1921           0 : bool CCmpUnitMotion::IsTargetRangeReachable(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange)
    1922             : {
    1923           0 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1924           0 :     if (!cmpPosition || !cmpPosition->IsInWorld())
    1925           0 :         return false;
    1926             : 
    1927           0 :     MoveRequest request(target, minRange, maxRange);
    1928           0 :     PathGoal goal;
    1929           0 :     if (!ComputeGoal(goal, request))
    1930             :         return false;
    1931             : 
    1932           0 :     CmpPtr<ICmpPathfinder> cmpPathfinder(GetSimContext(), SYSTEM_ENTITY);
    1933           0 :     CFixedVector2D pos = cmpPosition->GetPosition2D();
    1934           0 :     return cmpPathfinder->IsGoalReachable(pos.X, pos.Y, goal, m_PassClass);
    1935             : }
    1936             : 
    1937           0 : void CCmpUnitMotion::RenderPath(const WaypointPath& path, std::vector<SOverlayLine>& lines, CColor color)
    1938             : {
    1939           0 :     bool floating = false;
    1940           0 :     CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
    1941           0 :     if (cmpPosition)
    1942           0 :         floating = cmpPosition->CanFloat();
    1943             : 
    1944           0 :     lines.clear();
    1945           0 :     std::vector<float> waypointCoords;
    1946           0 :     for (size_t i = 0; i < path.m_Waypoints.size(); ++i)
    1947             :     {
    1948           0 :         float x = path.m_Waypoints[i].x.ToFloat();
    1949           0 :         float z = path.m_Waypoints[i].z.ToFloat();
    1950           0 :         waypointCoords.push_back(x);
    1951           0 :         waypointCoords.push_back(z);
    1952           0 :         lines.push_back(SOverlayLine());
    1953           0 :         lines.back().m_Color = color;
    1954           0 :         SimRender::ConstructSquareOnGround(GetSimContext(), x, z, 1.0f, 1.0f, 0.0f, lines.back(), floating);
    1955             :     }
    1956           0 :     float x = cmpPosition->GetPosition2D().X.ToFloat();
    1957           0 :     float z = cmpPosition->GetPosition2D().Y.ToFloat();
    1958           0 :     waypointCoords.push_back(x);
    1959           0 :     waypointCoords.push_back(z);
    1960           0 :     lines.push_back(SOverlayLine());
    1961           0 :     lines.back().m_Color = color;
    1962           0 :     SimRender::ConstructLineOnGround(GetSimContext(), waypointCoords, lines.back(), floating);
    1963             : 
    1964           0 : }
    1965             : 
    1966           0 : void CCmpUnitMotion::RenderSubmit(SceneCollector& collector)
    1967             : {
    1968           0 :     if (!m_DebugOverlayEnabled)
    1969             :         return;
    1970             : 
    1971           0 :     const auto& palette{m_IsFormationController ?
    1972             :         FORMATION_CONTROLLER_PALETTE : REGULAR_UNIT_PALETTE};
    1973             : 
    1974           0 :     RenderPath(m_LongPath, m_DebugOverlayLongPathLines, palette.longPath);
    1975           0 :     RenderPath(m_ShortPath, m_DebugOverlayShortPathLines, palette.shortPath);
    1976             : 
    1977           0 :     for (SOverlayLine& line : m_DebugOverlayLongPathLines)
    1978           0 :         collector.Submit(&line);
    1979             : 
    1980           0 :     for (SOverlayLine& line : m_DebugOverlayShortPathLines)
    1981           0 :         collector.Submit(&line);
    1982             : }
    1983             : 
    1984             : #endif // INCLUDED_CCMPUNITMOTION

Generated by: LCOV version 1.16