Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ICmpPosition.h"
21 :
22 : #include "maths/BoundingBoxOriented.h"
23 : #include "maths/Fixed.h"
24 : #include "maths/FixedVector2D.h"
25 : #include "maths/FixedVector3D.h"
26 : #include "maths/MathUtil.h"
27 : #include "maths/Matrix3D.h"
28 : #include "maths/Vector2D.h"
29 : #include "maths/Vector3D.h"
30 : #include "ps/CLogger.h"
31 : #include "ps/CStr.h"
32 : #include "ps/Profile.h"
33 : #include "simulation2/MessageTypes.h"
34 : #include "simulation2/components/ICmpTerrain.h"
35 : #include "simulation2/components/ICmpVisual.h"
36 : #include "simulation2/components/ICmpWaterManager.h"
37 : #include "simulation2/helpers/Position.h"
38 : #include "simulation2/serialization/SerializeTemplates.h"
39 : #include "simulation2/serialization/SerializedTypes.h"
40 : #include "simulation2/system/Component.h"
41 : #include "simulation2/system/Entity.h"
42 : #include "simulation2/system/Message.h"
43 :
44 : #include <algorithm>
45 : #include <cmath>
46 : #include <numbers>
47 : #include <set>
48 : #include <string>
49 : #include <utility>
50 :
51 : /**
52 : * Basic ICmpPosition implementation.
53 : */
54 201 : class CCmpPosition final : public ICmpPosition
55 : {
56 : public:
57 137 : static void ClassInit(CComponentManager& componentManager)
58 : {
59 137 : componentManager.SubscribeToMessageType(MT_TurnStart);
60 137 : componentManager.SubscribeToMessageType(MT_TerrainChanged);
61 137 : componentManager.SubscribeToMessageType(MT_WaterChanged);
62 137 : componentManager.SubscribeToMessageType(MT_Deserialized);
63 :
64 : // TODO: if this component turns out to be a performance issue, it should
65 : // be optimised by creating a new PositionStatic component that doesn't subscribe
66 : // to messages and doesn't store LastX/LastZ, and that should be used for all
67 : // entities that don't move
68 137 : }
69 :
70 534 : DEFAULT_COMPONENT_ALLOCATOR(Position)
71 :
72 : // Template state:
73 :
74 : enum class AnchorType
75 : {
76 : UNDEFINED = -1, // Used for m_ActorAnchorType only since it's optional.
77 : UPRIGHT = 0,
78 : PITCH = 1,
79 : PITCH_ROLL = 2,
80 : ROLL = 3,
81 : };
82 :
83 : AnchorType m_AnchorType;
84 :
85 : bool m_Floating;
86 : entity_pos_t m_FloatDepth;
87 :
88 : // Maximum radians per second, used by InterpolatedRotY to follow RotY and the unitMotion.
89 : fixed m_RotYSpeed;
90 :
91 : // Dynamic state:
92 :
93 : bool m_InWorld;
94 : // m_LastX/Z contain the position from the start of the most recent turn
95 : // m_PrevX/Z conatain the position from the turn before that
96 : entity_pos_t m_X, m_Z, m_LastX, m_LastZ, m_PrevX, m_PrevZ; // these values contain undefined junk if !InWorld
97 :
98 : entity_pos_t m_Y, m_LastYDifference; // either the relative or the absolute Y coordinate
99 : bool m_RelativeToGround; // whether m_Y is relative to terrain/water plane, or an absolute height
100 :
101 : fixed m_ConstructionProgress;
102 :
103 : // when the entity is a turret, only m_RotY is used, and this is the rotation
104 : // relative to the parent entity
105 : entity_angle_t m_RotX, m_RotY, m_RotZ;
106 :
107 : entity_id_t m_TurretParent;
108 : CFixedVector3D m_TurretPosition;
109 : std::set<entity_id_t> m_Turrets;
110 :
111 : // Not serialized:
112 : AnchorType m_ActorAnchorType;
113 : float m_InterpolatedRotX, m_InterpolatedRotY, m_InterpolatedRotZ;
114 : float m_LastInterpolatedRotX, m_LastInterpolatedRotZ;
115 : bool m_ActorFloating;
116 :
117 : bool m_EnabledMessageInterpolate;
118 :
119 137 : static std::string GetSchema()
120 : {
121 137 : return
122 : "<a:help>Allows this entity to exist at a location (and orientation) in the world, and defines some details of the positioning.</a:help>"
123 : "<a:example>"
124 : "<Anchor>upright</Anchor>"
125 : "<Altitude>0.0</Altitude>"
126 : "<Floating>false</Floating>"
127 : "<FloatDepth>0.0</FloatDepth>"
128 : "<TurnRate>6.0</TurnRate>"
129 : "</a:example>"
130 : "<element name='Anchor' a:help='Automatic rotation to follow the slope of terrain'>"
131 : "<choice>"
132 : "<value a:help='Always stand straight up (e.g. humans)'>upright</value>"
133 : "<value a:help='Rotate backwards and forwards to follow the terrain (e.g. animals)'>pitch</value>"
134 : "<value a:help='Rotate sideways to follow the terrain'>roll</value>"
135 : "<value a:help='Rotate in all directions to follow the terrain (e.g. carts)'>pitch-roll</value>"
136 : "</choice>"
137 : "</element>"
138 : "<element name='Altitude' a:help='Height above terrain in meters'>"
139 : "<data type='decimal'/>"
140 : "</element>"
141 : "<element name='Floating' a:help='Whether the entity floats on water'>"
142 : "<data type='boolean'/>"
143 : "</element>"
144 : "<element name='FloatDepth' a:help='The depth at which an entity floats on water (needs Floating to be true)'>"
145 : "<ref name='nonNegativeDecimal'/>"
146 : "</element>"
147 : "<element name='TurnRate' a:help='Maximum rotation speed around Y axis, in radians per second. Used for all graphical rotations and some real unitMotion driven rotations.'>"
148 : "<ref name='positiveDecimal'/>"
149 137 : "</element>";
150 : }
151 :
152 201 : void Init(const CParamNode& paramNode) override
153 : {
154 201 : m_AnchorType = ParseAnchorString(paramNode.GetChild("Anchor").ToString());
155 201 : m_ActorAnchorType = AnchorType::UNDEFINED;
156 :
157 201 : m_InWorld = false;
158 :
159 201 : m_LastYDifference = entity_pos_t::Zero();
160 201 : m_Y = paramNode.GetChild("Altitude").ToFixed();
161 201 : m_RelativeToGround = true;
162 201 : m_Floating = paramNode.GetChild("Floating").ToBool();
163 201 : m_FloatDepth = paramNode.GetChild("FloatDepth").ToFixed();
164 :
165 201 : m_RotYSpeed = paramNode.GetChild("TurnRate").ToFixed();
166 :
167 201 : m_RotX = m_RotY = m_RotZ = entity_angle_t::FromInt(0);
168 201 : m_InterpolatedRotX = m_InterpolatedRotY = m_InterpolatedRotZ = 0.f;
169 201 : m_LastInterpolatedRotX = m_LastInterpolatedRotZ = 0.f;
170 :
171 201 : m_TurretParent = INVALID_ENTITY;
172 201 : m_TurretPosition = CFixedVector3D();
173 :
174 201 : m_ActorFloating = false;
175 :
176 201 : m_EnabledMessageInterpolate = false;
177 201 : }
178 :
179 201 : void Deinit() override
180 : {
181 201 : }
182 :
183 1050 : void Serialize(ISerializer& serialize) override
184 : {
185 1050 : serialize.Bool("in world", m_InWorld);
186 1050 : if (m_InWorld)
187 : {
188 1038 : serialize.NumberFixed_Unbounded("x", m_X);
189 1038 : serialize.NumberFixed_Unbounded("y", m_Y);
190 1038 : serialize.NumberFixed_Unbounded("z", m_Z);
191 1038 : serialize.NumberFixed_Unbounded("last x", m_LastX);
192 1038 : serialize.NumberFixed_Unbounded("last y diff", m_LastYDifference);
193 1038 : serialize.NumberFixed_Unbounded("last z", m_LastZ);
194 : }
195 :
196 1050 : serialize.NumberFixed_Unbounded("rot x", m_RotX);
197 1050 : serialize.NumberFixed_Unbounded("rot y", m_RotY);
198 1050 : serialize.NumberFixed_Unbounded("rot z", m_RotZ);
199 1050 : serialize.NumberFixed_Unbounded("rot y speed", m_RotYSpeed);
200 1050 : serialize.NumberFixed_Unbounded("altitude", m_Y);
201 1050 : serialize.Bool("relative", m_RelativeToGround);
202 1050 : serialize.Bool("floating", m_Floating);
203 1050 : serialize.NumberFixed_Unbounded("float depth", m_FloatDepth);
204 1050 : serialize.NumberFixed_Unbounded("constructionprogress", m_ConstructionProgress);
205 :
206 1050 : if (serialize.IsDebug())
207 : {
208 6 : const char* anchor = "???";
209 6 : switch (m_AnchorType)
210 : {
211 : case AnchorType::PITCH:
212 : anchor = "pitch";
213 : break;
214 :
215 0 : case AnchorType::PITCH_ROLL:
216 0 : anchor = "pitch-roll";
217 0 : break;
218 :
219 0 : case AnchorType::ROLL:
220 0 : anchor = "roll";
221 0 : break;
222 :
223 6 : case AnchorType::UPRIGHT: // upright is the default
224 6 : default:
225 6 : anchor = "upright";
226 6 : break;
227 : }
228 12 : serialize.StringASCII("anchor", anchor, 0, 16);
229 : }
230 1050 : serialize.NumberU32_Unbounded("turret parent", m_TurretParent);
231 1050 : if (m_TurretParent != INVALID_ENTITY)
232 : {
233 0 : serialize.NumberFixed_Unbounded("x", m_TurretPosition.X);
234 0 : serialize.NumberFixed_Unbounded("y", m_TurretPosition.Y);
235 0 : serialize.NumberFixed_Unbounded("z", m_TurretPosition.Z);
236 : }
237 1050 : Serializer(serialize, "turrets", m_Turrets);
238 1050 : }
239 :
240 3 : void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
241 : {
242 3 : Init(paramNode);
243 :
244 3 : deserialize.Bool("in world", m_InWorld);
245 3 : if (m_InWorld)
246 : {
247 1 : deserialize.NumberFixed_Unbounded("x", m_X);
248 1 : deserialize.NumberFixed_Unbounded("y", m_Y);
249 1 : deserialize.NumberFixed_Unbounded("z", m_Z);
250 1 : deserialize.NumberFixed_Unbounded("last x", m_LastX);
251 1 : deserialize.NumberFixed_Unbounded("last y diff", m_LastYDifference);
252 1 : deserialize.NumberFixed_Unbounded("last z", m_LastZ);
253 : }
254 :
255 3 : deserialize.NumberFixed_Unbounded("rot x", m_RotX);
256 3 : deserialize.NumberFixed_Unbounded("rot y", m_RotY);
257 3 : deserialize.NumberFixed_Unbounded("rot z", m_RotZ);
258 3 : deserialize.NumberFixed_Unbounded("rot y speed", m_RotYSpeed);
259 3 : deserialize.NumberFixed_Unbounded("altitude", m_Y);
260 3 : deserialize.Bool("relative", m_RelativeToGround);
261 3 : deserialize.Bool("floating", m_Floating);
262 3 : deserialize.NumberFixed_Unbounded("float depth", m_FloatDepth);
263 3 : deserialize.NumberFixed_Unbounded("constructionprogress", m_ConstructionProgress);
264 : // TODO: should there be range checks on all these values?
265 :
266 3 : m_InterpolatedRotY = m_RotY.ToFloat();
267 :
268 3 : deserialize.NumberU32_Unbounded("turret parent", m_TurretParent);
269 3 : if (m_TurretParent != INVALID_ENTITY)
270 : {
271 0 : deserialize.NumberFixed_Unbounded("x", m_TurretPosition.X);
272 0 : deserialize.NumberFixed_Unbounded("y", m_TurretPosition.Y);
273 0 : deserialize.NumberFixed_Unbounded("z", m_TurretPosition.Z);
274 : }
275 3 : Serializer(deserialize, "turrets", m_Turrets);
276 :
277 3 : if (m_InWorld)
278 1 : UpdateXZRotation();
279 :
280 3 : UpdateMessageSubscriptions();
281 3 : }
282 :
283 0 : void Deserialized()
284 : {
285 0 : AdvertiseInterpolatedPositionChanges();
286 0 : }
287 :
288 0 : void UpdateTurretPosition() override
289 : {
290 0 : if (m_TurretParent == INVALID_ENTITY)
291 0 : return;
292 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), m_TurretParent);
293 0 : if (!cmpPosition)
294 : {
295 0 : LOGERROR("Turret with parent without position component");
296 0 : return;
297 : }
298 0 : if (!cmpPosition->IsInWorld())
299 0 : MoveOutOfWorld();
300 : else
301 : {
302 0 : CFixedVector2D rotatedPosition = CFixedVector2D(m_TurretPosition.X, m_TurretPosition.Z);
303 0 : rotatedPosition = rotatedPosition.Rotate(cmpPosition->GetRotation().Y);
304 0 : CFixedVector2D rootPosition = cmpPosition->GetPosition2D();
305 0 : entity_pos_t x = rootPosition.X + rotatedPosition.X;
306 0 : entity_pos_t z = rootPosition.Y + rotatedPosition.Y;
307 0 : if (!m_InWorld || m_X != x || m_Z != z)
308 0 : MoveTo(x, z);
309 0 : entity_pos_t y = cmpPosition->GetHeightOffset() + m_TurretPosition.Y;
310 0 : if (!m_InWorld || GetHeightOffset() != y)
311 0 : SetHeightOffset(y);
312 0 : m_InWorld = true;
313 : }
314 : }
315 :
316 0 : std::set<entity_id_t>* GetTurrets() override
317 : {
318 0 : return &m_Turrets;
319 : }
320 :
321 0 : void SetTurretParent(entity_id_t id, const CFixedVector3D& offset) override
322 : {
323 0 : entity_angle_t angle = GetRotation().Y;
324 0 : if (m_TurretParent != INVALID_ENTITY)
325 : {
326 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), m_TurretParent);
327 0 : if (cmpPosition)
328 0 : cmpPosition->GetTurrets()->erase(GetEntityId());
329 : }
330 :
331 0 : m_TurretParent = id;
332 0 : m_TurretPosition = offset;
333 :
334 0 : if (m_TurretParent != INVALID_ENTITY)
335 : {
336 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), m_TurretParent);
337 0 : if (cmpPosition)
338 0 : cmpPosition->GetTurrets()->insert(GetEntityId());
339 : }
340 0 : SetYRotation(angle);
341 0 : UpdateTurretPosition();
342 0 : }
343 :
344 0 : entity_id_t GetTurretParent() const override
345 : {
346 0 : return m_TurretParent;
347 : }
348 :
349 222318 : bool IsInWorld() const override
350 : {
351 222318 : return m_InWorld;
352 : }
353 :
354 2 : void MoveOutOfWorld() override
355 : {
356 2 : m_InWorld = false;
357 :
358 2 : AdvertisePositionChanges();
359 2 : AdvertiseInterpolatedPositionChanges();
360 0 : }
361 :
362 6 : void MoveTo(entity_pos_t x, entity_pos_t z) override
363 : {
364 6 : m_X = x;
365 6 : m_Z = z;
366 :
367 6 : if (!m_InWorld)
368 : {
369 1 : m_InWorld = true;
370 1 : m_LastX = m_PrevX = m_X;
371 1 : m_LastZ = m_PrevZ = m_Z;
372 1 : m_LastYDifference = entity_pos_t::Zero();
373 : }
374 :
375 6 : AdvertisePositionChanges();
376 6 : AdvertiseInterpolatedPositionChanges();
377 6 : }
378 :
379 6948 : void MoveAndTurnTo(entity_pos_t x, entity_pos_t z, entity_angle_t ry) override
380 : {
381 6948 : m_X = x;
382 6948 : m_Z = z;
383 :
384 6948 : if (!m_InWorld)
385 : {
386 0 : m_InWorld = true;
387 0 : m_LastX = m_PrevX = m_X;
388 0 : m_LastZ = m_PrevZ = m_Z;
389 0 : m_LastYDifference = entity_pos_t::Zero();
390 : }
391 :
392 : // TurnTo will advertise the position changes
393 6948 : TurnTo(ry);
394 :
395 6948 : AdvertiseInterpolatedPositionChanges();
396 6948 : }
397 :
398 199 : void JumpTo(entity_pos_t x, entity_pos_t z) override
399 : {
400 199 : m_LastX = m_PrevX = m_X = x;
401 199 : m_LastZ = m_PrevZ = m_Z = z;
402 199 : m_InWorld = true;
403 :
404 199 : UpdateXZRotation();
405 :
406 199 : m_LastInterpolatedRotX = m_InterpolatedRotX;
407 199 : m_LastInterpolatedRotZ = m_InterpolatedRotZ;
408 :
409 199 : AdvertisePositionChanges();
410 199 : AdvertiseInterpolatedPositionChanges();
411 199 : }
412 :
413 4 : void SetHeightOffset(entity_pos_t dy) override
414 : {
415 : // subtract the offset and replace with a new offset
416 4 : m_LastYDifference = dy - GetHeightOffset();
417 4 : m_Y += m_LastYDifference;
418 4 : AdvertiseInterpolatedPositionChanges();
419 4 : }
420 :
421 728 : entity_pos_t GetHeightOffset() const override
422 : {
423 728 : if (m_RelativeToGround)
424 724 : return m_Y;
425 : // not relative to the ground, so the height offset is m_Y - ground height
426 : // except when floating, when the height offset is m_Y - water level + float depth
427 4 : entity_pos_t baseY;
428 4 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
429 4 : if (cmpTerrain)
430 4 : baseY = cmpTerrain->GetGroundLevel(m_X, m_Z);
431 :
432 4 : if (m_Floating)
433 : {
434 3 : CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
435 3 : if (cmpWaterManager)
436 6 : baseY = std::max(baseY, cmpWaterManager->GetWaterLevel(m_X, m_Z) - m_FloatDepth);
437 : }
438 4 : return m_Y - baseY;
439 : }
440 :
441 2 : void SetHeightFixed(entity_pos_t y) override
442 : {
443 : // subtract the absolute height and replace it with a new absolute height
444 2 : m_LastYDifference = y - GetHeightFixed();
445 2 : m_Y += m_LastYDifference;
446 2 : AdvertiseInterpolatedPositionChanges();
447 2 : }
448 :
449 3609 : entity_pos_t GetHeightFixed() const override
450 : {
451 11 : return GetHeightAtFixed(m_X, m_Z);
452 : }
453 :
454 3999 : entity_pos_t GetHeightAtFixed(entity_pos_t x, entity_pos_t z) const override
455 : {
456 3999 : if (!m_RelativeToGround)
457 7 : return m_Y;
458 : // relative to the ground, so the fixed height = ground height + m_Y
459 : // except when floating, when the fixed height = water level - float depth + m_Y
460 3992 : entity_pos_t baseY;
461 3992 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
462 3992 : if (cmpTerrain)
463 3992 : baseY = cmpTerrain->GetGroundLevel(x, z);
464 :
465 3992 : if (m_Floating)
466 : {
467 9 : CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
468 9 : if (cmpWaterManager)
469 18 : baseY = std::max(baseY, cmpWaterManager->GetWaterLevel(x, z) - m_FloatDepth);
470 : }
471 3992 : return m_Y + baseY;
472 : }
473 :
474 2 : bool IsHeightRelative() const override
475 : {
476 2 : return m_RelativeToGround;
477 : }
478 :
479 1 : void SetHeightRelative(bool relative) override
480 : {
481 : // move y to use the right offset (from terrain or from map origin)
482 2 : m_Y = relative ? GetHeightOffset() : GetHeightFixed();
483 1 : m_RelativeToGround = relative;
484 1 : m_LastYDifference = entity_pos_t::Zero();
485 1 : AdvertiseInterpolatedPositionChanges();
486 1 : }
487 :
488 3 : bool CanFloat() const override
489 : {
490 3 : return m_Floating;
491 : }
492 :
493 3 : void SetFloating(bool flag) override
494 : {
495 3 : m_Floating = flag;
496 3 : AdvertiseInterpolatedPositionChanges();
497 3 : }
498 :
499 0 : void SetActorFloating(bool flag) override
500 : {
501 0 : m_ActorFloating = flag;
502 0 : AdvertiseInterpolatedPositionChanges();
503 0 : }
504 :
505 0 : void SetActorAnchor(const CStr& anchor) override
506 : {
507 0 : m_ActorAnchorType = ParseAnchorString(anchor);
508 0 : }
509 :
510 0 : void SetConstructionProgress(fixed progress) override
511 : {
512 0 : m_ConstructionProgress = progress;
513 0 : AdvertiseInterpolatedPositionChanges();
514 0 : }
515 :
516 3598 : CFixedVector3D GetPosition() const override
517 : {
518 3598 : if (!m_InWorld)
519 : {
520 0 : LOGERROR("CCmpPosition::GetPosition called on entity when IsInWorld is false");
521 0 : return CFixedVector3D();
522 : }
523 :
524 3598 : return CFixedVector3D(m_X, GetHeightFixed(), m_Z);
525 : }
526 :
527 204900 : CFixedVector2D GetPosition2D() const override
528 : {
529 204900 : if (!m_InWorld)
530 : {
531 0 : LOGERROR("CCmpPosition::GetPosition2D called on entity when IsInWorld is false");
532 0 : return CFixedVector2D();
533 : }
534 :
535 204900 : return CFixedVector2D(m_X, m_Z);
536 : }
537 :
538 270 : CFixedVector3D GetPreviousPosition() const override
539 : {
540 270 : if (!m_InWorld)
541 : {
542 0 : LOGERROR("CCmpPosition::GetPreviousPosition called on entity when IsInWorld is false");
543 0 : return CFixedVector3D();
544 : }
545 :
546 270 : return CFixedVector3D(m_PrevX, GetHeightAtFixed(m_PrevX, m_PrevZ), m_PrevZ);
547 : }
548 :
549 12255 : CFixedVector2D GetPreviousPosition2D() const override
550 : {
551 12255 : if (!m_InWorld)
552 : {
553 0 : LOGERROR("CCmpPosition::GetPreviousPosition2D called on entity when IsInWorld is false");
554 0 : return CFixedVector2D();
555 : }
556 :
557 12255 : return CFixedVector2D(m_PrevX, m_PrevZ);
558 : }
559 :
560 7314 : fixed GetTurnRate() const override
561 : {
562 7314 : return m_RotYSpeed;
563 : }
564 :
565 7731 : void TurnTo(entity_angle_t y) override
566 : {
567 7731 : if (m_TurretParent != INVALID_ENTITY)
568 : {
569 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), m_TurretParent);
570 0 : if (cmpPosition)
571 0 : y -= cmpPosition->GetRotation().Y;
572 : }
573 :
574 7731 : m_RotY = y;
575 :
576 7731 : AdvertisePositionChanges();
577 7731 : UpdateMessageSubscriptions();
578 7731 : }
579 :
580 16 : void SetYRotation(entity_angle_t y) override
581 : {
582 16 : if (m_TurretParent != INVALID_ENTITY)
583 : {
584 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), m_TurretParent);
585 0 : if (cmpPosition)
586 0 : y -= cmpPosition->GetRotation().Y;
587 : }
588 16 : m_RotY = y;
589 16 : m_InterpolatedRotY = m_RotY.ToFloat();
590 :
591 16 : if (m_InWorld)
592 : {
593 15 : UpdateXZRotation();
594 :
595 15 : m_LastInterpolatedRotX = m_InterpolatedRotX;
596 15 : m_LastInterpolatedRotZ = m_InterpolatedRotZ;
597 : }
598 :
599 16 : AdvertisePositionChanges();
600 16 : UpdateMessageSubscriptions();
601 16 : }
602 :
603 16 : void SetXZRotation(entity_angle_t x, entity_angle_t z) override
604 : {
605 16 : m_RotX = x;
606 16 : m_RotZ = z;
607 :
608 16 : if (m_InWorld)
609 : {
610 15 : UpdateXZRotation();
611 :
612 15 : m_LastInterpolatedRotX = m_InterpolatedRotX;
613 15 : m_LastInterpolatedRotZ = m_InterpolatedRotZ;
614 : }
615 16 : }
616 :
617 8236 : CFixedVector3D GetRotation() const override
618 : {
619 8236 : entity_angle_t y = m_RotY;
620 8236 : if (m_TurretParent != INVALID_ENTITY)
621 : {
622 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), m_TurretParent);
623 0 : if (cmpPosition)
624 0 : y += cmpPosition->GetRotation().Y;
625 : }
626 8236 : return CFixedVector3D(m_RotX, y, m_RotZ);
627 : }
628 :
629 0 : fixed GetDistanceTravelled() const override
630 : {
631 0 : if (!m_InWorld)
632 : {
633 0 : LOGERROR("CCmpPosition::GetDistanceTravelled called on entity when IsInWorld is false");
634 0 : return fixed::Zero();
635 : }
636 :
637 0 : return CFixedVector2D(m_X - m_LastX, m_Z - m_LastZ).Length();
638 : }
639 :
640 14337 : float GetConstructionProgressOffset(const CVector3D& pos) const
641 : {
642 14337 : if (m_ConstructionProgress.IsZero())
643 : return 0.0f;
644 :
645 0 : CmpPtr<ICmpVisual> cmpVisual(GetEntityHandle());
646 0 : if (!cmpVisual)
647 : return 0.0f;
648 :
649 : // We use selection boxes to calculate the model size, since the model could be offset
650 : // TODO: this annoyingly shows decals, would be nice to hide them
651 0 : CBoundingBoxOriented bounds = cmpVisual->GetSelectionBox();
652 0 : if (bounds.IsEmpty())
653 : return 0.0f;
654 :
655 0 : float dy = 2.0f * bounds.m_HalfSizes.Y;
656 :
657 : // If this is a floating unit, we want it to start all the way under the terrain,
658 : // so find the difference between its current position and the terrain
659 :
660 0 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
661 0 : if (cmpTerrain && (m_Floating || m_ActorFloating))
662 : {
663 0 : float ground = cmpTerrain->GetExactGroundLevel(pos.X, pos.Z);
664 0 : dy += std::max(0.f, pos.Y - ground);
665 : }
666 :
667 0 : return (m_ConstructionProgress.ToFloat() - 1.0f) * dy;
668 : }
669 :
670 15 : void GetInterpolatedPosition2D(float frameOffset, float& x, float& z, float& rotY) const override
671 : {
672 15 : if (!m_InWorld)
673 : {
674 0 : LOGERROR("CCmpPosition::GetInterpolatedPosition2D called on entity when IsInWorld is false");
675 0 : return;
676 : }
677 :
678 15 : x = Interpolate(m_LastX.ToFloat(), m_X.ToFloat(), frameOffset);
679 15 : z = Interpolate(m_LastZ.ToFloat(), m_Z.ToFloat(), frameOffset);
680 :
681 15 : rotY = m_InterpolatedRotY;
682 : }
683 :
684 15 : CMatrix3D GetInterpolatedTransform(float frameOffset) const override
685 : {
686 15 : if (m_TurretParent != INVALID_ENTITY)
687 : {
688 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), m_TurretParent);
689 0 : if (!cmpPosition)
690 : {
691 0 : LOGERROR("Turret with parent without position component");
692 0 : CMatrix3D m;
693 0 : m.SetIdentity();
694 0 : return m;
695 : }
696 0 : if (!cmpPosition->IsInWorld())
697 : {
698 0 : LOGERROR("CCmpPosition::GetInterpolatedTransform called on turret entity when IsInWorld is false");
699 0 : CMatrix3D m;
700 0 : m.SetIdentity();
701 0 : return m;
702 : }
703 : else
704 : {
705 0 : CMatrix3D parentTransformMatrix = cmpPosition->GetInterpolatedTransform(frameOffset);
706 0 : CMatrix3D ownTransformation = CMatrix3D();
707 0 : ownTransformation.SetYRotation(m_InterpolatedRotY);
708 0 : ownTransformation.Translate(-m_TurretPosition.X.ToFloat(), m_TurretPosition.Y.ToFloat(), -m_TurretPosition.Z.ToFloat());
709 0 : return parentTransformMatrix * ownTransformation;
710 : }
711 : }
712 15 : if (!m_InWorld)
713 : {
714 0 : LOGERROR("CCmpPosition::GetInterpolatedTransform called on entity when IsInWorld is false");
715 0 : CMatrix3D m;
716 0 : m.SetIdentity();
717 0 : return m;
718 : }
719 :
720 15 : float x{0.0f}, z{0.0f}, rotY{0.0f};
721 15 : GetInterpolatedPosition2D(frameOffset, x, z, rotY);
722 :
723 :
724 15 : float baseY = 0;
725 15 : if (m_RelativeToGround)
726 : {
727 15 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
728 15 : if (cmpTerrain)
729 15 : baseY = cmpTerrain->GetExactGroundLevel(x, z);
730 :
731 15 : if (m_Floating || m_ActorFloating)
732 : {
733 3 : CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
734 3 : if (cmpWaterManager)
735 6 : baseY = std::max(baseY, cmpWaterManager->GetExactWaterLevel(x, z) - m_FloatDepth.ToFloat());
736 : }
737 : }
738 :
739 15 : float y = baseY + m_Y.ToFloat() + Interpolate(-1 * m_LastYDifference.ToFloat(), 0.f, frameOffset);
740 :
741 15 : CMatrix3D m;
742 :
743 : // linear interpolation is good enough (for RotX/Z).
744 : // As you always stay close to zero angle.
745 15 : m.SetXRotation(Interpolate(m_LastInterpolatedRotX, m_InterpolatedRotX, frameOffset));
746 15 : m.RotateZ(Interpolate(m_LastInterpolatedRotZ, m_InterpolatedRotZ, frameOffset));
747 :
748 15 : CVector3D pos(x, y, z);
749 :
750 15 : pos.Y += GetConstructionProgressOffset(pos);
751 :
752 15 : m.RotateY(rotY + std::numbers::pi_v<float>);
753 15 : m.Translate(pos);
754 :
755 15 : return m;
756 : }
757 :
758 7161 : void GetInterpolatedPositions(CVector3D& pos0, CVector3D& pos1) const
759 : {
760 7161 : float baseY0 = 0;
761 7161 : float baseY1 = 0;
762 7161 : float x0 = m_LastX.ToFloat();
763 7161 : float z0 = m_LastZ.ToFloat();
764 7161 : float x1 = m_X.ToFloat();
765 7161 : float z1 = m_Z.ToFloat();
766 7161 : if (m_RelativeToGround)
767 : {
768 7157 : CmpPtr<ICmpTerrain> cmpTerrain(GetSimContext(), SYSTEM_ENTITY);
769 7157 : if (cmpTerrain)
770 : {
771 7157 : baseY0 = cmpTerrain->GetExactGroundLevel(x0, z0);
772 7157 : baseY1 = cmpTerrain->GetExactGroundLevel(x1, z1);
773 : }
774 :
775 7157 : if (m_Floating || m_ActorFloating)
776 : {
777 5 : CmpPtr<ICmpWaterManager> cmpWaterManager(GetSimContext(), SYSTEM_ENTITY);
778 5 : if (cmpWaterManager)
779 : {
780 5 : baseY0 = std::max(baseY0, cmpWaterManager->GetExactWaterLevel(x0, z0) - m_FloatDepth.ToFloat());
781 10 : baseY1 = std::max(baseY1, cmpWaterManager->GetExactWaterLevel(x1, z1) - m_FloatDepth.ToFloat());
782 : }
783 : }
784 : }
785 :
786 7161 : float y0 = baseY0 + m_Y.ToFloat() + m_LastYDifference.ToFloat();
787 7161 : float y1 = baseY1 + m_Y.ToFloat();
788 :
789 7161 : pos0 = CVector3D(x0, y0, z0);
790 7161 : pos1 = CVector3D(x1, y1, z1);
791 :
792 7161 : pos0.Y += GetConstructionProgressOffset(pos0);
793 7161 : pos1.Y += GetConstructionProgressOffset(pos1);
794 7161 : }
795 :
796 8020 : void HandleMessage(const CMessage& msg, bool /*global*/) override
797 : {
798 8020 : switch (msg.GetType())
799 : {
800 0 : case MT_Interpolate:
801 0 : {
802 0 : PROFILE("Position::Interpolate");
803 :
804 0 : const CMessageInterpolate& msgData = static_cast<const CMessageInterpolate&> (msg);
805 :
806 0 : float rotY = m_RotY.ToFloat();
807 :
808 0 : if (rotY != m_InterpolatedRotY)
809 : {
810 0 : float rotYSpeed = m_RotYSpeed.ToFloat();
811 0 : float delta = rotY - m_InterpolatedRotY;
812 : // Wrap delta to -PI..PI
813 0 : delta = fmodf(delta + std::numbers::pi_v<float>, 2.f * std::numbers::pi_v<float>); // range -2PI..2PI
814 0 : if (delta < 0) delta += 2.f * std::numbers::pi_v<float>; // range 0..2PI
815 0 : delta -= std::numbers::pi_v<float>; // range -PI..PI
816 : // Clamp to max rate
817 0 : float deltaClamped = Clamp(delta, -rotYSpeed*msgData.deltaSimTime, +rotYSpeed*msgData.deltaSimTime);
818 : // Calculate new orientation, in a peculiar way in order to make sure the
819 : // result gets close to m_orientation (rather than being n*2*PI out)
820 0 : m_InterpolatedRotY = rotY + deltaClamped - delta;
821 :
822 : // update the visual XZ rotation
823 0 : if (m_InWorld)
824 : {
825 0 : m_LastInterpolatedRotX = m_InterpolatedRotX;
826 0 : m_LastInterpolatedRotZ = m_InterpolatedRotZ;
827 :
828 0 : UpdateXZRotation();
829 : }
830 :
831 0 : UpdateMessageSubscriptions();
832 : }
833 :
834 0 : break;
835 0 : }
836 8020 : case MT_TurnStart:
837 8020 : {
838 :
839 8020 : m_LastInterpolatedRotX = m_InterpolatedRotX;
840 8020 : m_LastInterpolatedRotZ = m_InterpolatedRotZ;
841 :
842 8020 : if (m_InWorld && (m_LastX != m_X || m_LastZ != m_Z))
843 6784 : UpdateXZRotation();
844 :
845 : // Store the positions from the turn before
846 8020 : m_PrevX = m_LastX;
847 8020 : m_PrevZ = m_LastZ;
848 :
849 8020 : m_LastX = m_X;
850 8020 : m_LastZ = m_Z;
851 8020 : m_LastYDifference = entity_pos_t::Zero();
852 :
853 8020 : break;
854 : }
855 0 : case MT_TerrainChanged:
856 0 : case MT_WaterChanged:
857 0 : {
858 0 : AdvertiseInterpolatedPositionChanges();
859 0 : break;
860 : }
861 0 : case MT_Deserialized:
862 0 : {
863 0 : Deserialized();
864 : break;
865 : }
866 : }
867 8020 : }
868 :
869 : private:
870 :
871 201 : AnchorType ParseAnchorString(const CStr& anchor)
872 : {
873 201 : if (anchor == "pitch")
874 : return AnchorType::PITCH;
875 117 : if (anchor == "roll")
876 : return AnchorType::ROLL;
877 117 : if (anchor == "pitch-roll")
878 6 : return AnchorType::PITCH_ROLL;
879 : return AnchorType::UPRIGHT;
880 : }
881 :
882 : /*
883 : * Must be called whenever m_RotY or m_InterpolatedRotY change,
884 : * to determine whether we need to call Interpolate to make the unit rotate.
885 : */
886 7750 : void UpdateMessageSubscriptions()
887 : {
888 7750 : bool needInterpolate = false;
889 :
890 7750 : float rotY = m_RotY.ToFloat();
891 7750 : if (rotY != m_InterpolatedRotY)
892 6825 : needInterpolate = true;
893 :
894 7750 : if (needInterpolate != m_EnabledMessageInterpolate)
895 : {
896 165 : GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_Interpolate, this, needInterpolate);
897 165 : m_EnabledMessageInterpolate = needInterpolate;
898 : }
899 7750 : }
900 :
901 : /**
902 : * This must be called after changing anything that will affect the
903 : * return value of GetPosition2D() or GetRotation().Y:
904 : * - m_InWorld
905 : * - m_X, m_Z
906 : * - m_RotY
907 : */
908 7954 : void AdvertisePositionChanges() const
909 : {
910 7954 : for (std::set<entity_id_t>::const_iterator it = m_Turrets.begin(); it != m_Turrets.end(); ++it)
911 : {
912 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), *it);
913 0 : if (cmpPosition)
914 0 : cmpPosition->UpdateTurretPosition();
915 : }
916 7954 : if (m_InWorld)
917 : {
918 7951 : CMessagePositionChanged msg(GetEntityId(), true, m_X, m_Z, m_RotY);
919 7951 : GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
920 7951 : }
921 : else
922 : {
923 3 : CMessagePositionChanged msg(GetEntityId(), false, entity_pos_t::Zero(), entity_pos_t::Zero(), entity_angle_t::Zero());
924 3 : GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
925 3 : }
926 7954 : }
927 :
928 : /**
929 : * This must be called after changing anything that will affect the
930 : * return value of GetInterpolatedPositions():
931 : * - m_InWorld
932 : * - m_X, m_Z
933 : * - m_LastX, m_LastZ
934 : * - m_Y, m_LastYDifference, m_RelativeToGround
935 : * - If m_RelativeToGround, then the ground under this unit
936 : * - If m_RelativeToGround && m_Float, then the water level
937 : */
938 7165 : void AdvertiseInterpolatedPositionChanges() const
939 : {
940 7165 : if (m_InWorld)
941 : {
942 7161 : CVector3D pos0, pos1;
943 7161 : GetInterpolatedPositions(pos0, pos1);
944 :
945 7161 : CMessageInterpolatedPositionChanged msg(GetEntityId(), true, pos0, pos1);
946 7161 : GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
947 7161 : }
948 : else
949 : {
950 4 : CMessageInterpolatedPositionChanged msg(GetEntityId(), false, CVector3D(), CVector3D());
951 4 : GetSimContext().GetComponentManager().PostMessage(GetEntityId(), msg);
952 4 : }
953 7165 : }
954 :
955 7014 : void UpdateXZRotation()
956 : {
957 7014 : if (!m_InWorld)
958 : {
959 0 : LOGERROR("CCmpPosition::UpdateXZRotation called on entity when IsInWorld is false");
960 3813 : return;
961 : }
962 :
963 7014 : AnchorType anchor = m_ActorAnchorType == AnchorType::UNDEFINED ? m_AnchorType : m_ActorAnchorType;
964 7014 : if (anchor == AnchorType::UPRIGHT || !m_RotZ.IsZero() || !m_RotX.IsZero())
965 : {
966 : // set the visual rotations to the ones fixed by the interface
967 3813 : m_InterpolatedRotX = m_RotX.ToFloat();
968 3813 : m_InterpolatedRotZ = m_RotZ.ToFloat();
969 3813 : return;
970 : }
971 :
972 3201 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
973 3201 : if (!cmpTerrain || !cmpTerrain->IsLoaded())
974 : {
975 0 : LOGERROR("Terrain not loaded");
976 0 : return;
977 : }
978 :
979 : // TODO: average normal (average all the tiles?) for big units or for buildings?
980 3201 : CVector3D normal = cmpTerrain->CalcExactNormal(m_X.ToFloat(), m_Z.ToFloat());
981 :
982 : // rotate the normal so the positive x direction is in the direction of the unit
983 3201 : CVector2D projected = CVector2D(normal.X, normal.Z);
984 3201 : projected.Rotate(m_InterpolatedRotY);
985 :
986 3201 : normal.X = projected.X;
987 3201 : normal.Z = projected.Y;
988 :
989 : // project and calculate the angles
990 3201 : if (anchor == AnchorType::PITCH || anchor == AnchorType::PITCH_ROLL)
991 3201 : m_InterpolatedRotX = -atan2(normal.Z, normal.Y);
992 :
993 3201 : if (anchor == AnchorType::ROLL || anchor == AnchorType::PITCH_ROLL)
994 276 : m_InterpolatedRotZ = atan2(normal.X, normal.Y);
995 : }
996 : };
997 :
998 274 : REGISTER_COMPONENT_TYPE(Position)
|