Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
CCmpUnitMotion.h
Go to the documentation of this file.
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"
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
66namespace
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 */
76constexpr 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 */
82
83/**
84 * Minimum distance to goal for a long path request
85 */
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 */
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 */
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 */
108constexpr 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 */
117constexpr 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 */
123constexpr std::uint8_t ALTERNATE_PATH_TYPE_DELAY = 3;
124constexpr 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 */
132constexpr 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 */
138constexpr std::uint8_t VERY_OBSTRUCTED_THRESHOLD = 10;
139
141{
144};
145
146constexpr PathColorPalette REGULAR_UNIT_PALETTE{{1, 1, 1, 1}, {1, 0, 0, 1}};
147constexpr PathColorPalette FORMATION_CONTROLLER_PALETTE{{0, 0, 1, 1}, {0, 1, 0, 1}};
148} // anonymous namespace
149
150class CCmpUnitMotion final : public ICmpUnitMotion
151{
153public:
154 static void ClassInit(CComponentManager& componentManager)
155 {
156 componentManager.SubscribeToMessageType(MT_Create);
157 componentManager.SubscribeToMessageType(MT_Destroy);
158 componentManager.SubscribeToMessageType(MT_PathResult);
159 componentManager.SubscribeToMessageType(MT_OwnershipChanged);
160 componentManager.SubscribeToMessageType(MT_ValueModification);
161 componentManager.SubscribeToMessageType(MT_MovementObstructionChanged);
162 componentManager.SubscribeToMessageType(MT_Deserialized);
163 }
164
166
170
171 // Template state:
172
174
178
179 // Dynamic state:
180
182
183 // cached for efficiency
185
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.
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 {
213 LONG_PATH
214 } m_Type = SHORT_PATH; // Pick some default value to avoid UB.
215
216 void clear() { m_Ticket = 0; }
218
219 struct MoveRequest {
220 enum Type {
224 OFFSET
229
230 // For readability
232
233 MoveRequest() = default;
234 MoveRequest(CFixedVector2D pos, entity_pos_t minRange, entity_pos_t maxRange) : m_Type(POINT), m_Position(pos), m_MinRange(minRange), m_MaxRange(maxRange) {};
235 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 MoveRequest(entity_id_t target, CFixedVector2D offset) : m_Type(OFFSET), m_Entity(target), m_Position(offset) {};
238
239 // If this is not INVALID_ENTITY, the unit is a formation member.
241
242 // If the entity moves, it will do so at m_WalkSpeed * m_SpeedMultiplier.
244 // This caches the resulting speed from m_WalkSpeed * m_SpeedMultiplier for convenience.
246
247 // Mean speed over the last turn.
249
250 // The speed achieved at the end of the current turn.
252
254
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.
261
262 static std::string GetSchema()
263 {
264 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 "</optional>";
298 }
299
300 void Init(const CParamNode& paramNode) override
301 {
302 m_IsFormationController = paramNode.GetChild("FormationController").ToBool();
303
305
306 m_WalkSpeed = m_TemplateWalkSpeed = m_Speed = paramNode.GetChild("WalkSpeed").ToFixed();
309
311 if (paramNode.GetChild("RunMultiplier").IsOk())
312 m_RunMultiplier = m_TemplateRunMultiplier = paramNode.GetChild("RunMultiplier").ToFixed();
313
314 m_InstantTurnAngle = paramNode.GetChild("InstantTurnAngle").ToFixed();
315
316 m_Acceleration = m_TemplateAcceleration = paramNode.GetChild("Acceleration").ToFixed();
317
318 m_TemplateWeight = paramNode.GetChild("Weight").ToFixed();
319
320 m_PassClassName = paramNode.GetChild("PassabilityClass").ToString();
322
324 if (cmpObstruction)
325 m_BlockMovement = cmpObstruction->GetBlockMovementFlag(true);
326
327 SetParticipateInPushing(!paramNode.GetChild("DisablePushing").IsOk() || !paramNode.GetChild("DisablePushing").ToBool());
328
329 m_DebugOverlayEnabled = false;
330 }
331
332 void Deinit() override
333 {
334 }
335
336 template<typename S>
337 void SerializeCommon(S& serialize)
338 {
339 // m_Clearance and m_PassClass are constructed from this.
340 serialize.StringASCII("pass class", m_PassClassName, 0, 64);
341
342 serialize.NumberU32_Unbounded("ticket", m_ExpectedPathTicket.m_Ticket);
343 Serializer(serialize, "ticket type", m_ExpectedPathTicket.m_Type, Ticket::Type::LONG_PATH);
344
345 serialize.NumberU8_Unbounded("failed movements", m_FailedMovements);
346 serialize.NumberU8_Unbounded("followknownimperfectpath", m_FollowKnownImperfectPathCountdown);
347
348 Serializer(serialize, "target type", m_MoveRequest.m_Type, MoveRequest::Type::OFFSET);
349 serialize.NumberU32_Unbounded("target entity", m_MoveRequest.m_Entity);
350 serialize.NumberFixed_Unbounded("target pos x", m_MoveRequest.m_Position.X);
351 serialize.NumberFixed_Unbounded("target pos y", m_MoveRequest.m_Position.Y);
352 serialize.NumberFixed_Unbounded("target min range", m_MoveRequest.m_MinRange);
353 serialize.NumberFixed_Unbounded("target max range", m_MoveRequest.m_MaxRange);
354
355 serialize.NumberU32_Unbounded("formation controller", m_FormationController);
356
357 serialize.NumberFixed_Unbounded("speed multiplier", m_SpeedMultiplier);
358
359 serialize.NumberFixed_Unbounded("last turn speed", m_LastTurnSpeed);
360 serialize.NumberFixed_Unbounded("current speed", m_CurrentSpeed);
361
362 serialize.NumberFixed_Unbounded("instant turn angle", m_InstantTurnAngle);
363
364 serialize.NumberFixed_Unbounded("acceleration", m_Acceleration);
365
366 serialize.Bool("facePointAfterMove", m_FacePointAfterMove);
367 serialize.Bool("pushing", m_Pushing);
368
369 Serializer(serialize, "long path", m_LongPath.m_Waypoints);
370 Serializer(serialize, "short path", m_ShortPath.m_Waypoints);
371 }
372
373 void Serialize(ISerializer& serialize) override
374 {
375 SerializeCommon(serialize);
376 }
377
378 void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
379 {
380 Init(paramNode);
381
382 SerializeCommon(deserialize);
383
385
387 if (cmpObstruction)
388 m_BlockMovement = cmpObstruction->GetBlockMovementFlag(false);
389 }
390
391 void HandleMessage(const CMessage& msg, bool /*global*/) override
392 {
393 switch (msg.GetType())
394 {
395 case MT_RenderSubmit:
396 {
397 PROFILE("UnitMotion::RenderSubmit");
398 const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
399 RenderSubmit(msgData.collector);
400 break;
401 }
402 case MT_PathResult:
403 {
404 const CMessagePathResult& msgData = static_cast<const CMessagePathResult&> (msg);
405 PathResult(msgData.ticket, msgData.path);
406 break;
407 }
408 case MT_Create:
409 {
412 break;
413 }
414 case MT_Destroy:
415 {
418 break;
419 }
420 case MT_MovementObstructionChanged:
421 {
423 if (cmpObstruction)
424 m_BlockMovement = cmpObstruction->GetBlockMovementFlag(false);
425 break;
426 }
427 case MT_ValueModification:
428 {
429 const CMessageValueModification& msgData = static_cast<const CMessageValueModification&> (msg);
430 if (msgData.component != L"UnitMotion")
431 break;
432 [[fallthrough]];
433 }
434 case MT_OwnershipChanged:
435 {
437 break;
438 }
439 case MT_Deserialized:
440 {
442 break;
443 }
444 }
445 }
446
448 {
449 bool needRender = m_DebugOverlayEnabled;
450 GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_RenderSubmit, this, needRender);
451 }
452
453 bool IsMoveRequested() const override
454 {
456 }
457
458 bool IsMovingAsFormation() const override
459 {
461 }
462
463 fixed GetSpeedMultiplier() const override
464 {
465 return m_SpeedMultiplier;
466 }
467
468 void SetSpeedMultiplier(fixed multiplier) override
469 {
470 m_SpeedMultiplier = std::min(multiplier, m_RunMultiplier);
472 }
473
474 fixed GetSpeed() const override
475 {
476 return m_Speed;
477 }
478
479 fixed GetWalkSpeed() const override
480 {
481 return m_WalkSpeed;
482 }
483
484 fixed GetRunMultiplier() const override
485 {
486 return m_RunMultiplier;
487 }
488
490 {
492 if (!cmpPosition || !cmpPosition->IsInWorld())
493 return CFixedVector2D();
494
495 // TODO: formation members should perhaps try to use the controller's position.
496
497 CFixedVector2D pos = cmpPosition->GetPosition2D();
498 entity_angle_t angle = cmpPosition->GetRotation().Y;
499 fixed speed = m_CurrentSpeed;
500 // Copy the path so we don't change it.
501 WaypointPath shortPath = m_ShortPath;
502 WaypointPath longPath = m_LongPath;
503
504 PerformMove(dt, cmpPosition->GetTurnRate(), shortPath, longPath, pos, speed, angle, 0);
505 return pos;
506 }
507
508 fixed GetAcceleration() const override
509 {
510 return m_Acceleration;
511 }
512
513 void SetAcceleration(fixed acceleration) override
514 {
515 m_Acceleration = acceleration;
516 }
517
519 {
520 return m_TemplateWeight;
521 }
522
524 {
525 return m_PassClass;
526 }
527
528 std::string GetPassabilityClassName() const override
529 {
530 return m_PassClassName;
531 }
532
533 void SetPassabilityClassName(const std::string& passClassName) override
534 {
536 {
537 LOGWARNING("Only formation controllers can change their passability class");
538 return;
539 }
540 SetPassabilityData(passClassName);
541 }
542
543 fixed GetCurrentSpeed() const override
544 {
545 return m_CurrentSpeed;
546 }
547
548 void SetCurrentSpeed(const fixed& speed) override
549 {
550 m_CurrentSpeed = speed;
551
552 if (speed == fixed::Zero())
554 else
555 m_LastTurnSpeed = speed;
556 }
557
558 void SetFacePointAfterMove(bool facePointAfterMove) override
559 {
560 m_FacePointAfterMove = facePointAfterMove;
561 }
562
563 bool GetFacePointAfterMove() const override
564 {
566 }
567
568 void SetDebugOverlay(bool enabled) override
569 {
570 m_DebugOverlayEnabled = enabled;
572 }
573
575 {
576 return MoveTo(MoveRequest(CFixedVector2D(x, z), minRange, maxRange));
577 }
578
579 bool MoveToTargetRange(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) override
580 {
581 return MoveTo(MoveRequest(target, minRange, maxRange));
582 }
583
585 {
586 // Pass the controller to the move request anyways.
587 MoveTo(MoveRequest(controller, CFixedVector2D(x, z)));
588 }
589
590 void SetMemberOfFormation(entity_id_t controller) override
591 {
592 m_FormationController = controller;
593 }
594
595 std::optional<CFixedVector2D> GetFormationOffset() const override
596 {
598 return std::nullopt;
599
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 void StopMoving() override
613 {
615 {
617 if (cmpPosition && cmpPosition->IsInWorld())
618 {
619 CFixedVector2D targetPos;
620 if (ComputeTargetPosition(targetPos))
621 FaceTowardsPointFromPos(cmpPosition->GetPosition2D(), targetPos.X, targetPos.Y);
622 }
623 }
624
627 m_LongPath.m_Waypoints.clear();
628 m_ShortPath.m_Waypoints.clear();
629 }
630
632 {
633 return m_Clearance;
634 }
635
636private:
637 bool IsFormationMember() const
638 {
640 }
641
643 {
645 return cmpControllerMotion && cmpControllerMotion->IsMoveRequested();
646 }
647
649 {
651 }
652
653 void SetParticipateInPushing(bool pushing)
654 {
655 CmpPtr<ICmpUnitMotionManager> cmpUnitMotionManager(GetSystemEntity());
656 m_Pushing = pushing && cmpUnitMotionManager->IsPushingActivated();
657 }
658
659 void SetPassabilityData(const std::string& passClassName)
660 {
661 m_PassClassName = passClassName;
663 if (cmpPathfinder)
664 {
665 m_PassClass = cmpPathfinder->GetPassabilityClass(passClassName);
666 m_Clearance = cmpPathfinder->GetClearance(m_PassClass);
667
669 if (cmpObstruction)
670 cmpObstruction->SetUnitClearance(m_Clearance);
671 }
672 }
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 */
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).
685 return;
686
689 }
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 */
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).
702 return;
703
706 }
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 */
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).
719 return;
720
724 }
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 */
731 {
734 {
735 MoveFailed();
737 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
748 {
750 }
751
752 bool InShortPathRange(const PathGoal& goal, const CFixedVector2D& pos) const
753 {
754 return goal.DistanceToPoint(pos) < LONG_PATH_MIN_DIST;
755 }
756
758 {
759 std::uint8_t multiple = m_FailedMovements < SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY ? 0 :
762 if (searchRange > SHORT_PATH_MAX_SEARCH_RANGE)
763 searchRange = SHORT_PATH_MAX_SEARCH_RANGE;
764 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
773 {
774 CmpPtr<ICmpValueModificationManager> cmpValueModificationManager(GetSystemEntity());
775 if (!cmpValueModificationManager)
776 return;
777
778 m_WalkSpeed = cmpValueModificationManager->ApplyModifications(L"UnitMotion/WalkSpeed", m_TemplateWalkSpeed, GetEntityId());
779 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).
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
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;
827 {
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;
837 {
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 */
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 */
865 {
866 return !m_Pushing && m_BlockMovement;
867 }
868
869 /**
870 * Returns an appropriate obstruction filter for use with path requests.
871 */
873 {
875 }
876 /**
877 * Filter a specific tag on top of the existing control groups.
878 */
880 {
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
926REGISTER_COMPONENT_TYPE(UnitMotion)
927
928bool CCmpUnitMotion::RejectFartherPaths(const PathGoal& goal, const WaypointPath& path, const CFixedVector2D& pos) const
929{
930 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 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
940void CCmpUnitMotion::PathResult(std::uint32_t ticket, const WaypointPath& path)
941{
942 // Ignore obsolete path requests
944 return;
945
948
949 // If we not longer have a position, we won't be able to do much.
950 // Fail in the next Move() call.
952 if (!cmpPosition || !cmpPosition->IsInWorld())
953 return;
954 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 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 bool shortPathHack = false;
961 if (path.m_Waypoints.empty())
962 {
963 // No waypoints means pathing failed. If this was a long-path, try the short-path hack.
964 if (!pathedTowardsGoal)
965 return;
966 shortPathHack = ticketType == Ticket::LONG_PATH;
967 }
968 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 if (!m_LongPath.m_Waypoints.empty())
979 return;
980 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 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.
994
995 CFixedVector2D targetPos;
996 if (ComputeTargetPosition(targetPos))
997 m_LongPath.m_Waypoints.emplace_back(Waypoint{ targetPos.X, targetPos.Y });
998 return;
999 }
1000
1001 if (ticketType == Ticket::LONG_PATH)
1002 {
1003 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 if (m_LongPath.m_Waypoints.size() >= 2)
1009 {
1010 const Waypoint& firstWpt = m_LongPath.m_Waypoints.back();
1011 if (CFixedVector2D(firstWpt.x - pos.X, firstWpt.z - pos.Y).CompareLength(Pathfinding::NAVCELL_SIZE * 4) <= 0)
1012 {
1013 CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
1014 ENSURE(cmpPathfinder);
1015 const Waypoint& secondWpt = m_LongPath.m_Waypoints[m_LongPath.m_Waypoints.size() - 2];
1016 if (cmpPathfinder->CheckMovement(GetObstructionFilter(), pos.X, pos.Y, secondWpt.x, secondWpt.z, m_Clearance, m_PassClass))
1017 m_LongPath.m_Waypoints.pop_back();
1018 }
1019
1020 }
1021 }
1022 else
1023 m_ShortPath = path;
1024
1025 m_FollowKnownImperfectPathCountdown = 0;
1026
1027 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 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 if (!IncrementFailedMovementsAndMaybeNotify())
1043 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 m_FollowKnownImperfectPathCountdown = KNOWN_IMPERFECT_PATH_RESET_COUNTDOWN;
1047 }
1048}
1049
1051{
1053 MoveSucceeded();
1054 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 m_LongPath.m_Waypoints.clear();
1062 m_ShortPath.m_Waypoints.clear();
1063
1064 MoveFailed();
1065 }
1066}
1067
1069{
1070 state.ignore = !m_Pushing || !m_BlockMovement;
1071
1072 state.wasObstructed = false;
1073 state.wentStraight = false;
1074
1075 // If we were idle and will still be, no need for an update.
1076 state.needUpdate = state.cmpPosition->IsInWorld() &&
1078
1079 if (!m_BlockMovement)
1080 return;
1081
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.
1087 CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
1088 if (cmpObstruction)
1089 cmpObstruction->SetMovingFlag(state.isMoving);
1090}
1091
1093{
1094 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 state.wentStraight = TryGoingStraightToTarget(state.initialPos, true);
1100
1101 state.wasObstructed = PerformMove(dt, state.cmpPosition->GetTurnRate(), m_ShortPath, m_LongPath, state.pos, state.speed, state.angle, state.pushingPressure);
1102}
1103
1105{
1106 // Update our speed over this turn so that the visual actor shows the correct animation.
1107 if (state.pos == state.initialPos)
1108 {
1109 if (state.angle != state.initialAngle)
1110 state.cmpPosition->TurnTo(state.angle);
1112 }
1113 else
1114 {
1115 // Update the Position component after our movement (if we actually moved anywhere)
1116 CFixedVector2D offset = state.pos - state.initialPos;
1117 state.cmpPosition->MoveAndTurnTo(state.pos.X, state.pos.Y, state.angle);
1118
1119 // Calculate the mean speed over this past turn.
1120 UpdateMovementState(state.speed, offset.Length() / dt);
1121 }
1122
1123 if (state.wasObstructed && HandleObstructedMove(state.pos != state.initialPos))
1124 return;
1125 else if (!state.wasObstructed && state.pos != state.initialPos)
1127
1128 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 if (!needPathUpdate && !state.wasObstructed && m_LongPath.m_Waypoints.size() >= 1 && m_ShortPath.m_Waypoints.empty())
1132 {
1133 ICmpObstructionManager::tag_t specificIgnore;
1135 {
1137 if (cmpTargetObstruction)
1138 specificIgnore = cmpTargetObstruction->GetObstruction();
1139 }
1140 CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
1141 if (cmpObstructionManager && cmpObstructionManager->TestUnitLine(GetObstructionFilter(specificIgnore),
1142 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 if (m_LongPath.m_Waypoints.size() > 1) {
1149 fixed radius = Pathfinding::NAVCELL_SIZE * 2;
1150 m_LongPath.m_Waypoints.pop_back();
1151 PathGoal subgoal = { PathGoal::CIRCLE, m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z, radius };
1152 RequestShortPath(state.pos, subgoal, false);
1153 } else {
1154 // If we only have one waypoint left, request a short path to the waypoint itself.
1155 PathGoal goal;
1156 if (ComputeGoal(goal, m_MoveRequest))
1157 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 if (state.wentStraight && !state.wasObstructed)
1164 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 if (!state.wentStraight && needPathUpdate)
1169 {
1170 PathGoal goal;
1171 if (ComputeGoal(goal, m_MoveRequest))
1172 ComputePathToGoal(state.pos, goal);
1173 }
1176}
1177
1179{
1181 return false;
1182
1183 CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
1184 ENSURE(cmpObstructionManager);
1185
1186 switch (m_MoveRequest.m_Type)
1187 {
1188 case MoveRequest::POINT:
1189 return cmpObstructionManager->IsInPointRange(
1192
1194 return cmpObstructionManager->IsInTargetRange(
1197
1199 {
1201 if (cmpControllerMotion && cmpControllerMotion->IsMoveRequested())
1202 return false;
1203
1204 CFixedVector2D targetPos;
1205 ComputeTargetPosition(targetPos);
1207 return (targetPos - cmpPosition->GetPosition2D()).CompareLength(Pathfinding::NAVCELL_SIZE) <= 0;
1208 }
1209
1210 default:
1211 return false;
1212 }
1213}
1214
1215bool 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 if (shortPath.m_Waypoints.empty() && longPath.m_Waypoints.empty())
1219 return true;
1220
1221 // Wrap the angle to (-Pi, Pi].
1222 while (angle > entity_angle_t::Pi())
1223 angle -= entity_angle_t::Pi() * 2;
1224 while (angle < -entity_angle_t::Pi())
1225 angle += entity_angle_t::Pi() * 2;
1226
1227 CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
1228 ENSURE(cmpPathfinder);
1229
1230 fixed basicSpeed = m_Speed;
1231 // If in formation, run to keep up; otherwise just walk.
1232 if (IsMovingAsFormation())
1233 basicSpeed = m_Speed.Multiply(m_RunMultiplier);
1234
1235 // If pushing pressure is applied, slow the unit down.
1236 if (pushingPressure)
1237 {
1238 // Values below this pressure don't slow the unit down (avoids slowing groups down).
1239 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 constexpr int maxPressure = CCmpUnitMotionManager::MAX_PRESSURE - pressureMinThreshold - 80;
1244 constexpr entity_pos_t floorSpeed = entity_pos_t::FromFraction(3, 2);
1245 static_assert(maxPressure > 0);
1246
1247 uint8_t slowdown = maxPressure - std::min(maxPressure, std::max(0, pushingPressure - pressureMinThreshold));
1248 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 basicSpeed = std::max(std::min(m_TemplateWalkSpeed, floorSpeed), basicSpeed);
1255 }
1256
1257 // TODO: would be nice to support terrain-dependent speed again.
1258 fixed maxSpeed = basicSpeed;
1259
1260 fixed timeLeft = dt;
1261 fixed zero = fixed::Zero();
1262
1263 ICmpObstructionManager::tag_t specificIgnore;
1265 {
1267 if (cmpTargetObstruction)
1268 specificIgnore = cmpTargetObstruction->GetObstruction();
1269 }
1270
1271 while (timeLeft > zero)
1272 {
1273 // If we ran out of path, we have to stop.
1274 if (shortPath.m_Waypoints.empty() && longPath.m_Waypoints.empty())
1275 break;
1276
1277 CFixedVector2D target;
1278 if (shortPath.m_Waypoints.empty())
1279 target = CFixedVector2D(longPath.m_Waypoints.back().x, longPath.m_Waypoints.back().z);
1280 else
1281 target = CFixedVector2D(shortPath.m_Waypoints.back().x, shortPath.m_Waypoints.back().z);
1282
1283 CFixedVector2D offset = target - pos;
1284
1285 if (turnRate > zero && !offset.IsZero())
1286 {
1287 fixed angleDiff = angle - atan2_approx(offset.X, offset.Y);
1288 fixed absoluteAngleDiff = angleDiff.Absolute();
1289 if (absoluteAngleDiff > entity_angle_t::Pi())
1290 absoluteAngleDiff = entity_angle_t::Pi() * 2 - absoluteAngleDiff;
1291
1292 // We only rotate to the instantTurnAngle angle. The rest we rotate during movement.
1293 if (absoluteAngleDiff > m_InstantTurnAngle)
1294 {
1295 // Stop moving when rotating this far.
1296 speed = zero;
1297
1298 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 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 if (absoluteAngleDiff - m_InstantTurnAngle > maxRotation)
1305 {
1306 angle += maxRotation * direction;
1307 if (angle * direction > entity_angle_t::Pi())
1308 angle -= entity_angle_t::Pi() * 2 * direction;
1309 break;
1310 }
1311 // Rotate towards the next waypoint and continue moving.
1312 angle = atan2_approx(offset.X, offset.Y);
1313 timeLeft = std::min(maxRotation, maxRotation - absoluteAngleDiff + m_InstantTurnAngle) / turnRate;
1314 }
1315 else
1316 {
1317 // Modify the speed depending on the angle difference.
1318 fixed sin, cos;
1319 sincos_approx(angleDiff, sin, cos);
1320 speed = speed.Multiply(cos);
1321 angle = atan2_approx(offset.X, offset.Y);
1322 }
1323 }
1324
1325 // Work out how far we can travel in timeLeft.
1326 fixed accelTime = std::min(timeLeft, (maxSpeed - speed) / m_Acceleration);
1327 fixed accelDist = speed.Multiply(accelTime) + accelTime.Square().Multiply(m_Acceleration) / 2;
1328 fixed maxdist = accelDist + maxSpeed.Multiply(timeLeft - accelTime);
1329
1330 // If the target is close, we can move there directly.
1331 fixed offsetLength = offset.Length();
1332 if (offsetLength <= maxdist)
1333 {
1334 if (cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), pos.X, pos.Y, target.X, target.Y, m_Clearance, m_PassClass))
1335 {
1336 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 if (offsetLength <= accelDist)
1343 {
1344 fixed requiredTime = (-speed + (speed.Square() + offsetLength.Multiply(m_Acceleration).Multiply(fixed::FromInt(2))).Sqrt()) / m_Acceleration;
1345 timeLeft -= requiredTime;
1346 speed += m_Acceleration.Multiply(requiredTime);
1347 }
1348 else
1349 {
1350 timeLeft -= accelTime + (offsetLength - accelDist) / maxSpeed;
1351 speed = maxSpeed;
1352 }
1353
1354 if (shortPath.m_Waypoints.empty())
1355 longPath.m_Waypoints.pop_back();
1356 else
1357 shortPath.m_Waypoints.pop_back();
1358
1359 continue;
1360 }
1361 else
1362 {
1363 // Error - path was obstructed.
1364 return true;
1365 }
1366 }
1367 else
1368 {
1369 // Not close enough, so just move in the right direction.
1370 offset.Normalize(maxdist);
1371 target = pos + offset;
1372
1373 speed = std::min(maxSpeed, speed + m_Acceleration.Multiply(timeLeft));
1374
1375 if (cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), pos.X, pos.Y, target.X, target.Y, m_Clearance, m_PassClass))
1376 pos = target;
1377 else
1378 return true;
1379
1380 break;
1381 }
1382 }
1383 return false;
1384}
1385
1387{
1389 if (cmpVisual)
1390 {
1391 if (meanSpeed == fixed::Zero())
1392 cmpVisual->SelectMovementAnimation("idle", fixed::FromInt(1));
1393 else
1394 cmpVisual->SelectMovementAnimation(meanSpeed > (m_WalkSpeed / 2).Multiply(m_RunMultiplier + fixed::FromInt(1)) ? "run" : "walk", meanSpeed);
1395 }
1396
1397 m_LastTurnSpeed = meanSpeed;
1398 m_CurrentSpeed = speed;
1399}
1400
1402{
1404 if (!cmpPosition || !cmpPosition->IsInWorld())
1405 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 if (!moved || m_FailedMovements < 2)
1411 {
1414 }
1415
1416 PathGoal goal;
1417 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 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 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 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.
1439 {
1440 Waypoint next = m_ShortPath.m_Waypoints.back();
1441 CFixedVector2D backUp(pos.X - next.x, pos.Y - next.z);
1442 backUp.Normalize();
1443 next.x = pos.X + backUp.X;
1444 next.z = pos.Y + backUp.Y;
1445 m_ShortPath.m_Waypoints.push_back(next);
1446 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 fixed skipbeyond = std::max(ShortPathSearchRange() / 3, Pathfinding::NAVCELL_SIZE * 8);
1454 if (m_LongPath.m_Waypoints.size() > 1 &&
1455 (pos - CFixedVector2D(m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z)).CompareLength(skipbeyond) < 0)
1456 {
1457 m_LongPath.m_Waypoints.pop_back();
1458 }
1459 else if (ShouldAlternatePathfinder())
1460 {
1461 // Recompute the whole thing occasionally, in case we got stuck in a dead end from removing long waypoints.
1462 RequestLongPath(pos, goal);
1463 return true;
1464 }
1465
1466 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 fixed radius = Clamp(skipbeyond/3, Pathfinding::NAVCELL_SIZE * 4, Pathfinding::NAVCELL_SIZE * 12);
1472 PathGoal subgoal = { PathGoal::CIRCLE, m_LongPath.m_Waypoints.back().x, m_LongPath.m_Waypoints.back().z, radius };
1473 RequestShortPath(pos, subgoal, false);
1474 return true;
1475 }()) return true;
1476
1477 // If we couldn't use a workaround, try recomputing the entire path.
1478 ComputePathToGoal(pos, goal);
1479
1480 return true;
1481}
1482
1484{
1485 if (moveRequest.m_Type != MoveRequest::ENTITY)
1486 return true;
1487
1488 CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), moveRequest.m_Entity);
1489 return cmpPosition && cmpPosition->IsInWorld();
1490}
1491
1493{
1494 if (moveRequest.m_Type == MoveRequest::POINT)
1495 {
1496 out = moveRequest.m_Position;
1497 return true;
1498 }
1499
1500 CmpPtr<ICmpPosition> cmpTargetPosition(GetSimContext(), moveRequest.m_Entity);
1501 if (!cmpTargetPosition || !cmpTargetPosition->IsInWorld())
1502 return false;
1503
1504 if (moveRequest.m_Type == MoveRequest::OFFSET)
1505 {
1506 // There is an offset, so compute it relative to orientation
1507 entity_angle_t angle = cmpTargetPosition->GetRotation().Y;
1508 CFixedVector2D offset = moveRequest.GetOffset().Rotate(angle);
1509 out = cmpTargetPosition->GetPosition2D() + offset;
1510 }
1511 else
1512 {
1513 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 CmpPtr<ICmpUnitMotion> cmpUnitMotion(GetSimContext(), moveRequest.m_Entity);
1523 CmpPtr<ICmpUnitMotionManager> cmpUnitMotionManager(GetSystemEntity());
1524 bool needInterpolation = cmpUnitMotion && cmpUnitMotion->IsMoveRequested() && cmpUnitMotionManager->ComputingMotion();
1525 if (needInterpolation)
1526 {
1527 // Add predicted movement.
1528 CFixedVector2D tempPos = out + (out - cmpTargetPosition->GetPreviousPosition2D());
1529 out = tempPos;
1530 }
1531 }
1532 return true;
1533}
1534
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 if (!IsFormationMember() && !m_ShortPath.m_Waypoints.empty())
1541 return false;
1542
1543 CFixedVector2D targetPos;
1544 if (!ComputeTargetPosition(targetPos))
1545 return false;
1546
1547 CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
1548 if (!cmpPathfinder)
1549 return false;
1550
1551 // Move the goal to match the target entity's new position
1552 PathGoal goal;
1553 if (!ComputeGoal(goal, m_MoveRequest))
1554 return false;
1555 goal.x = targetPos.X;
1556 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 CFixedVector2D goalPos = goal.NearestPointOnGoal(from);
1562
1563 // Fail if the target is too far away
1564 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 ICmpObstructionManager::tag_t specificIgnore;
1571 {
1573 if (cmpTargetObstruction)
1574 specificIgnore = cmpTargetObstruction->GetObstruction();
1575 }
1576
1577 // Check movement against units - we want to use the short pathfinder to walk around those if needed.
1578 if (specificIgnore.valid())
1579 {
1580 if (!cmpPathfinder->CheckMovement(GetObstructionFilter(specificIgnore), from.X, from.Y, goalPos.X, goalPos.Y, m_Clearance, m_PassClass))
1581 return false;
1582 }
1583 else if (!cmpPathfinder->CheckMovement(GetObstructionFilter(), from.X, from.Y, goalPos.X, goalPos.Y, m_Clearance, m_PassClass))
1584 return false;
1585
1586 if (!updatePaths)
1587 return true;
1588
1589 // That route is okay, so update our path
1590 m_LongPath.m_Waypoints.clear();
1591 m_ShortPath.m_Waypoints.clear();
1592 m_ShortPath.m_Waypoints.emplace_back(Waypoint{ goalPos.X, goalPos.Y });
1593 return true;
1594}
1595
1597{
1599 return false;
1600
1601 CFixedVector2D targetPos;
1602 if (!ComputeTargetPosition(targetPos))
1603 return false;
1604
1606 return false;
1607
1609 return false;
1610
1611 // Get the obstruction shape and translate it where we estimate the target to be.
1612 ICmpObstructionManager::ObstructionSquare estimatedTargetShape;
1614 {
1616 if (cmpTargetObstruction)
1617 cmpTargetObstruction->GetObstructionSquare(estimatedTargetShape);
1618 }
1619
1620 estimatedTargetShape.x = targetPos.X;
1621 estimatedTargetShape.z = targetPos.Y;
1622
1623 CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
1625 if (cmpObstruction)
1626 cmpObstruction->GetObstructionSquare(shape);
1627
1628 // Translate our own obstruction shape to our last waypoint or our current position, lacking that.
1629 if (m_LongPath.m_Waypoints.empty() && m_ShortPath.m_Waypoints.empty())
1630 {
1631 shape.x = from.X;
1632 shape.z = from.Y;
1633 }
1634 else
1635 {
1636 const Waypoint& lastWaypoint = m_LongPath.m_Waypoints.empty() ? m_ShortPath.m_Waypoints.front() : m_LongPath.m_Waypoints.front();
1637 shape.x = lastWaypoint.x;
1638 shape.z = lastWaypoint.z;
1639 }
1640
1641 CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
1642 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 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.
1651
1652 if (cmpObstructionManager->AreShapesInRange(shape, estimatedTargetShape, minRange, maxRange, false))
1653 return false;
1654
1655 return true;
1656}
1657
1659{
1661 if (!cmpPosition || !cmpPosition->IsInWorld())
1662 return;
1663
1664 CFixedVector2D pos = cmpPosition->GetPosition2D();
1665 FaceTowardsPointFromPos(pos, x, z);
1666}
1667
1669{
1670 CFixedVector2D target(x, z);
1671 CFixedVector2D offset = target - pos;
1672 if (!offset.IsZero())
1673 {
1674 entity_angle_t angle = atan2_approx(offset.X, offset.Y);
1675
1677 if (!cmpPosition)
1678 return;
1679 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.
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 return (range > circleRadius*3);
1694}
1695
1696bool CCmpUnitMotion::ComputeGoal(PathGoal& out, const MoveRequest& moveRequest) const
1697{
1698 if (moveRequest.m_Type == MoveRequest::NONE)
1699 return false;
1700
1702 if (!cmpPosition || !cmpPosition->IsInWorld())
1703 return false;
1704
1705 CFixedVector2D pos = cmpPosition->GetPosition2D();
1706
1707 CFixedVector2D targetPosition;
1708 if (!ComputeTargetPosition(targetPosition, moveRequest))
1709 return false;
1710
1712 if (moveRequest.m_Type == MoveRequest::ENTITY)
1713 {
1714 CmpPtr<ICmpObstruction> cmpTargetObstruction(GetSimContext(), moveRequest.m_Entity);
1715 if (cmpTargetObstruction)
1716 cmpTargetObstruction->GetObstructionSquare(targetObstruction);
1717 }
1718 targetObstruction.x = targetPosition.X;
1719 targetObstruction.z = targetPosition.Y;
1720
1722 CmpPtr<ICmpObstruction> cmpObstruction(GetEntityHandle());
1723 if (cmpObstruction)
1724 cmpObstruction->GetObstructionSquare(obstruction);
1725 else
1726 {
1727 obstruction.x = pos.X;
1728 obstruction.z = pos.Y;
1729 }
1730
1731 CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSystemEntity());
1732 ENSURE(cmpObstructionManager);
1733
1734 out.x = targetObstruction.x;
1735 out.z = targetObstruction.z;
1736 out.hw = targetObstruction.hw;
1737 out.hh = targetObstruction.hh;
1738 out.u = targetObstruction.u;
1739 out.v = targetObstruction.v;
1740
1741 if (moveRequest.m_MinRange > fixed::Zero() || moveRequest.m_MaxRange > fixed::Zero() ||
1742 targetObstruction.hw > fixed::Zero())
1743 out.type = PathGoal::SQUARE;
1744 else
1745 {
1746 out.type = PathGoal::POINT;
1747 return true;
1748 }
1749
1750 entity_pos_t distance = cmpObstructionManager->DistanceBetweenShapes(obstruction, targetObstruction);
1751
1752 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 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 entity_pos_t goalDistance = moveRequest.m_MinRange + m_Clearance * 3 / 2;
1766
1767 if (ShouldTreatTargetAsCircle(moveRequest.m_MinRange, circleRadius))
1768 {
1769 // We are safely away from the obstruction itself if we are away from the circumscribing circle
1771 out.hw = circleRadius + goalDistance;
1772 }
1773 else
1774 {
1776 out.hw = targetObstruction.hw + goalDistance;
1777 out.hh = targetObstruction.hh + goalDistance;
1778 }
1779 }
1780 else if (moveRequest.m_MaxRange >= fixed::Zero() && distance > moveRequest.m_MaxRange)
1781 {
1782 if (ShouldTreatTargetAsCircle(moveRequest.m_MaxRange, circleRadius))
1783 {
1784 entity_pos_t goalDistance = moveRequest.m_MaxRange;
1785 // We must go in-range of the inscribed circle, not the circumscribing circle.
1786 circleRadius = std::min(targetObstruction.hw, targetObstruction.hh);
1787
1788 out.type = PathGoal::CIRCLE;
1789 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 entity_pos_t goalDistance = moveRequest.m_MaxRange * 2 / 3; // multiply by slightly less than 1/sqrt(2)
1797
1798 out.type = PathGoal::SQUARE;
1799 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 out.hw = targetObstruction.hw + delta;
1801 out.hh = targetObstruction.hh + delta;
1802 }
1803 }
1804 // Do nothing in particular in case we are already in range.
1805 return true;
1806}
1807
1809{
1810#if DISABLE_PATHFINDER
1811 {
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.
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 m_ShortPath.m_Waypoints.clear();
1829 RequestLongPath(from, goal);
1830 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 bool shortPath = InShortPathRange(goal, from);
1845 shortPath = !shortPath;
1846 if (shortPath)
1847 {
1848 m_LongPath.m_Waypoints.clear();
1849 // Extend the range so that our first path is probably valid.
1850 RequestShortPath(from, goal, true);
1851 }
1852 else
1853 {
1854 m_ShortPath.m_Waypoints.clear();
1855 RequestLongPath(from, goal);
1856 }
1857}
1858
1860{
1861 CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
1862 if (!cmpPathfinder)
1863 return;
1864
1865 // this is by how much our waypoints will be apart at most.
1866 // this value here seems sensible enough.
1867 PathGoal improvedGoal = goal;
1869
1870 cmpPathfinder->SetDebugPath(from.X, from.Y, improvedGoal, m_PassClass);
1871
1873 m_ExpectedPathTicket.m_Ticket = cmpPathfinder->ComputePathAsync(from.X, from.Y, improvedGoal, m_PassClass, GetEntityId());
1874}
1875
1876void CCmpUnitMotion::RequestShortPath(const CFixedVector2D &from, const PathGoal& goal, bool extendRange)
1877{
1878 CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
1879 if (!cmpPathfinder)
1880 return;
1881
1882 entity_pos_t searchRange = ShortPathSearchRange();
1883 if (extendRange)
1884 {
1885 CFixedVector2D dist(from.X - goal.x, from.Y - goal.z);
1886 if (dist.CompareLength(searchRange - entity_pos_t::FromInt(1)) >= 0)
1887 {
1888 searchRange = dist.Length() + fixed::FromInt(1);
1889 if (searchRange > SHORT_PATH_MAX_SEARCH_RANGE)
1890 searchRange = SHORT_PATH_MAX_SEARCH_RANGE;
1891 }
1892 }
1893
1895 m_ExpectedPathTicket.m_Ticket = cmpPathfinder->ComputeShortPathAsync(from.X, from.Y, m_Clearance, searchRange, goal, m_PassClass, ShouldCollideWithMovingUnits(), GetGroup(), GetEntityId());
1896}
1897
1899{
1900 PROFILE("MoveTo");
1901
1902 if (request.m_MinRange == request.m_MaxRange && !request.m_MinRange.IsZero())
1903 LOGWARNING("MaxRange must be larger than MinRange; See CCmpUnitMotion.cpp for more information");
1904
1906 if (!cmpPosition || !cmpPosition->IsInWorld())
1907 return false;
1908
1909 PathGoal goal;
1910 if (!ComputeGoal(goal, request))
1911 return false;
1912
1913 m_MoveRequest = request;
1916
1917 ComputePathToGoal(cmpPosition->GetPosition2D(), goal);
1918 return true;
1919}
1920
1922{
1924 if (!cmpPosition || !cmpPosition->IsInWorld())
1925 return false;
1926
1927 MoveRequest request(target, minRange, maxRange);
1928 PathGoal goal;
1929 if (!ComputeGoal(goal, request))
1930 return false;
1931
1933 CFixedVector2D pos = cmpPosition->GetPosition2D();
1934 return cmpPathfinder->IsGoalReachable(pos.X, pos.Y, goal, m_PassClass);
1935}
1936
1937void CCmpUnitMotion::RenderPath(const WaypointPath& path, std::vector<SOverlayLine>& lines, CColor color)
1938{
1939 bool floating = false;
1941 if (cmpPosition)
1942 floating = cmpPosition->CanFloat();
1943
1944 lines.clear();
1945 std::vector<float> waypointCoords;
1946 for (size_t i = 0; i < path.m_Waypoints.size(); ++i)
1947 {
1948 float x = path.m_Waypoints[i].x.ToFloat();
1949 float z = path.m_Waypoints[i].z.ToFloat();
1950 waypointCoords.push_back(x);
1951 waypointCoords.push_back(z);
1952 lines.push_back(SOverlayLine());
1953 lines.back().m_Color = color;
1954 SimRender::ConstructSquareOnGround(GetSimContext(), x, z, 1.0f, 1.0f, 0.0f, lines.back(), floating);
1955 }
1956 float x = cmpPosition->GetPosition2D().X.ToFloat();
1957 float z = cmpPosition->GetPosition2D().Y.ToFloat();
1958 waypointCoords.push_back(x);
1959 waypointCoords.push_back(z);
1960 lines.push_back(SOverlayLine());
1961 lines.back().m_Color = color;
1962 SimRender::ConstructLineOnGround(GetSimContext(), waypointCoords, lines.back(), floating);
1963
1964}
1965
1967{
1969 return;
1970
1971 const auto& palette{m_IsFormationController ?
1973
1976
1978 collector.Submit(&line);
1979
1981 collector.Submit(&line);
1982}
1983
1984#endif // INCLUDED_CCMPUNITMOTION
#define LOGWARNING(fmtstring,...)
Definition: CLogger.h:41
#define DEFAULT_COMPONENT_ALLOCATOR(cname)
Definition: Component.h:39
#define REGISTER_COMPONENT_TYPE(cname)
Definition: Component.h:32
CFixed_15_16 atan2_approx(CFixed_15_16 y, CFixed_15_16 x)
Inaccurate approximation of atan2 over fixed-point numbers.
Definition: Fixed.cpp:149
void sincos_approx(CFixed_15_16 a, CFixed_15_16 &sin_out, CFixed_15_16 &cos_out)
Compute sin(a) and cos(a).
Definition: Fixed.cpp:189
T Clamp(T value, T min, T max)
Definition: MathUtil.h:34
std::uint16_t pass_class_t
Definition: Pathfinding.h:33
Entity coordinate types.
#define PROFILE(name)
Definition: Profile.h:157
Helper templates definitions for serializing/deserializing common objects.
void Serializer(S &serialize, const char *name, Args &&... args)
Definition: SerializeTemplates.h:51
Provide specializations for some generic types and containers.
Definition: CCmpUnitMotionManager.h:38
static constexpr int MAX_PRESSURE
Maximum value for pushing pressure.
Definition: CCmpUnitMotionManager.h:47
Definition: CCmpUnitMotion.h:151
bool MoveTo(MoveRequest request)
General handler for MoveTo interface functions.
Definition: CCmpUnitMotion.h:1898
bool m_IsFormationController
Definition: CCmpUnitMotion.h:173
void Init(const CParamNode &paramNode) override
Definition: CCmpUnitMotion.h:300
fixed m_CurrentSpeed
Definition: CCmpUnitMotion.h:251
void PathResult(std::uint32_t ticket, const WaypointPath &path)
Handle the result of an asynchronous path query.
Definition: CCmpUnitMotion.h:940
bool ComputeGoal(PathGoal &out, const MoveRequest &moveRequest) const
Create a PathGoal from a move request.
Definition: CCmpUnitMotion.h:1696
entity_pos_t GetWeight() const
Definition: CCmpUnitMotion.h:518
bool MoveToPointRange(entity_pos_t x, entity_pos_t z, entity_pos_t minRange, entity_pos_t maxRange) override
Attempt to walk into range of a to a given point, or as close as possible.
Definition: CCmpUnitMotion.h:574
CFixedVector2D EstimateFuturePosition(const fixed dt) const override
Definition: CCmpUnitMotion.h:489
bool ShouldTreatTargetAsCircle(entity_pos_t range, entity_pos_t circleRadius) const
Decide whether to approximate the given range from a square target as a circle, rather than as a squa...
Definition: CCmpUnitMotion.h:1686
static std::string GetSchema()
Definition: CCmpUnitMotion.h:262
void SetDebugOverlay(bool enabled) override
Toggle the rendering of debug info.
Definition: CCmpUnitMotion.h:568
fixed GetRunMultiplier() const override
Get the unit template running (i.e.
Definition: CCmpUnitMotion.h:484
bool GetFacePointAfterMove() const override
Definition: CCmpUnitMotion.h:563
fixed GetCurrentSpeed() const override
Get the speed at the end of the current turn.
Definition: CCmpUnitMotion.h:543
fixed m_Acceleration
Definition: CCmpUnitMotion.h:255
void RequestShortPath(const CFixedVector2D &from, const PathGoal &goal, bool extendRange)
Start an asynchronous short path query.
Definition: CCmpUnitMotion.h:1876
std::uint8_t m_FailedMovements
Definition: CCmpUnitMotion.h:198
bool InShortPathRange(const PathGoal &goal, const CFixedVector2D &pos) const
Definition: CCmpUnitMotion.h:752
bool TryGoingStraightToTarget(const CFixedVector2D &from, bool updatePaths)
Attempts to replace the current path with a straight line to the target, if it's close enough and the...
Definition: CCmpUnitMotion.h:1535
WaypointPath m_LongPath
Definition: CCmpUnitMotion.h:259
bool PossiblyAtDestination() const override
Returns true if we are possibly at our destination.
Definition: CCmpUnitMotion.h:1178
struct CCmpUnitMotion::Ticket m_ExpectedPathTicket
void Deinit() override
Definition: CCmpUnitMotion.h:332
SkipTagAndControlGroupObstructionFilter GetObstructionFilter(const ICmpObstructionManager::tag_t &tag) const
Filter a specific tag on top of the existing control groups.
Definition: CCmpUnitMotion.h:879
bool ComputeTargetPosition(CFixedVector2D &out) const
Definition: CCmpUnitMotion.h:836
fixed GetWalkSpeed() const override
Get the unit template walk speed after modifications.
Definition: CCmpUnitMotion.h:479
void StopMoving() override
Clears the current MoveRequest - the unit will stop and no longer try and move.
Definition: CCmpUnitMotion.h:612
bool IsFormationControllerMoving() const
Definition: CCmpUnitMotion.h:642
fixed m_LastTurnSpeed
Definition: CCmpUnitMotion.h:248
bool ShouldAlternatePathfinder() const
Definition: CCmpUnitMotion.h:747
bool m_Pushing
Definition: CCmpUnitMotion.h:189
void Deserialize(const CParamNode &paramNode, IDeserializer &deserialize) override
Definition: CCmpUnitMotion.h:378
static void ClassInit(CComponentManager &componentManager)
Definition: CCmpUnitMotion.h:154
std::string m_PassClassName
Definition: CCmpUnitMotion.h:177
entity_pos_t ShortPathSearchRange() const
Definition: CCmpUnitMotion.h:757
bool IsMovingAsFormation() const override
Definition: CCmpUnitMotion.h:458
fixed m_InstantTurnAngle
Definition: CCmpUnitMotion.h:253
void ComputePathToGoal(const CFixedVector2D &from, const PathGoal &goal)
Compute a path to the given goal from the given position.
Definition: CCmpUnitMotion.h:1808
void RenderPath(const WaypointPath &path, std::vector< SOverlayLine > &lines, CColor color)
Convert a path into a renderable list of lines.
Definition: CCmpUnitMotion.h:1937
fixed m_RunMultiplier
Definition: CCmpUnitMotion.h:184
void SetParticipateInPushing(bool pushing)
Definition: CCmpUnitMotion.h:653
void OnTurnStart()
Check if we are at destination early in the turn, this both lets units react faster and ensure that d...
Definition: CCmpUnitMotion.h:1050
fixed m_SpeedMultiplier
Definition: CCmpUnitMotion.h:243
void RenderSubmit(SceneCollector &collector)
Definition: CCmpUnitMotion.h:1966
std::string GetPassabilityClassName() const override
Get the passability class name (as defined in pathfinder.xml)
Definition: CCmpUnitMotion.h:528
struct CCmpUnitMotion::MoveRequest m_MoveRequest
bool IsMoveRequested() const override
Definition: CCmpUnitMotion.h:453
bool ShouldCollideWithMovingUnits() const
Units in 'pushing' mode are marked as 'moving' in the obstruction manager.
Definition: CCmpUnitMotion.h:864
entity_id_t GetGroup() const
Definition: CCmpUnitMotion.h:648
void FaceTowardsPointFromPos(const CFixedVector2D &pos, entity_pos_t x, entity_pos_t z)
Rotate to face towards the target point, given the current pos.
Definition: CCmpUnitMotion.h:1668
void RequestLongPath(const CFixedVector2D &from, const PathGoal &goal)
Start an asynchronous long path query.
Definition: CCmpUnitMotion.h:1859
fixed m_WalkSpeed
Definition: CCmpUnitMotion.h:184
bool m_BlockMovement
Definition: CCmpUnitMotion.h:193
void SetPassabilityClassName(const std::string &passClassName) override
Sets the passability class name (as defined in pathfinder.xml)
Definition: CCmpUnitMotion.h:533
pass_class_t m_PassClass
Definition: CCmpUnitMotion.h:176
void SetAcceleration(fixed acceleration) override
Set the current acceleration.
Definition: CCmpUnitMotion.h:513
bool HandleObstructedMove(bool moved)
React if our move was obstructed.
Definition: CCmpUnitMotion.h:1401
std::vector< SOverlayLine > m_DebugOverlayShortPathLines
Definition: CCmpUnitMotion.h:169
bool m_DebugOverlayEnabled
Definition: CCmpUnitMotion.h:167
std::optional< CFixedVector2D > GetFormationOffset() const override
Get the current formation offset if this unit is moving as a formation member.
Definition: CCmpUnitMotion.h:595
bool PathingUpdateNeeded(const CFixedVector2D &from) const
Returns whether our we need to recompute a path to reach our target.
Definition: CCmpUnitMotion.h:1596
std::vector< SOverlayLine > m_DebugOverlayLongPathLines
Definition: CCmpUnitMotion.h:168
bool IsFormationMember() const
Definition: CCmpUnitMotion.h:637
void SetPassabilityData(const std::string &passClassName)
Definition: CCmpUnitMotion.h:659
void HandleMessage(const CMessage &msg, bool) override
Definition: CCmpUnitMotion.h:391
void MoveFailed()
Warns other components that our current movement will likely fail (e.g.
Definition: CCmpUnitMotion.h:679
fixed m_Speed
Definition: CCmpUnitMotion.h:245
bool IncrementFailedMovementsAndMaybeNotify()
Increment the number of failed movements and notify other components if required.
Definition: CCmpUnitMotion.h:730
void MoveToFormationOffset(entity_id_t controller, entity_pos_t x, entity_pos_t z) override
Join a formation, and move towards a given offset relative to the formation controller entity.
Definition: CCmpUnitMotion.h:584
bool PerformMove(fixed dt, const fixed &turnRate, WaypointPath &shortPath, WaypointPath &longPath, CFixedVector2D &pos, fixed &speed, entity_angle_t &angle, uint8_t pushingPressure) const
Process the move the unit will do this turn.
Definition: CCmpUnitMotion.h:1215
void Move(CCmpUnitMotionManager::MotionState &state, fixed dt)
Definition: CCmpUnitMotion.h:1092
fixed m_TemplateRunMultiplier
Definition: CCmpUnitMotion.h:175
void SetSpeedMultiplier(fixed multiplier) override
Set the current movement speed.
Definition: CCmpUnitMotion.h:468
fixed m_TemplateWeight
Definition: CCmpUnitMotion.h:175
void MoveObstructed()
Warns other components that our current movement was obstructed (i.e.
Definition: CCmpUnitMotion.h:713
WaypointPath m_ShortPath
Definition: CCmpUnitMotion.h:260
void SerializeCommon(S &serialize)
Definition: CCmpUnitMotion.h:337
bool m_FacePointAfterMove
Definition: CCmpUnitMotion.h:186
void PreMove(CCmpUnitMotionManager::MotionState &state)
Definition: CCmpUnitMotion.h:1068
void Serialize(ISerializer &serialize) override
Definition: CCmpUnitMotion.h:373
void MoveSucceeded()
Warns other components that our current movement is likely over (i.e.
Definition: CCmpUnitMotion.h:696
void UpdateMessageSubscriptions()
Definition: CCmpUnitMotion.h:447
void SetCurrentSpeed(const fixed &speed) override
Set the speed.
Definition: CCmpUnitMotion.h:548
fixed m_TemplateAcceleration
Definition: CCmpUnitMotion.h:175
void FaceTowardsPoint(entity_pos_t x, entity_pos_t z) override
Turn to look towards the given point.
Definition: CCmpUnitMotion.h:1658
void SetMemberOfFormation(entity_id_t controller) override
Set/unset the unit as a formation member.
Definition: CCmpUnitMotion.h:590
fixed GetSpeedMultiplier() const override
Returns the ratio of GetSpeed() / GetWalkSpeed().
Definition: CCmpUnitMotion.h:463
void SetFacePointAfterMove(bool facePointAfterMove) override
Set whether the unit will turn to face the target point after finishing moving.
Definition: CCmpUnitMotion.h:558
fixed GetAcceleration() const override
Get the current acceleration.
Definition: CCmpUnitMotion.h:508
entity_pos_t m_Clearance
Definition: CCmpUnitMotion.h:181
fixed m_TemplateWalkSpeed
Definition: CCmpUnitMotion.h:175
void UpdateMovementState(entity_pos_t speed, entity_pos_t meanSpeed)
Update other components on our speed.
Definition: CCmpUnitMotion.h:1386
bool RejectFartherPaths(const PathGoal &goal, const WaypointPath &path, const CFixedVector2D &pos) const
If path would take us farther away from the goal than pos currently is, return false,...
Definition: CCmpUnitMotion.h:928
pass_class_t GetPassabilityClass() const override
Get the unit's passability class.
Definition: CCmpUnitMotion.h:523
std::uint8_t m_FollowKnownImperfectPathCountdown
Definition: CCmpUnitMotion.h:207
void OnValueModification()
Definition: CCmpUnitMotion.h:772
entity_pos_t GetUnitClearance() const override
Get the unit clearance (used by the Obstruction component)
Definition: CCmpUnitMotion.h:631
bool ComputeTargetPosition(CFixedVector2D &out, const MoveRequest &moveRequest) const
Computes the current location of our target entity (plus offset).
Definition: CCmpUnitMotion.h:1492
entity_id_t m_FormationController
Definition: CCmpUnitMotion.h:240
fixed GetSpeed() const override
Get the speed at which the unit intends to move.
Definition: CCmpUnitMotion.h:474
ControlGroupMovementObstructionFilter GetObstructionFilter() const
Returns an appropriate obstruction filter for use with path requests.
Definition: CCmpUnitMotion.h:872
bool TargetHasValidPosition() const
Definition: CCmpUnitMotion.h:826
bool MoveToTargetRange(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) override
Attempt to walk into range of a given target entity, or as close as possible.
Definition: CCmpUnitMotion.h:579
bool IsTargetRangeReachable(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange) override
Check if the target is reachable.
Definition: CCmpUnitMotion.h:1921
void PostMove(CCmpUnitMotionManager::MotionState &state, fixed dt)
Definition: CCmpUnitMotion.h:1104
Definition: ComponentManager.h:46
void PostMessage(entity_id_t ent, const CMessage &msg)
Send a message, targeted at a particular entity.
Definition: ComponentManager.cpp:1050
void SubscribeToMessageType(MessageTypeId mtid)
Subscribe the current component type to the given message type.
Definition: ComponentManager.cpp:576
void DynamicSubscriptionNonsync(MessageTypeId mtid, IComponent *component, bool enabled)
Subscribe the given component instance to all messages of the given message type.
Definition: ComponentManager.cpp:616
Definition: FixedVector2D.h:25
fixed X
Definition: FixedVector2D.h:27
int CompareLength(fixed cmp) const
Returns -1, 0, +1 depending on whether length is less/equal/greater than the argument.
Definition: FixedVector2D.h:122
CFixedVector2D Rotate(fixed angle) const
Rotate the vector by the given angle (anticlockwise).
Definition: FixedVector2D.h:241
fixed Length() const
Returns the length of the vector.
Definition: FixedVector2D.h:101
fixed Y
Definition: FixedVector2D.h:27
bool IsZero() const
Definition: FixedVector2D.h:172
void Normalize()
Normalize the vector so that length is close to 1.
Definition: FixedVector2D.h:181
A simple fixed-point number class.
Definition: Fixed.h:129
static constexpr CFixed FromFraction(int n, int d)
Definition: Fixed.h:155
constexpr CFixed Absolute() const
Definition: Fixed.h:325
static CFixed Zero()
Definition: Fixed.h:140
constexpr CFixed Square() const
Multiply the value by itself.
Definition: Fixed.h:343
CFixed Multiply(CFixed n) const
Multiply by a CFixed.
Definition: Fixed.h:331
constexpr bool IsZero() const
Returns true if the number is precisely 0.
Definition: Fixed.h:218
static constexpr CFixed FromInt(int n)
Definition: Fixed.h:149
static CFixed Pi()
Definition: Fixed.cpp:184
Sent by CCmpUnitMotion during Update if an event happened that might interest other components.
Definition: MessageTypes.h:313
@ LIKELY_FAILURE
Definition: MessageTypes.h:319
@ VERY_OBSTRUCTED
Definition: MessageTypes.h:321
@ LIKELY_SUCCESS
Definition: MessageTypes.h:318
@ OBSTRUCTED
Definition: MessageTypes.h:320
Sent by CCmpPathfinder after async path requests.
Definition: MessageTypes.h:470
WaypointPath path
Definition: MessageTypes.h:480
std::uint32_t ticket
Definition: MessageTypes.h:479
Add renderable objects to the scene collector.
Definition: MessageTypes.h:155
SceneCollector & collector
Definition: MessageTypes.h:164
Sent by aura manager when a value of a certain entity's component is changed.
Definition: MessageTypes.h:487
std::wstring component
Definition: MessageTypes.h:499
Definition: Message.h:31
virtual int GetType() const =0
An entity initialisation parameter node.
Definition: ParamNode.h:153
bool ToBool() const
Parses the content of this node as a boolean ("true" == true, anything else == false)
Definition: ParamNode.cpp:310
const CParamNode & GetChild(const char *name) const
Returns the (unique) child node with the given name, or a node with IsOk() == false if there is none.
Definition: ParamNode.cpp:267
const std::string & ToString() const
Returns the content of this node as an UTF8 string.
Definition: ParamNode.cpp:285
bool IsOk() const
Returns true if this is a valid CParamNode, false if it represents a non-existent node.
Definition: ParamNode.cpp:275
fixed ToFixed() const
Parses the content of this node as a fixed-point number.
Definition: ParamNode.cpp:300
CComponentManager & GetComponentManager() const
Definition: SimContext.cpp:37
A simplified syntax for accessing entity components.
Definition: CmpPtr.h:58
Obstruction test filter that reject shapes in a given control group, and rejects shapes that don't bl...
Definition: ICmpObstructionManager.h:406
Motion interface for entities with complex movement capabilities.
Definition: ICmpUnitMotion.h:41
entity_id_t GetEntityId() const
Definition: IComponent.h:57
const CSimContext & GetSimContext() const
Definition: IComponent.h:61
CEntityHandle GetEntityHandle() const
Definition: IComponent.h:54
CEntityHandle GetSystemEntity() const
Definition: IComponent.h:59
Deserialization interface; see serialization overview.
Definition: IDeserializer.h:40
Serialization interface; see serialization overview.
Definition: ISerializer.h:126
Pathfinder goal.
Definition: PathGoal.h:34
@ SQUARE
Definition: PathGoal.h:40
@ CIRCLE
Definition: PathGoal.h:38
@ INVERTED_CIRCLE
Definition: PathGoal.h:39
@ INVERTED_SQUARE
Definition: PathGoal.h:41
@ POINT
Definition: PathGoal.h:37
fixed DistanceToPoint(CFixedVector2D pos) const
Returns the minimum distance from the point pos to any point on the goal shape.
Definition: PathGoal.cpp:296
CFixedVector2D NearestPointOnGoal(CFixedVector2D pos) const
Returns the coordinates of the point on the goal that is closest to the point pos.
Definition: PathGoal.cpp:329
entity_pos_t z
Definition: PathGoal.h:44
entity_pos_t maxdist
Definition: PathGoal.h:50
entity_pos_t x
Definition: PathGoal.h:44
This interface accepts renderable objects.
Definition: Scene.h:90
virtual void Submit(CPatch *patch)=0
Submit a terrain patch that is part of the scene.
Similar to ControlGroupMovementObstructionFilter, but also ignoring a specific tag.
Definition: ICmpObstructionManager.h:547
#define ENSURE(expr)
ensure the expression <expr> evaluates to non-zero.
Definition: debug.h:222
enum PS::Loader::anonymous_namespace{Loader.cpp}::@26 state
constexpr fixed NAVCELL_SIZE
The long-range pathfinder operates primarily over a navigation grid (a uniform-cost 2D passability gr...
Definition: Pathfinding.h:145
constexpr int NAVCELL_SIZE_INT
Definition: Pathfinding.h:146
void ConstructSquareOnGround(const CSimContext &context, float x, float z, float w, float h, float a, SOverlayLine &overlay, bool floating, float heightOffset=0.25f)
Constructs overlay line as rectangle with given center and dimensions, conforming to terrain.
Definition: Render.cpp:160
void ConstructLineOnGround(const CSimContext &context, const std::vector< float > &xz, SOverlayLine &overlay, bool floating, float heightOffset=0.25f)
Constructs overlay line from given points, conforming to terrain.
Definition: Render.cpp:45
constexpr std::uint8_t SHORT_PATH_SEARCH_RANGE_INCREASE_DELAY
Definition: CCmpUnitMotion.h:76
constexpr entity_pos_t SHORT_PATH_MIN_SEARCH_RANGE
Min/Max range to restrict short path queries to.
Definition: CCmpUnitMotion.h:73
constexpr std::uint8_t ALTERNATE_PATH_TYPE_DELAY
When computing paths but failing to move, we want to occasionally alternate pathfinder systems to avo...
Definition: CCmpUnitMotion.h:123
constexpr std::uint8_t MAX_FAILED_MOVEMENTS
When we fail to move this many turns in a row, inform other components that the move will fail.
Definition: CCmpUnitMotion.h:117
constexpr entity_pos_t DIRECT_PATH_RANGE
If we are this close to our target entity/point, then think about heading for it in a straight line i...
Definition: CCmpUnitMotion.h:92
constexpr entity_pos_t TARGET_UNCERTAINTY_MULTIPLIER
To avoid recomputing paths too often, have some leeway for target range checks based on our distance ...
Definition: CCmpUnitMotion.h:99
constexpr entity_pos_t SHORT_PATH_MAX_SEARCH_RANGE
Definition: CCmpUnitMotion.h:74
constexpr std::uint8_t VERY_OBSTRUCTED_THRESHOLD
After this many failed computations, start sending "VERY_OBSTRUCTED" messages instead.
Definition: CCmpUnitMotion.h:138
constexpr entity_pos_t SHORT_PATH_LONG_WAYPOINT_RANGE
When using the short-pathfinder to rejoin a long-path waypoint, aim for a circle of this radius aroun...
Definition: CCmpUnitMotion.h:81
constexpr std::uint8_t BACKUP_HACK_DELAY
Units can occasionally get stuck near corners.
Definition: CCmpUnitMotion.h:132
constexpr PathColorPalette FORMATION_CONTROLLER_PALETTE
Definition: CCmpUnitMotion.h:147
constexpr std::uint8_t KNOWN_IMPERFECT_PATH_RESET_COUNTDOWN
When following a known imperfect path (i.e.
Definition: CCmpUnitMotion.h:108
constexpr PathColorPalette REGULAR_UNIT_PALETTE
Definition: CCmpUnitMotion.h:146
constexpr std::uint8_t ALTERNATE_PATH_TYPE_EVERY
Definition: CCmpUnitMotion.h:124
constexpr entity_pos_t SHORT_PATH_SEARCH_RANGE_INCREMENT
Definition: CCmpUnitMotion.h:75
constexpr entity_pos_t LONG_PATH_MIN_DIST
Minimum distance to goal for a long path request.
Definition: CCmpUnitMotion.h:86
Definition: ShaderDefines.cpp:43
const entity_id_t INVALID_ENTITY
Invalid entity ID.
Definition: Entity.h:35
const entity_id_t SYSTEM_ENTITY
Entity ID for singleton 'system' components.
Definition: Entity.h:43
std::uint32_t entity_id_t
Entity ID type.
Definition: Entity.h:29
#define ENTITY_IS_LOCAL(id)
Definition: Entity.h:59
Definition: CCmpUnitMotionManager.h:51
Definition: CCmpUnitMotion.h:219
entity_id_t m_Entity
Definition: CCmpUnitMotion.h:226
CFixedVector2D m_Position
Definition: CCmpUnitMotion.h:227
entity_pos_t m_MinRange
Definition: CCmpUnitMotion.h:228
entity_pos_t m_MaxRange
Definition: CCmpUnitMotion.h:228
MoveRequest(entity_id_t target, CFixedVector2D offset)
Definition: CCmpUnitMotion.h:236
CFixedVector2D GetOffset() const
Definition: CCmpUnitMotion.h:231
MoveRequest(CFixedVector2D pos, entity_pos_t minRange, entity_pos_t maxRange)
Definition: CCmpUnitMotion.h:234
enum CCmpUnitMotion::MoveRequest::Type m_Type
MoveRequest(entity_id_t target, entity_pos_t minRange, entity_pos_t maxRange)
Definition: CCmpUnitMotion.h:235
Type
Definition: CCmpUnitMotion.h:220
@ ENTITY
Definition: CCmpUnitMotion.h:223
@ NONE
Definition: CCmpUnitMotion.h:221
@ OFFSET
Definition: CCmpUnitMotion.h:224
@ POINT
Definition: CCmpUnitMotion.h:222
Definition: CCmpUnitMotion.h:209
void clear()
Definition: CCmpUnitMotion.h:216
std::uint32_t m_Ticket
Definition: CCmpUnitMotion.h:210
Type
Definition: CCmpUnitMotion.h:211
@ LONG_PATH
Definition: CCmpUnitMotion.h:213
@ SHORT_PATH
Definition: CCmpUnitMotion.h:212
enum CCmpUnitMotion::Ticket::Type m_Type
Definition: Color.h:46
Standard representation for all types of shapes, for use with geometry processing code.
Definition: ICmpObstructionManager.h:70
CFixedVector2D u
Definition: ICmpObstructionManager.h:72
entity_pos_t z
Definition: ICmpObstructionManager.h:71
entity_pos_t hw
Definition: ICmpObstructionManager.h:73
entity_pos_t hh
Definition: ICmpObstructionManager.h:73
entity_pos_t x
Definition: ICmpObstructionManager.h:71
CFixedVector2D v
Definition: ICmpObstructionManager.h:72
External identifiers for shapes.
Definition: ICmpObstructionManager.h:81
bool valid() const
Definition: ICmpObstructionManager.h:84
Line-based overlay, with world-space coordinates, rendered in the world potentially behind other obje...
Definition: Overlay.h:42
Returned path.
Definition: Pathfinding.h:69
std::vector< Waypoint > m_Waypoints
Definition: Pathfinding.h:70
Definition: Pathfinding.h:60
entity_pos_t x
Definition: Pathfinding.h:61
entity_pos_t z
Definition: Pathfinding.h:61
CColor longPath
Definition: CCmpUnitMotion.h:142
CColor shortPath
Definition: CCmpUnitMotion.h:143
static void out(const wchar_t *fmt,...)
Definition: wdbg_sym.cpp:407