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 "ICmpRangeManager.h"
21 :
22 : #include "ICmpTerrain.h"
23 : #include "graphics/Color.h"
24 : #include "graphics/Overlay.h"
25 : #include "lib/debug.h"
26 : #include "lib/posix/posix_types.h"
27 : #include "maths/Fixed.h"
28 : #include "maths/FixedVector2D.h"
29 : #include "maths/FixedVector3D.h"
30 : #include "maths/MathUtil.h"
31 : #include "maths/Sqrt.h"
32 : #include "ps/CLogger.h"
33 : #include "ps/Future.h"
34 : #include "ps/Profile.h"
35 : #include "ps/TaskManager.h"
36 : #include "renderer/Scene.h"
37 : #include "simulation2/MessageTypes.h"
38 : #include "simulation2/components/ICmpFogging.h"
39 : #include "simulation2/components/ICmpMirage.h"
40 : #include "simulation2/components/ICmpObstruction.h"
41 : #include "simulation2/components/ICmpOwnership.h"
42 : #include "simulation2/components/ICmpPathfinder.h"
43 : #include "simulation2/components/ICmpPosition.h"
44 : #include "simulation2/components/ICmpTerritoryManager.h"
45 : #include "simulation2/components/ICmpVisibility.h"
46 : #include "simulation2/components/ICmpVision.h"
47 : #include "simulation2/components/ICmpWaterManager.h"
48 : #include "simulation2/helpers/Grid.h"
49 : #include "simulation2/helpers/Los.h"
50 : #include "simulation2/helpers/MapEdgeTiles.h"
51 : #include "simulation2/helpers/Pathfinding.h"
52 : #include "simulation2/helpers/Player.h"
53 : #include "simulation2/helpers/Position.h"
54 : #include "simulation2/helpers/Render.h"
55 : #include "simulation2/helpers/Spatial.h"
56 : #include "simulation2/serialization/SerializeTemplates.h"
57 : #include "simulation2/serialization/SerializedTypes.h"
58 : #include "simulation2/system/Component.h"
59 : #include "simulation2/system/Entity.h"
60 : #include "simulation2/system/EntityMap.h"
61 : #include "simulation2/system/Message.h"
62 :
63 : #include <algorithm>
64 : #include <array>
65 : #include <cstdint>
66 : #include <cstdlib>
67 : #include <iterator>
68 : #include <limits>
69 : #include <map>
70 : #include <set>
71 : #include <string>
72 : #include <type_traits>
73 : #include <utility>
74 : #include <vector>
75 :
76 : #define DEBUG_RANGE_MANAGER_BOUNDS 0
77 :
78 : namespace
79 : {
80 : /**
81 : * How many LOS vertices to have per region.
82 : * LOS regions are used to keep track of units.
83 : */
84 : constexpr int LOS_REGION_RATIO = 8;
85 :
86 : /**
87 : * Tolerance for parabolic range calculations.
88 : * TODO C++20: change this to constexpr by fixing CFixed with std::is_constant_evaluated
89 : */
90 : const fixed PARABOLIC_RANGE_TOLERANCE = fixed::FromInt(1)/2;
91 :
92 : /**
93 : * Convert an owner ID (-1 = unowned, 0 = gaia, 1..30 = players)
94 : * into a 32-bit mask for quick set-membership tests.
95 : */
96 3353 : std::uint32_t CalcOwnerMask(player_id_t owner)
97 : {
98 455 : if (owner >= -1 && owner < 31)
99 3352 : return 1 << (1+owner);
100 : else
101 : return 0; // owner was invalid
102 : }
103 :
104 : /**
105 : * Returns LOS mask for given player.
106 : */
107 18 : std::uint32_t CalcPlayerLosMask(player_id_t player)
108 : {
109 18 : if (player > 0 && player <= 16)
110 9 : return static_cast<std::uint32_t>(LosState::MASK) << (2*(player-1));
111 : return 0;
112 : }
113 :
114 : /**
115 : * Returns shared LOS mask for given list of players.
116 : */
117 : std::uint32_t CalcSharedLosMask(std::vector<player_id_t> players)
118 : {
119 : std::uint32_t playerMask = 0;
120 36 : for (size_t i = 0; i < players.size(); i++)
121 27 : playerMask |= CalcPlayerLosMask(players[i]);
122 :
123 18 : return playerMask;
124 : }
125 :
126 : /**
127 : * Add/remove a player to/from mask, which is a 1-bit mask representing a list of players.
128 : * Returns true if the mask is modified.
129 : */
130 288 : bool SetPlayerSharedDirtyVisibilityBit(std::uint16_t& mask, player_id_t player, bool enable)
131 : {
132 288 : if (player <= 0 || player > 16)
133 : return false;
134 :
135 144 : std::uint16_t oldMask = mask;
136 :
137 144 : if (enable)
138 9 : mask |= (0x1 << (player - 1));
139 : else
140 135 : mask &= ~(0x1 << (player - 1));
141 :
142 144 : return oldMask != mask;
143 : }
144 :
145 : /**
146 : * Computes the 2-bit visibility for one player, given the total 32-bit visibilities
147 : */
148 117566 : LosVisibility GetPlayerVisibility(std::uint32_t visibilities, player_id_t player)
149 : {
150 117566 : if (player > 0 && player <= 16)
151 116456 : return static_cast<LosVisibility>( (visibilities >> (2 *(player-1))) & 0x3 );
152 : return LosVisibility::HIDDEN;
153 : }
154 :
155 : /**
156 : * Test whether the visibility is dirty for a given LoS region and a given player
157 : */
158 1684983 : bool IsVisibilityDirty(std::uint16_t dirty, player_id_t player)
159 : {
160 1527 : if (player > 0 && player <= 16)
161 1683456 : return (dirty >> (player - 1)) & 0x1;
162 : return false;
163 : }
164 :
165 : /**
166 : * Test whether a player share this vision
167 : */
168 0 : bool HasVisionSharing(std::uint16_t visionSharing, player_id_t player)
169 : {
170 0 : return (visionSharing & (1 << (player - 1))) != 0;
171 : }
172 :
173 : /**
174 : * Computes the shared vision mask for the player
175 : */
176 0 : std::uint16_t CalcVisionSharingMask(player_id_t player)
177 : {
178 0 : return 1 << (player-1);
179 : }
180 :
181 : /**
182 : * Representation of a range query.
183 : */
184 183 : struct Query
185 : {
186 : std::vector<entity_id_t> lastMatch;
187 : CEntityHandle source; // TODO: this could crash if an entity is destroyed while a Query is still referencing it
188 : entity_pos_t minRange;
189 : entity_pos_t maxRange;
190 : entity_pos_t baseRange; // Non-parabolic detection range
191 : entity_pos_t yOrigin; // Used for parabolas only.
192 : std::uint32_t ownersMask;
193 : std::int32_t interface;
194 : std::uint8_t flagsMask;
195 : bool enabled;
196 : bool parabolic;
197 : bool accountForSize; // If true, the query accounts for unit sizes, otherwise it treats all entities as points.
198 : bool preferMirages; // If true, include mirages and filter HIDDEN entities. Otherwise exclude mirages and no visibility filter.
199 : };
200 :
201 : /**
202 : * Checks whether v is in a parabolic range of (0,0,0)
203 : * The highest point of the paraboloid is (0,range/2,0)
204 : * and the circle of distance 'range' around (0,0,0) on height y=0 is part of the paraboloid
205 : * This equates to computing f(x, z) = y = -(xx + zz)/(2*range) + range/2 > 0,
206 : * or alternatively sqrt(xx+zz) <= sqrt(range^2 - 2range*y).
207 : *
208 : * Avoids sqrting and overflowing.
209 : */
210 0 : static bool InParabolicRange(CFixedVector3D v, fixed range)
211 : {
212 0 : std::uint64_t xx = SQUARE_U64_FIXED(v.X); // xx <= 2^62
213 0 : std::uint64_t zz = SQUARE_U64_FIXED(v.Z);
214 0 : std::int64_t d2 = (xx + zz) >> 1; // d2 <= 2^62 (no overflow)
215 :
216 0 : std::int32_t y = v.Y.GetInternalValue();
217 0 : std::int32_t c = range.GetInternalValue();
218 0 : std::int32_t c_2 = c >> 1;
219 :
220 0 : std::int64_t c2 = MUL_I64_I32_I32(c_2 - y, c);
221 :
222 0 : return d2 <= c2;
223 : }
224 :
225 0 : struct EntityParabolicRangeOutline
226 : {
227 : entity_id_t source;
228 : CFixedVector3D position;
229 : entity_pos_t range;
230 : std::vector<entity_pos_t> outline;
231 : };
232 :
233 : static std::map<entity_id_t, EntityParabolicRangeOutline> ParabolicRangesOutlines;
234 :
235 : /**
236 : * Representation of an entity, with the data needed for queries.
237 : */
238 : enum FlagMasks
239 : {
240 : // flags used for queries
241 : None = 0x00,
242 : Normal = 0x01,
243 : Injured = 0x02,
244 : AllQuery = Normal | Injured,
245 :
246 : // 0x04 reserved for future use
247 :
248 : // general flags
249 : InWorld = 0x08,
250 : RetainInFog = 0x10,
251 : RevealShore = 0x20,
252 : ScriptedVisibility = 0x40,
253 : SharedVision = 0x80
254 : };
255 :
256 : struct EntityData
257 : {
258 193 : EntityData() :
259 0 : visibilities(0), size(0), visionSharing(0),
260 0 : owner(-1), flags(FlagMasks::Normal)
261 : { }
262 : entity_pos_t x, z;
263 : entity_pos_t visionRange;
264 : std::uint32_t visibilities; // 2-bit visibility, per player
265 : std::uint32_t size;
266 : std::uint16_t visionSharing; // 1-bit per player
267 : std::int8_t owner;
268 : std::uint8_t flags; // See the FlagMasks enum
269 :
270 : template<int mask>
271 52028 : inline bool HasFlag() const { return (flags & mask) != 0; }
272 :
273 : template<int mask>
274 367 : inline void SetFlag(bool val) { flags = val ? (flags | mask) : (flags & ~mask); }
275 :
276 69 : inline void SetFlag(std::uint8_t mask, bool val) { flags = val ? (flags | mask) : (flags & ~mask); }
277 : };
278 :
279 : static_assert(sizeof(EntityData) == 24);
280 :
281 : // Convert world-space circle to tile-space bounds
282 : struct TileCircle
283 : {
284 : std::int32_t centerX, centerZ;
285 : std::int32_t radius;
286 : std::int32_t squaredRadius;
287 : std::int32_t minX, maxX, minZ, maxZ;
288 : };
289 :
290 : // Apply an action to every tile within the circle
291 : template<typename Func>
292 2 : void ForEachTileInCircle(const TileCircle& circle, Func&& func)
293 : {
294 94 : for (std::int32_t tileZ = circle.minZ; tileZ <= circle.maxZ; ++tileZ)
295 : {
296 92 : const std::int32_t deltaZ{tileZ - circle.centerZ};
297 92 : const std::int32_t squaredDeltaZ{deltaZ * deltaZ};
298 :
299 5046 : for (std::int32_t tileX = circle.minX; tileX <= circle.maxX; ++tileX)
300 : {
301 4954 : const std::int32_t deltaX{tileX - circle.centerX};
302 4954 : if (deltaX * deltaX + squaredDeltaZ > circle.squaredRadius)
303 200 : continue;
304 :
305 4754 : func(tileX, tileZ);
306 : }
307 : }
308 2 : }
309 :
310 : /**
311 : * Functor for sorting entities by distance from a source point.
312 : * It must only be passed entities that are in 'entities'
313 : * and are currently in the world.
314 : */
315 : class EntityDistanceOrdering
316 : {
317 : public:
318 79 : EntityDistanceOrdering(const EntityMap<EntityData>& entities, const CFixedVector2D& source) :
319 79 : m_EntityData(entities), m_Source(source)
320 : {
321 : }
322 :
323 : EntityDistanceOrdering(const EntityDistanceOrdering& entity) = default;
324 :
325 0 : bool operator()(entity_id_t a, entity_id_t b) const
326 : {
327 0 : const EntityData& da = m_EntityData.find(a)->second;
328 0 : const EntityData& db = m_EntityData.find(b)->second;
329 0 : CFixedVector2D vecA = CFixedVector2D(da.x, da.z) - m_Source;
330 0 : CFixedVector2D vecB = CFixedVector2D(db.x, db.z) - m_Source;
331 0 : return (vecA.CompareLength(vecB) < 0);
332 : }
333 :
334 : const EntityMap<EntityData>& m_EntityData;
335 : CFixedVector2D m_Source;
336 :
337 : private:
338 : EntityDistanceOrdering& operator=(const EntityDistanceOrdering&);
339 : };
340 : } // anonymous namespace
341 :
342 : /**
343 : * Serialization helper template for Query
344 : */
345 : template<>
346 : struct SerializeHelper<Query>
347 : {
348 : template<typename S>
349 912 : void Common(S& serialize, const char* /*name*/, Serialize::qualify<S, Query> value)
350 : {
351 912 : serialize.NumberFixed_Unbounded("min range", value.minRange);
352 912 : serialize.NumberFixed_Unbounded("max range", value.maxRange);
353 912 : serialize.NumberFixed_Unbounded("baseRange", value.baseRange);
354 912 : serialize.NumberFixed_Unbounded("yOrigin", value.yOrigin);
355 912 : serialize.NumberU32_Unbounded("owners mask", value.ownersMask);
356 912 : serialize.NumberI32_Unbounded("interface", value.interface);
357 912 : Serializer(serialize, "last match", value.lastMatch);
358 912 : serialize.NumberU8_Unbounded("flagsMask", value.flagsMask);
359 912 : serialize.Bool("enabled", value.enabled);
360 912 : serialize.Bool("parabolic",value.parabolic);
361 912 : serialize.Bool("account for size",value.accountForSize);
362 912 : serialize.Bool("preferMirages", value.preferMirages);
363 912 : }
364 :
365 912 : void operator()(ISerializer& serialize, const char* name, Query& value, const CSimContext&)
366 : {
367 912 : Common(serialize, name, value);
368 :
369 912 : uint32_t id = value.source.GetId();
370 912 : serialize.NumberU32_Unbounded("source", id);
371 : }
372 :
373 0 : void operator()(IDeserializer& deserialize, const char* name, Query& value, const CSimContext& context)
374 : {
375 0 : Common(deserialize, name, value);
376 :
377 0 : uint32_t id;
378 0 : deserialize.NumberU32_Unbounded("source", id);
379 0 : value.source = context.GetComponentManager().LookupEntityHandle(id, true);
380 : // the referenced entity might not have been deserialized yet,
381 : // so tell LookupEntityHandle to allocate the handle if necessary
382 0 : }
383 : };
384 :
385 : /**
386 : * Serialization helper template for EntityData
387 : */
388 : template<>
389 : struct SerializeHelper<EntityData>
390 : {
391 : template<typename S>
392 1032 : void operator()(S& serialize, const char* /*name*/, Serialize::qualify<S, EntityData> value)
393 : {
394 1032 : serialize.NumberFixed_Unbounded("x", value.x);
395 1032 : serialize.NumberFixed_Unbounded("z", value.z);
396 1032 : serialize.NumberFixed_Unbounded("vision", value.visionRange);
397 1032 : serialize.NumberU32_Unbounded("visibilities", value.visibilities);
398 1032 : serialize.NumberU32_Unbounded("size", value.size);
399 1032 : serialize.NumberU16_Unbounded("vision sharing", value.visionSharing);
400 1032 : serialize.NumberI8_Unbounded("owner", value.owner);
401 1032 : serialize.NumberU8_Unbounded("flags", value.flags);
402 1032 : }
403 : };
404 :
405 : /**
406 : * Range manager implementation.
407 : * Maintains a list of all entities (and their positions and owners), which is used for
408 : * queries.
409 : *
410 : * LOS implementation is based on the model described in GPG2.
411 : * (TODO: would be nice to make it cleverer, so e.g. mountains and walls
412 : * can block vision)
413 : */
414 16 : class CCmpRangeManager final : public ICmpRangeManager
415 : {
416 : public:
417 137 : static void ClassInit(CComponentManager& componentManager)
418 : {
419 137 : componentManager.SubscribeGloballyToMessageType(MT_Create);
420 137 : componentManager.SubscribeGloballyToMessageType(MT_PositionChanged);
421 137 : componentManager.SubscribeGloballyToMessageType(MT_OwnershipChanged);
422 137 : componentManager.SubscribeGloballyToMessageType(MT_Destroy);
423 137 : componentManager.SubscribeGloballyToMessageType(MT_VisionRangeChanged);
424 137 : componentManager.SubscribeGloballyToMessageType(MT_VisionSharingChanged);
425 :
426 137 : componentManager.SubscribeToMessageType(MT_Deserialized);
427 137 : componentManager.SubscribeToMessageType(MT_Update);
428 137 : componentManager.SubscribeToMessageType(MT_RenderSubmit); // for debug overlays
429 137 : }
430 :
431 32 : DEFAULT_COMPONENT_ALLOCATOR(RangeManager)
432 :
433 : bool m_DebugOverlayEnabled;
434 : bool m_DebugOverlayDirty;
435 : std::vector<SOverlayLine> m_DebugOverlayLines;
436 :
437 : // Deserialization flag. A lot of different functions are called by Deserialize()
438 : // and we don't want to pass isDeserializing bool arguments to all of them...
439 : bool m_Deserializing;
440 :
441 : // World bounds (entities are expected to be within this range)
442 : entity_pos_t m_WorldX0;
443 : entity_pos_t m_WorldZ0;
444 : entity_pos_t m_WorldX1;
445 : entity_pos_t m_WorldZ1;
446 :
447 : // Range query state:
448 : tag_t m_QueryNext; // next allocated id
449 : std::map<tag_t, Query> m_Queries;
450 : EntityMap<EntityData> m_EntityData;
451 :
452 : using RangeUpdateMessage = std::pair<entity_id_t, CMessageRangeUpdate>;
453 :
454 : FastSpatialSubdivision m_Subdivision; // spatial index of m_EntityData
455 :
456 : // One persistent buffer for each hardware thread including the main thread.
457 : // Used to temporarily store the results of all the asynchronous spatial subdivision queries
458 : // (which can get quite long) always in the same place to minimize reallocations and memory fragmentation.
459 : std::vector<std::vector<entity_id_t>> m_SubdivisionResultBuffers;
460 :
461 : // LOS state:
462 : static const player_id_t MAX_LOS_PLAYER_ID = 16;
463 :
464 : using LosRegion = std::pair<std::uint16_t, std::uint16_t>;
465 :
466 : std::array<bool, MAX_LOS_PLAYER_ID+1> m_LosRevealWholeMap;
467 : bool m_LosRevealWholeMapForAll;
468 : bool m_LosCircular;
469 : std::int32_t m_LosVerticesPerSide;
470 :
471 : // Cache for visibility tracking
472 : std::int32_t m_LosRegionsPerSide;
473 : bool m_GlobalVisibilityUpdate;
474 : std::array<bool, MAX_LOS_PLAYER_ID> m_GlobalPlayerVisibilityUpdate;
475 : Grid<std::uint16_t> m_DirtyVisibility;
476 : Grid<std::set<entity_id_t>> m_LosRegions;
477 : // List of entities that must be updated, regardless of the status of their tile
478 : std::vector<entity_id_t> m_ModifiedEntities;
479 :
480 : // Counts of units seeing vertex, per vertex, per player (starting with player 0).
481 : // Use std::uint16_t to avoid overflows when we have very large (but not infeasibly large) numbers
482 : // of units in a very small area.
483 : // (Note we use vertexes, not tiles, to better match the renderer.)
484 : // Lazily constructed when it's needed, to save memory in smaller games.
485 : std::array<Grid<std::uint16_t>, MAX_LOS_PLAYER_ID> m_LosPlayerCounts;
486 :
487 : // 2-bit LosState per player, starting with player 1 (not 0!) up to player MAX_LOS_PLAYER_ID (inclusive)
488 : Grid<std::uint32_t> m_LosState;
489 :
490 : // Special static visibility data for the "reveal whole map" mode
491 : // (TODO: this is usually a waste of memory)
492 : Grid<std::uint32_t> m_LosStateRevealed;
493 :
494 : // Shared LOS masks, one per player.
495 : std::array<std::uint32_t, MAX_LOS_PLAYER_ID+2> m_SharedLosMasks;
496 : // Shared dirty visibility masks, one per player.
497 : std::array<std::uint16_t, MAX_LOS_PLAYER_ID+2> m_SharedDirtyVisibilityMasks;
498 :
499 : // Cache explored vertices per player (not serialized)
500 : std::uint32_t m_TotalInworldVertices;
501 : std::vector<std::uint32_t> m_ExploredVertices;
502 :
503 137 : static std::string GetSchema()
504 : {
505 274 : return "<a:component type='system'/><empty/>";
506 : }
507 :
508 16 : void Init(const CParamNode&) override
509 : {
510 16 : m_QueryNext = 1;
511 :
512 16 : m_DebugOverlayEnabled = false;
513 16 : m_DebugOverlayDirty = true;
514 :
515 16 : m_Deserializing = false;
516 16 : m_WorldX0 = m_WorldZ0 = m_WorldX1 = m_WorldZ1 = entity_pos_t::Zero();
517 :
518 : // Initialise with bogus values (these will get replaced when
519 : // SetBounds is called)
520 16 : ResetSubdivisions(entity_pos_t::FromInt(1024), entity_pos_t::FromInt(1024));
521 :
522 :
523 16 : m_SubdivisionResultBuffers.resize(g_TaskManager.GetNumberOfWorkers() + 1);
524 80 : for (std::vector<entity_id_t>& buffer : m_SubdivisionResultBuffers)
525 64 : buffer.reserve(4096);
526 :
527 : // The whole map should be visible to Gaia by default, else e.g. animals
528 : // will get confused when trying to run from enemies
529 16 : m_LosRevealWholeMap[0] = true;
530 :
531 16 : m_GlobalVisibilityUpdate = true;
532 :
533 16 : m_LosCircular = false;
534 16 : m_LosVerticesPerSide = 0;
535 16 : }
536 :
537 16 : void Deinit() override
538 : {
539 16 : }
540 :
541 : template<typename S>
542 18 : void SerializeCommon(S& serialize)
543 : {
544 18 : serialize.NumberFixed_Unbounded("world x0", m_WorldX0);
545 18 : serialize.NumberFixed_Unbounded("world z0", m_WorldZ0);
546 18 : serialize.NumberFixed_Unbounded("world x1", m_WorldX1);
547 18 : serialize.NumberFixed_Unbounded("world z1", m_WorldZ1);
548 :
549 18 : serialize.NumberU32_Unbounded("query next", m_QueryNext);
550 18 : Serializer(serialize, "queries", m_Queries, GetSimContext());
551 18 : Serializer(serialize, "entity data", m_EntityData);
552 :
553 18 : Serializer(serialize, "los reveal whole map", m_LosRevealWholeMap);
554 18 : serialize.Bool("los reveal whole map for all", m_LosRevealWholeMapForAll);
555 18 : serialize.Bool("los circular", m_LosCircular);
556 18 : serialize.NumberI32_Unbounded("los verts per side", m_LosVerticesPerSide);
557 :
558 18 : serialize.Bool("global visibility update", m_GlobalVisibilityUpdate);
559 18 : Serializer(serialize, "global player visibility update", m_GlobalPlayerVisibilityUpdate);
560 18 : Serializer(serialize, "dirty visibility", m_DirtyVisibility);
561 18 : Serializer(serialize, "modified entities", m_ModifiedEntities);
562 :
563 : // We don't serialize m_Subdivision, m_LosPlayerCounts or m_LosRegions
564 : // since they can be recomputed from the entity data when deserializing;
565 : // m_LosState must be serialized since it depends on the history of exploration
566 :
567 18 : Serializer(serialize, "los state", m_LosState);
568 360 : Serializer(serialize, "shared los masks", m_SharedLosMasks);
569 18 : Serializer(serialize, "shared dirty visibility masks", m_SharedDirtyVisibilityMasks);
570 18 : }
571 :
572 18 : void Serialize(ISerializer& serialize) override
573 : {
574 18 : SerializeCommon(serialize);
575 18 : }
576 :
577 0 : void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
578 : {
579 0 : Init(paramNode);
580 :
581 0 : SerializeCommon(deserialize);
582 0 : }
583 :
584 9656 : void HandleMessage(const CMessage& msg, bool /*global*/) override
585 : {
586 9656 : switch (msg.GetType())
587 : {
588 0 : case MT_Deserialized:
589 0 : {
590 : // Reinitialize subdivisions and LOS data after all
591 : // other components have been deserialized.
592 0 : m_Deserializing = true;
593 0 : ResetDerivedData();
594 0 : m_Deserializing = false;
595 0 : break;
596 : }
597 217 : case MT_Create:
598 217 : {
599 217 : const CMessageCreate& msgData = static_cast<const CMessageCreate&> (msg);
600 217 : entity_id_t ent = msgData.entity;
601 :
602 : // Ignore local entities - we shouldn't let them influence anything
603 217 : if (ENTITY_IS_LOCAL(ent))
604 : break;
605 :
606 : // Ignore non-positional entities
607 208 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), ent);
608 208 : if (!cmpPosition)
609 : break;
610 :
611 : // The newly-created entity will have owner -1 and position out-of-world
612 : // (any initialisation of those values will happen later), so we can just
613 : // use the default-constructed EntityData here
614 193 : EntityData entdata;
615 :
616 : // Store the LOS data, if any
617 193 : CmpPtr<ICmpVision> cmpVision(GetSimContext(), ent);
618 193 : if (cmpVision)
619 : {
620 187 : entdata.visionRange = cmpVision->GetRange();
621 187 : entdata.SetFlag<FlagMasks::RevealShore>(cmpVision->GetRevealShore());
622 : }
623 193 : CmpPtr<ICmpVisibility> cmpVisibility(GetSimContext(), ent);
624 193 : if (cmpVisibility)
625 180 : entdata.SetFlag<FlagMasks::RetainInFog>(cmpVisibility->GetRetainInFog());
626 :
627 : // Store the size
628 193 : CmpPtr<ICmpObstruction> cmpObstruction(GetSimContext(), ent);
629 193 : if (cmpObstruction)
630 192 : entdata.size = cmpObstruction->GetSize().ToInt_RoundToInfinity();
631 :
632 : // Remember this entity
633 193 : m_EntityData.insert(ent, entdata);
634 : break;
635 : }
636 8983 : case MT_PositionChanged:
637 8983 : {
638 8983 : const CMessagePositionChanged& msgData = static_cast<const CMessagePositionChanged&> (msg);
639 8983 : entity_id_t ent = msgData.entity;
640 :
641 8983 : EntityMap<EntityData>::iterator it = m_EntityData.find(ent);
642 :
643 : // Ignore if we're not already tracking this entity
644 8983 : if (it == m_EntityData.end())
645 : break;
646 :
647 8965 : if (msgData.inWorld)
648 : {
649 8965 : if (it->second.HasFlag<FlagMasks::InWorld>())
650 : {
651 8772 : CFixedVector2D from(it->second.x, it->second.z);
652 8772 : CFixedVector2D to(msgData.x, msgData.z);
653 8772 : m_Subdivision.Move(ent, from, to, it->second.size);
654 8772 : if (it->second.HasFlag<FlagMasks::SharedVision>())
655 0 : SharingLosMove(it->second.visionSharing, it->second.visionRange, from, to);
656 : else
657 8772 : LosMove(it->second.owner, it->second.visionRange, from, to);
658 8772 : LosRegion oldLosRegion = PosToLosRegionsHelper(it->second.x, it->second.z);
659 8772 : LosRegion newLosRegion = PosToLosRegionsHelper(msgData.x, msgData.z);
660 17544 : if (oldLosRegion != newLosRegion)
661 : {
662 1573 : RemoveFromRegion(oldLosRegion, ent);
663 3146 : AddToRegion(newLosRegion, ent);
664 : }
665 : }
666 : else
667 : {
668 193 : CFixedVector2D to(msgData.x, msgData.z);
669 193 : m_Subdivision.Add(ent, to, it->second.size);
670 193 : if (it->second.HasFlag<FlagMasks::SharedVision>())
671 0 : SharingLosAdd(it->second.visionSharing, it->second.visionRange, to);
672 : else
673 193 : LosAdd(it->second.owner, it->second.visionRange, to);
674 386 : AddToRegion(PosToLosRegionsHelper(msgData.x, msgData.z), ent);
675 : }
676 :
677 8965 : it->second.SetFlag<FlagMasks::InWorld>(true);
678 8965 : it->second.x = msgData.x;
679 8965 : it->second.z = msgData.z;
680 : }
681 : else
682 : {
683 0 : if (it->second.HasFlag<FlagMasks::InWorld>())
684 : {
685 0 : CFixedVector2D from(it->second.x, it->second.z);
686 0 : m_Subdivision.Remove(ent, from, it->second.size);
687 0 : if (it->second.HasFlag<FlagMasks::SharedVision>())
688 0 : SharingLosRemove(it->second.visionSharing, it->second.visionRange, from);
689 : else
690 0 : LosRemove(it->second.owner, it->second.visionRange, from);
691 0 : RemoveFromRegion(PosToLosRegionsHelper(it->second.x, it->second.z), ent);
692 : }
693 :
694 0 : it->second.SetFlag<FlagMasks::InWorld>(false);
695 0 : it->second.x = entity_pos_t::Zero();
696 0 : it->second.z = entity_pos_t::Zero();
697 : }
698 :
699 8965 : RequestVisibilityUpdate(ent);
700 :
701 : break;
702 : }
703 238 : case MT_OwnershipChanged:
704 238 : {
705 238 : const CMessageOwnershipChanged& msgData = static_cast<const CMessageOwnershipChanged&> (msg);
706 238 : entity_id_t ent = msgData.entity;
707 :
708 238 : EntityMap<EntityData>::iterator it = m_EntityData.find(ent);
709 :
710 : // Ignore if we're not already tracking this entity
711 238 : if (it == m_EntityData.end())
712 : break;
713 :
714 229 : if (it->second.HasFlag<FlagMasks::InWorld>())
715 : {
716 : // Entity vision is taken into account in VisionSharingChanged
717 : // when sharing component activated
718 44 : if (!it->second.HasFlag<FlagMasks::SharedVision>())
719 : {
720 44 : CFixedVector2D pos(it->second.x, it->second.z);
721 88 : LosRemove(it->second.owner, it->second.visionRange, pos);
722 44 : LosAdd(msgData.to, it->second.visionRange, pos);
723 : }
724 :
725 44 : if (it->second.HasFlag<FlagMasks::RevealShore>())
726 : {
727 0 : RevealShore(it->second.owner, false);
728 0 : RevealShore(msgData.to, true);
729 : }
730 : }
731 :
732 229 : ENSURE(-128 <= msgData.to && msgData.to <= 127);
733 229 : it->second.owner = static_cast<std::int8_t>(msgData.to);
734 :
735 229 : break;
736 : }
737 32 : case MT_Destroy:
738 32 : {
739 32 : const CMessageDestroy& msgData = static_cast<const CMessageDestroy&> (msg);
740 32 : entity_id_t ent = msgData.entity;
741 :
742 32 : EntityMap<EntityData>::iterator it = m_EntityData.find(ent);
743 :
744 : // Ignore if we're not already tracking this entity
745 32 : if (it == m_EntityData.end())
746 : break;
747 :
748 30 : if (it->second.HasFlag<FlagMasks::InWorld>())
749 : {
750 30 : m_Subdivision.Remove(ent, CFixedVector2D(it->second.x, it->second.z), it->second.size);
751 30 : RemoveFromRegion(PosToLosRegionsHelper(it->second.x, it->second.z), ent);
752 : }
753 :
754 : // This will be called after Ownership's OnDestroy, so ownership will be set
755 : // to -1 already and we don't have to do a LosRemove here
756 30 : ENSURE(it->second.owner == -1);
757 :
758 30 : m_EntityData.erase(it);
759 :
760 : break;
761 : }
762 0 : case MT_VisionRangeChanged:
763 0 : {
764 0 : const CMessageVisionRangeChanged& msgData = static_cast<const CMessageVisionRangeChanged&> (msg);
765 0 : entity_id_t ent = msgData.entity;
766 :
767 0 : EntityMap<EntityData>::iterator it = m_EntityData.find(ent);
768 :
769 : // Ignore if we're not already tracking this entity
770 0 : if (it == m_EntityData.end())
771 : break;
772 :
773 0 : CmpPtr<ICmpVision> cmpVision(GetSimContext(), ent);
774 0 : if (!cmpVision)
775 : break;
776 :
777 0 : entity_pos_t oldRange = it->second.visionRange;
778 0 : entity_pos_t newRange = msgData.newRange;
779 :
780 : // If the range changed and the entity's in-world, we need to manually adjust it
781 : // but if it's not in-world, we only need to set the new vision range
782 :
783 0 : it->second.visionRange = newRange;
784 :
785 0 : if (it->second.HasFlag<FlagMasks::InWorld>())
786 : {
787 0 : CFixedVector2D pos(it->second.x, it->second.z);
788 0 : if (it->second.HasFlag<FlagMasks::SharedVision>())
789 : {
790 0 : SharingLosRemove(it->second.visionSharing, oldRange, pos);
791 0 : SharingLosAdd(it->second.visionSharing, newRange, pos);
792 : }
793 : else
794 : {
795 0 : LosRemove(it->second.owner, oldRange, pos);
796 0 : LosAdd(it->second.owner, newRange, pos);
797 : }
798 : }
799 :
800 : break;
801 : }
802 0 : case MT_VisionSharingChanged:
803 0 : {
804 0 : const CMessageVisionSharingChanged& msgData = static_cast<const CMessageVisionSharingChanged&> (msg);
805 0 : entity_id_t ent = msgData.entity;
806 :
807 0 : EntityMap<EntityData>::iterator it = m_EntityData.find(ent);
808 :
809 : // Ignore if we're not already tracking this entity
810 0 : if (it == m_EntityData.end())
811 : break;
812 :
813 0 : ENSURE(msgData.player > 0 && msgData.player < MAX_LOS_PLAYER_ID+1);
814 0 : std::uint16_t visionChanged = CalcVisionSharingMask(msgData.player);
815 :
816 0 : if (!it->second.HasFlag<FlagMasks::SharedVision>())
817 : {
818 : // Activation of the Vision Sharing
819 0 : ENSURE(it->second.owner == static_cast<std::int8_t>(msgData.player));
820 0 : it->second.visionSharing = visionChanged;
821 0 : it->second.SetFlag<FlagMasks::SharedVision>(true);
822 : break;
823 : }
824 :
825 0 : if (it->second.HasFlag<FlagMasks::InWorld>())
826 : {
827 0 : entity_pos_t range = it->second.visionRange;
828 0 : CFixedVector2D pos(it->second.x, it->second.z);
829 0 : if (msgData.add)
830 0 : LosAdd(msgData.player, range, pos);
831 : else
832 0 : LosRemove(msgData.player, range, pos);
833 : }
834 :
835 0 : if (msgData.add)
836 0 : it->second.visionSharing |= visionChanged;
837 : else
838 0 : it->second.visionSharing &= ~visionChanged;
839 : break;
840 : }
841 186 : case MT_Update:
842 186 : {
843 186 : m_DebugOverlayDirty = true;
844 186 : ExecuteActiveQueries();
845 186 : UpdateVisibilityData();
846 186 : break;
847 : }
848 0 : case MT_RenderSubmit:
849 0 : {
850 0 : const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
851 0 : RenderSubmit(msgData.collector);
852 0 : break;
853 : }
854 : }
855 9656 : }
856 :
857 8 : void SetBounds(entity_pos_t x0, entity_pos_t z0, entity_pos_t x1, entity_pos_t z1) override
858 : {
859 : // Don't support rectangular looking maps.
860 8 : ENSURE(x1-x0 == z1-z0);
861 8 : m_WorldX0 = x0;
862 8 : m_WorldZ0 = z0;
863 8 : m_WorldX1 = x1;
864 8 : m_WorldZ1 = z1;
865 8 : m_LosVerticesPerSide = ((x1 - x0) / LOS_TILE_SIZE).ToInt_RoundToZero() + 1;
866 :
867 8 : ResetDerivedData();
868 8 : }
869 :
870 1041 : void Verify() override
871 : {
872 : // Ignore if map not initialised yet
873 1041 : if (m_WorldX1.IsZero())
874 0 : return;
875 :
876 : // Check that calling ResetDerivedData (i.e. recomputing all the state from scratch)
877 : // does not affect the incrementally-computed state
878 :
879 1041 : std::array<Grid<std::uint16_t>, MAX_LOS_PLAYER_ID> oldPlayerCounts = m_LosPlayerCounts;
880 1041 : Grid<std::uint32_t> oldStateRevealed = m_LosStateRevealed;
881 1041 : FastSpatialSubdivision oldSubdivision = m_Subdivision;
882 1041 : Grid<std::set<entity_id_t> > oldLosRegions = m_LosRegions;
883 :
884 1041 : m_Deserializing = true;
885 1041 : ResetDerivedData();
886 1041 : m_Deserializing = false;
887 :
888 2082 : if (oldPlayerCounts != m_LosPlayerCounts)
889 : {
890 0 : for (size_t id = 0; id < m_LosPlayerCounts.size(); ++id)
891 : {
892 0 : debug_printf("player %zu\n", id);
893 0 : for (size_t i = 0; i < oldPlayerCounts[id].width(); ++i)
894 : {
895 0 : for (size_t j = 0; j < oldPlayerCounts[id].height(); ++j)
896 0 : debug_printf("%i ", oldPlayerCounts[id].get(i,j));
897 0 : debug_printf("\n");
898 : }
899 : }
900 0 : for (size_t id = 0; id < m_LosPlayerCounts.size(); ++id)
901 : {
902 0 : debug_printf("player %zu\n", id);
903 0 : for (size_t i = 0; i < m_LosPlayerCounts[id].width(); ++i)
904 : {
905 0 : for (size_t j = 0; j < m_LosPlayerCounts[id].height(); ++j)
906 0 : debug_printf("%i ", m_LosPlayerCounts[id].get(i,j));
907 0 : debug_printf("\n");
908 : }
909 : }
910 0 : debug_warn(L"inconsistent player counts");
911 : }
912 1041 : if (oldStateRevealed != m_LosStateRevealed)
913 0 : debug_warn(L"inconsistent revealed");
914 1041 : if (oldSubdivision != m_Subdivision)
915 0 : debug_warn(L"inconsistent subdivs");
916 1041 : if (oldLosRegions != m_LosRegions)
917 0 : debug_warn(L"inconsistent los regions");
918 3123 : }
919 :
920 0 : FastSpatialSubdivision* GetSubdivision() override
921 : {
922 0 : return &m_Subdivision;
923 : }
924 :
925 : // Reinitialise subdivisions and LOS data, based on entity data
926 1052 : void ResetDerivedData()
927 : {
928 1052 : ENSURE(m_WorldX0.IsZero() && m_WorldZ0.IsZero()); // don't bother implementing non-zero offsets yet
929 1052 : ResetSubdivisions(m_WorldX1, m_WorldZ1);
930 :
931 1052 : m_LosRegionsPerSide = m_LosVerticesPerSide / LOS_REGION_RATIO;
932 :
933 17884 : for (size_t player_id = 0; player_id < m_LosPlayerCounts.size(); ++player_id)
934 16832 : m_LosPlayerCounts[player_id].clear();
935 :
936 1052 : m_ExploredVertices.clear();
937 1052 : m_ExploredVertices.resize(MAX_LOS_PLAYER_ID+1, 0);
938 :
939 1052 : if (m_Deserializing)
940 : {
941 : // recalc current exploration stats.
942 135138 : for (std::int32_t j = 0; j < m_LosVerticesPerSide; j++)
943 17420130 : for (std::int32_t i = 0; i < m_LosVerticesPerSide; i++)
944 17286033 : if (!LosIsOffWorld(i, j))
945 267143865 : for (std::uint8_t k = 1; k < MAX_LOS_PLAYER_ID+1; ++k)
946 : {
947 251429520 : m_ExploredVertices.at(k) += ((m_LosState.get(i, j) &
948 : (static_cast<std::uint32_t>(LosState::EXPLORED) <<
949 251429520 : (2 * (k - 1)))) > 0);
950 : }
951 : } else
952 11 : m_LosState.resize(m_LosVerticesPerSide, m_LosVerticesPerSide);
953 :
954 1052 : m_LosStateRevealed.resize(m_LosVerticesPerSide, m_LosVerticesPerSide);
955 :
956 1052 : if (!m_Deserializing)
957 : {
958 11 : m_DirtyVisibility.resize(m_LosRegionsPerSide, m_LosRegionsPerSide);
959 : }
960 1052 : ENSURE(m_DirtyVisibility.width() == m_LosRegionsPerSide);
961 1052 : ENSURE(m_DirtyVisibility.height() == m_LosRegionsPerSide);
962 :
963 1052 : m_LosRegions.resize(m_LosRegionsPerSide, m_LosRegionsPerSide);
964 :
965 4174 : for (EntityMap<EntityData>::const_iterator it = m_EntityData.begin(); it != m_EntityData.end(); ++it)
966 1035 : if (it->second.HasFlag<FlagMasks::InWorld>())
967 : {
968 1033 : if (it->second.HasFlag<FlagMasks::SharedVision>())
969 0 : SharingLosAdd(it->second.visionSharing, it->second.visionRange, CFixedVector2D(it->second.x, it->second.z));
970 : else
971 2066 : LosAdd(it->second.owner, it->second.visionRange, CFixedVector2D(it->second.x, it->second.z));
972 2066 : AddToRegion(PosToLosRegionsHelper(it->second.x, it->second.z), it->first);
973 :
974 1033 : if (it->second.HasFlag<FlagMasks::RevealShore>())
975 0 : RevealShore(it->second.owner, true);
976 : }
977 :
978 1052 : m_TotalInworldVertices = 0;
979 136888 : for (std::int32_t j = 0; j < m_LosVerticesPerSide; ++j)
980 17716152 : for (std::int32_t i = 0; i < m_LosVerticesPerSide; ++i)
981 : {
982 17580316 : if (LosIsOffWorld(i,j))
983 1592160 : m_LosStateRevealed.get(i, j) = 0;
984 : else
985 : {
986 15988156 : m_LosStateRevealed.get(i, j) = 0xFFFFFFFFu;
987 15988156 : m_TotalInworldVertices++;
988 : }
989 : }
990 1052 : }
991 :
992 1068 : void ResetSubdivisions(entity_pos_t x1, entity_pos_t z1)
993 : {
994 1068 : m_Subdivision.Reset(x1, z1);
995 :
996 4206 : for (EntityMap<EntityData>::const_iterator it = m_EntityData.begin(); it != m_EntityData.end(); ++it)
997 1035 : if (it->second.HasFlag<FlagMasks::InWorld>())
998 1033 : m_Subdivision.Add(it->first, CFixedVector2D(it->second.x, it->second.z), it->second.size);
999 1068 : }
1000 :
1001 111 : tag_t CreateActiveQuery(entity_id_t source,
1002 : entity_pos_t minRange, entity_pos_t maxRange,
1003 : const std::vector<int>& owners, int requiredInterface, std::uint8_t flags,
1004 : bool accountForSize, bool preferMirages) override
1005 : {
1006 111 : tag_t id = m_QueryNext++;
1007 111 : m_Queries[id] = ConstructQuery(source, minRange, maxRange, owners, requiredInterface, flags, accountForSize, preferMirages);
1008 111 : return id;
1009 : }
1010 :
1011 55 : tag_t CreateActiveParabolicQuery(entity_id_t source,
1012 : entity_pos_t minRange, entity_pos_t maxRange, entity_pos_t baseRange, entity_pos_t yOrigin,
1013 : const std::vector<int>& owners, int requiredInterface, std::uint8_t flags, bool preferMirages = false) override
1014 : {
1015 55 : tag_t id = m_QueryNext++;
1016 55 : m_Queries[id] = ConstructParabolicQuery(source, minRange, maxRange, baseRange, yOrigin, owners, requiredInterface, flags, true, preferMirages);
1017 55 : return id;
1018 : }
1019 :
1020 34 : void DestroyActiveQuery(tag_t tag) override
1021 : {
1022 68 : if (m_Queries.find(tag) == m_Queries.end())
1023 : {
1024 0 : LOGERROR("CCmpRangeManager: DestroyActiveQuery called with invalid tag {}", tag);
1025 0 : return;
1026 : }
1027 :
1028 34 : m_Queries.erase(tag);
1029 : }
1030 :
1031 166 : void EnableActiveQuery(tag_t tag) override
1032 : {
1033 166 : std::map<tag_t, Query>::iterator it = m_Queries.find(tag);
1034 166 : if (it == m_Queries.end())
1035 : {
1036 0 : LOGERROR("CCmpRangeManager: EnableActiveQuery called with invalid tag {}", tag);
1037 0 : return;
1038 : }
1039 :
1040 166 : Query& q = it->second;
1041 166 : q.enabled = true;
1042 : }
1043 :
1044 162 : void DisableActiveQuery(tag_t tag) override
1045 : {
1046 162 : std::map<tag_t, Query>::iterator it = m_Queries.find(tag);
1047 162 : if (it == m_Queries.end())
1048 : {
1049 0 : LOGERROR("CCmpRangeManager: DisableActiveQuery called with invalid tag {}", tag);
1050 0 : return;
1051 : }
1052 :
1053 162 : Query& q = it->second;
1054 162 : q.enabled = false;
1055 : }
1056 :
1057 0 : bool IsActiveQueryEnabled(tag_t tag) const override
1058 : {
1059 0 : std::map<tag_t, Query>::const_iterator it = m_Queries.find(tag);
1060 0 : if (it == m_Queries.end())
1061 : {
1062 0 : LOGERROR("CCmpRangeManager: IsActiveQueryEnabled called with invalid tag {}", tag);
1063 0 : return false;
1064 : }
1065 :
1066 0 : const Query& q = it->second;
1067 0 : return q.enabled;
1068 : }
1069 :
1070 57 : std::vector<entity_id_t> ExecuteQueryAroundPos(const CFixedVector2D& pos,
1071 : entity_pos_t minRange, entity_pos_t maxRange,
1072 : const std::vector<int>& owners, int requiredInterface, bool accountForSize) override
1073 : {
1074 57 : Query q = ConstructQuery(INVALID_ENTITY, minRange, maxRange, owners, requiredInterface, GetEntityFlagMask("normal"), accountForSize);
1075 57 : std::vector<entity_id_t> r;
1076 57 : PerformQuery(q, r, pos, m_SubdivisionResultBuffers[0]);
1077 :
1078 : // Return the list sorted by distance from the entity
1079 57 : std::stable_sort(r.begin(), r.end(), EntityDistanceOrdering(m_EntityData, pos));
1080 :
1081 57 : return r;
1082 57 : }
1083 :
1084 13 : std::vector<entity_id_t> ExecuteQuery(entity_id_t source,
1085 : entity_pos_t minRange, entity_pos_t maxRange,
1086 : const std::vector<int>& owners, int requiredInterface, bool accountForSize) override
1087 : {
1088 13 : PROFILE("ExecuteQuery");
1089 :
1090 13 : Query q = ConstructQuery(source, minRange, maxRange, owners, requiredInterface, GetEntityFlagMask("normal"), accountForSize);
1091 :
1092 13 : std::vector<entity_id_t> r;
1093 :
1094 13 : CmpPtr<ICmpPosition> cmpSourcePosition(q.source);
1095 13 : if (!cmpSourcePosition || !cmpSourcePosition->IsInWorld())
1096 : {
1097 : // If the source doesn't have a position, then the result is just the empty list
1098 : return r;
1099 : }
1100 :
1101 13 : CFixedVector2D pos = cmpSourcePosition->GetPosition2D();
1102 13 : PerformQuery(q, r, pos, m_SubdivisionResultBuffers[0]);
1103 :
1104 : // Return the list sorted by distance from the entity
1105 13 : std::stable_sort(r.begin(), r.end(), EntityDistanceOrdering(m_EntityData, pos));
1106 :
1107 13 : return r;
1108 13 : }
1109 :
1110 6 : std::vector<entity_id_t> ResetActiveQuery(tag_t tag) override
1111 : {
1112 6 : PROFILE("ResetActiveQuery");
1113 :
1114 6 : std::vector<entity_id_t> r;
1115 :
1116 6 : std::map<tag_t, Query>::iterator it = m_Queries.find(tag);
1117 6 : if (it == m_Queries.end())
1118 : {
1119 0 : LOGERROR("CCmpRangeManager: ResetActiveQuery called with invalid tag {}", tag);
1120 0 : return r;
1121 : }
1122 :
1123 6 : Query& q = it->second;
1124 6 : q.enabled = true;
1125 :
1126 6 : CmpPtr<ICmpPosition> cmpSourcePosition(q.source);
1127 6 : if (!cmpSourcePosition || !cmpSourcePosition->IsInWorld())
1128 : {
1129 : // If the source doesn't have a position, then the result is just the empty list
1130 0 : q.lastMatch = r;
1131 : return r;
1132 : }
1133 :
1134 6 : CFixedVector2D pos = cmpSourcePosition->GetPosition2D();
1135 6 : PerformQuery(q, r, pos, m_SubdivisionResultBuffers[0]);
1136 :
1137 6 : q.lastMatch = r;
1138 :
1139 : // Return the list sorted by distance from the entity
1140 6 : std::stable_sort(r.begin(), r.end(), EntityDistanceOrdering(m_EntityData, pos));
1141 :
1142 6 : return r;
1143 6 : }
1144 :
1145 280 : std::vector<entity_id_t> GetEntitiesByPlayer(player_id_t player) const override
1146 : {
1147 560 : return GetEntitiesByMask(CalcOwnerMask(player));
1148 : }
1149 :
1150 8 : std::vector<entity_id_t> GetNonGaiaEntities() const override
1151 : {
1152 8 : return GetEntitiesByMask(~3u); // bit 0 for owner=-1 and bit 1 for gaia
1153 : }
1154 :
1155 0 : std::vector<entity_id_t> GetGaiaAndNonGaiaEntities() const override
1156 : {
1157 0 : return GetEntitiesByMask(~1u); // bit 0 for owner=-1
1158 : }
1159 :
1160 288 : std::vector<entity_id_t> GetEntitiesByMask(std::uint32_t ownerMask) const
1161 : {
1162 288 : std::vector<entity_id_t> entities;
1163 :
1164 720 : for (EntityMap<EntityData>::const_iterator it = m_EntityData.begin(); it != m_EntityData.end(); ++it)
1165 : {
1166 : // Check owner and add to list if it matches
1167 144 : if (CalcOwnerMask(it->second.owner) & ownerMask)
1168 15 : entities.push_back(it->first);
1169 : }
1170 :
1171 288 : return entities;
1172 0 : }
1173 :
1174 0 : void SetDebugOverlay(bool enabled) override
1175 : {
1176 0 : m_DebugOverlayEnabled = enabled;
1177 0 : m_DebugOverlayDirty = true;
1178 0 : if (!enabled)
1179 0 : m_DebugOverlayLines.clear();
1180 0 : }
1181 :
1182 : /**
1183 : * Update all currently-enabled active queries.
1184 : */
1185 186 : void ExecuteActiveQueries()
1186 : {
1187 186 : PROFILE3("ExecuteActiveQueries");
1188 :
1189 186 : std::mutex mtx;
1190 :
1191 : // Points to the first unexecuted query (to be processed next).
1192 186 : std::map<tag_t, Query>::iterator it = m_Queries.begin();
1193 :
1194 : // Store a queue of all range update messages before sending any, since they modify the state of the simulation
1195 : // (including this component), which would interfere with the asynchronous tasks.
1196 : // Important: The order of messages must be fully deterministic.
1197 186 : std::vector<std::optional<RangeUpdateMessage>> messages(m_Queries.size());
1198 :
1199 : // Used to write update messages to the corresponding index in the message vector and maintain the original order.
1200 186 : size_t messageIdx = 0;
1201 :
1202 785 : const auto ProcessQueriesAsync = [&](std::vector<entity_id_t>& subdivisionResultsBuffer) {
1203 599 : PROFILE2("Async range query execution");
1204 :
1205 599 : std::vector<entity_id_t> results;
1206 599 : std::vector<entity_id_t> added;
1207 599 : std::vector<entity_id_t> removed;
1208 :
1209 7734 : while (true)
1210 : {
1211 7734 : size_t idxCopy;
1212 7734 : std::map<tag_t, Query>::iterator itCopy;
1213 :
1214 7734 : {
1215 : // Critical section:
1216 : // Retrieve the next query to process or stop if none are left.
1217 :
1218 7734 : std::lock_guard lg(mtx);
1219 7735 : if (it == m_Queries.end())
1220 : break;
1221 :
1222 7136 : itCopy = it++; // Only copy the iterator now and dereference it later, outside the critical section.
1223 7136 : idxCopy = messageIdx++;
1224 599 : }
1225 :
1226 7135 : tag_t tag = itCopy->first;
1227 7135 : Query& query = itCopy->second;
1228 :
1229 7135 : if (!query.enabled)
1230 14534 : continue;
1231 :
1232 335 : results.clear();
1233 335 : CmpPtr<ICmpPosition> cmpSourcePosition(query.source);
1234 335 : if (cmpSourcePosition && cmpSourcePosition->IsInWorld())
1235 : {
1236 335 : results.reserve(query.lastMatch.size());
1237 335 : PerformQuery(query, results, cmpSourcePosition->GetPosition2D(), subdivisionResultsBuffer);
1238 : }
1239 :
1240 : // Compute the changes vs the last match
1241 335 : added.clear();
1242 335 : removed.clear();
1243 : // Return the 'added' list sorted by distance from the entity
1244 : // (Don't bother sorting 'removed' because they might not even have positions or exist any more)
1245 335 : std::set_difference(results.begin(), results.end(), query.lastMatch.begin(), query.lastMatch.end(),
1246 : std::back_inserter(added));
1247 335 : std::set_difference(query.lastMatch.begin(), query.lastMatch.end(), results.begin(), results.end(),
1248 : std::back_inserter(removed));
1249 335 : if (added.empty() && removed.empty())
1250 332 : continue;
1251 :
1252 3 : if (cmpSourcePosition && cmpSourcePosition->IsInWorld())
1253 3 : std::stable_sort(added.begin(), added.end(), EntityDistanceOrdering(m_EntityData, cmpSourcePosition->GetPosition2D()));
1254 :
1255 : // Safe because it's guaranteed that no two threads can write to the same index anyway.
1256 3 : messages[idxCopy].emplace(
1257 3 : query.source.GetId(),
1258 6 : CMessageRangeUpdate(tag, std::move(added), std::move(removed))
1259 : );
1260 3 : query.lastMatch.swap(results);
1261 : }
1262 603 : };
1263 :
1264 186 : size_t numFutures = std::min(g_TaskManager.GetNumberOfWorkers(), m_Queries.size());
1265 186 : std::vector<Future<void>> futures;
1266 186 : futures.reserve(numFutures);
1267 599 : for (size_t i = 0; i < numFutures; i++)
1268 826 : futures.push_back({g_TaskManager,
1269 826 : [&ProcessQueriesAsync, &subdivisionResultsBuffer = m_SubdivisionResultBuffers[i]]() {
1270 413 : ProcessQueriesAsync(subdivisionResultsBuffer);
1271 : }
1272 : });
1273 :
1274 : // Start working in the main thread as well.
1275 186 : ProcessQueriesAsync(m_SubdivisionResultBuffers[numFutures]);
1276 :
1277 599 : for (Future<void>& future : futures)
1278 413 : future.Get();
1279 :
1280 186 : CComponentManager& cmpMgr = GetSimContext().GetComponentManager();
1281 7322 : for (const auto& msg : messages)
1282 7136 : if (msg.has_value())
1283 3 : cmpMgr.PostMessage(msg->first, msg->second);
1284 186 : }
1285 :
1286 : /**
1287 : * Returns whether the given entity matches the given query (ignoring maxRange)
1288 : */
1289 2546 : bool TestEntityQuery(const Query& q, entity_id_t id, const EntityData& entity) const
1290 : {
1291 : // Quick filter to ignore entities with the wrong owner
1292 5091 : if (!(CalcOwnerMask(entity.owner) & q.ownersMask))
1293 : return false;
1294 :
1295 : // Ignore entities not present in the world
1296 1353 : if (!entity.HasFlag<FlagMasks::InWorld>())
1297 : return false;
1298 :
1299 : // Ignore entities that don't match the current flags
1300 1353 : if (!((entity.flags & FlagMasks::AllQuery) & q.flagsMask))
1301 : return false;
1302 :
1303 : // Ignore self
1304 1353 : if (id == q.source.GetId())
1305 : return false;
1306 :
1307 : // Check if this is a mirage entity
1308 1331 : CmpPtr<ICmpMirage> cmpMirage(GetSimContext(), id);
1309 1331 : bool isMirage = !!cmpMirage;
1310 :
1311 : // If it's a mirage and we're not including mirages, skip it
1312 1331 : if (isMirage && !q.preferMirages)
1313 : return false;
1314 :
1315 : // If it's not a mirage, check interface normally
1316 1331 : if (!isMirage && q.interface && !GetSimContext().GetComponentManager().QueryInterface(id, q.interface))
1317 : return false;
1318 :
1319 : // Filter hidden entities when we want mirages (i.e., we care about visibility).
1320 1331 : if (q.preferMirages && q.source.GetId() != INVALID_ENTITY)
1321 : {
1322 : // Look up the source's current owner.
1323 1115 : EntityMap<EntityData>::const_iterator itSource = m_EntityData.find(q.source.GetId());
1324 1115 : if (itSource != m_EntityData.end())
1325 : {
1326 1115 : player_id_t sourceOwner = itSource->second.owner;
1327 : // Gaia and observers have no slot in the visibility mask (GetPlayerVisibility
1328 : // would report HIDDEN for everything); the whole map is visible to them anyway.
1329 1115 : if (sourceOwner > 0)
1330 : {
1331 1110 : LosVisibility vis = GetPlayerVisibility(entity.visibilities, sourceOwner);
1332 1110 : if (vis == LosVisibility::HIDDEN)
1333 1281 : return false;
1334 : }
1335 : }
1336 : }
1337 :
1338 : return true;
1339 : }
1340 :
1341 : /**
1342 : * Returns a list of distinct entity IDs that match the given query, sorted by ID.
1343 : */
1344 411 : void PerformQuery(const Query& q, std::vector<entity_id_t>& r, CFixedVector2D pos, std::vector<uint32_t>& subdivisionResultsBuffer)
1345 : {
1346 :
1347 : // Special case: range is ALWAYS_IN_RANGE means check all entities ignoring distance.
1348 411 : if (q.maxRange == ALWAYS_IN_RANGE)
1349 : {
1350 0 : for (EntityMap<EntityData>::const_iterator it = m_EntityData.begin(); it != m_EntityData.end(); ++it)
1351 : {
1352 0 : if (!TestEntityQuery(q, it->first, it->second))
1353 0 : continue;
1354 :
1355 0 : r.push_back(it->first);
1356 : }
1357 : }
1358 : // Not the entire world, so check a parabolic range, or a regular range.
1359 411 : else if (q.parabolic)
1360 : {
1361 : // The yOrigin is part of the 3D position, as the source is really that much higher.
1362 2 : CmpPtr<ICmpPosition> cmpSourcePosition(q.source);
1363 2 : CFixedVector3D pos3d = cmpSourcePosition->GetPosition() +
1364 2 : CFixedVector3D(entity_pos_t::Zero(), q.yOrigin, entity_pos_t::Zero());
1365 : // Get a quick list of entities that are potentially in range.
1366 : // For parabolic queries, the search radius must cover:
1367 : // 1. The baseRange circle (non-parabolic detection)
1368 : // 2. The maximum possible horizontal extent of the parabolic range
1369 : // Multiplying maxRange by 2 provides a safe upper bound for all possible height differences.
1370 2 : entity_pos_t subdivisionRange = std::max(q.baseRange, q.maxRange * 2);
1371 2 : subdivisionResultsBuffer.clear();
1372 2 : m_Subdivision.GetNear(subdivisionResultsBuffer, pos, subdivisionRange);
1373 :
1374 6 : for (size_t i = 0; i < subdivisionResultsBuffer.size(); ++i)
1375 : {
1376 8 : EntityMap<EntityData>::const_iterator it = m_EntityData.find(subdivisionResultsBuffer[i]);
1377 4 : ENSURE(it != m_EntityData.end());
1378 :
1379 4 : if (!TestEntityQuery(q, it->first, it->second))
1380 4 : continue;
1381 :
1382 2 : CFixedVector2D delta2D = CFixedVector2D(it->second.x, it->second.z) - pos;
1383 :
1384 : // Check base range first
1385 2 : bool inBaseRange = !q.baseRange.IsZero() && delta2D.CompareLength(q.baseRange) <= 0;
1386 :
1387 2 : if (inBaseRange)
1388 : {
1389 : // In base range - no need for parabolic check
1390 2 : if (q.minRange.IsZero() || delta2D.CompareLength(q.minRange) >= 0)
1391 2 : r.push_back(it->first);
1392 2 : continue;
1393 : }
1394 :
1395 : // Parabolic check for entities outside base range
1396 0 : CmpPtr<ICmpPosition> cmpSecondPosition(GetSimContext(), subdivisionResultsBuffer[i]);
1397 0 : if (!cmpSecondPosition || !cmpSecondPosition->IsInWorld())
1398 0 : continue;
1399 0 : CFixedVector3D secondPosition = cmpSecondPosition->GetPosition();
1400 :
1401 : // Doing an exact check for parabolas with obstruction sizes is not really possible.
1402 : // However, we can prove that InParabolicRange(d, range + size) > InParabolicRange(d, range)
1403 : // in the sense that it always returns true when the latter would, which is enough.
1404 : // To do so, compute the derivative with respect to distance, and notice that
1405 : // they have an intersection after which the former grows slower, and then use that to prove the above.
1406 : // Note that this is only true because we do not account for vertical size here,
1407 : // if we did, we would also need to artificially 'raise' the source over the target.
1408 0 : entity_pos_t range = q.maxRange + (q.accountForSize ? fixed::FromInt(it->second.size) : fixed::Zero());
1409 0 : if (!InParabolicRange(CFixedVector3D(it->second.x, secondPosition.Y, it->second.z) - pos3d, range))
1410 0 : continue;
1411 :
1412 0 : if (!q.minRange.IsZero())
1413 0 : if (delta2D.CompareLength(q.minRange) < 0)
1414 0 : continue;
1415 :
1416 0 : r.push_back(it->first);
1417 : }
1418 2 : std::sort(r.begin(), r.end());
1419 : }
1420 : // check a regular range (i.e. not the entire world, and not parabolic)
1421 : else
1422 : {
1423 : // Get a quick list of entities that are potentially in range
1424 409 : subdivisionResultsBuffer.clear();
1425 409 : m_Subdivision.GetNear(subdivisionResultsBuffer, pos, q.maxRange);
1426 :
1427 2951 : for (size_t i = 0; i < subdivisionResultsBuffer.size(); ++i)
1428 : {
1429 5082 : EntityMap<EntityData>::const_iterator it = m_EntityData.find(subdivisionResultsBuffer[i]);
1430 2541 : ENSURE(it != m_EntityData.end());
1431 :
1432 2541 : if (!TestEntityQuery(q, it->first, it->second))
1433 1278 : continue;
1434 :
1435 : // Restrict based on approximate circle-circle distance.
1436 1264 : entity_pos_t range = q.maxRange + (q.accountForSize ? fixed::FromInt(it->second.size) : fixed::Zero());
1437 1264 : if ((CFixedVector2D(it->second.x, it->second.z) - pos).CompareLength(range) > 0)
1438 1207 : continue;
1439 :
1440 57 : if (!q.minRange.IsZero())
1441 12 : if ((CFixedVector2D(it->second.x, it->second.z) - pos).CompareLength(q.minRange) < 0)
1442 4 : continue;
1443 :
1444 53 : r.push_back(it->first);
1445 : }
1446 409 : std::sort(r.begin(), r.end());
1447 : }
1448 411 : }
1449 :
1450 : /**
1451 : * Compute effective horizontal range given a reference range and height difference.
1452 : */
1453 943 : static entity_pos_t ComputeParabolicRange(entity_pos_t range, entity_pos_t heightDiff)
1454 : {
1455 943 : if (heightDiff < -range / 2)
1456 2 : return NEVER_IN_RANGE;
1457 :
1458 941 : entity_pos_t effectiveRange;
1459 941 : effectiveRange.SetInternalValue(static_cast<std::int32_t>(isqrt64(
1460 941 : SQUARE_U64_FIXED(range) +
1461 941 : static_cast<std::int64_t>(heightDiff.GetInternalValue()) *
1462 941 : static_cast<std::int64_t>(range.GetInternalValue()) * 2
1463 : )));
1464 941 : return effectiveRange;
1465 : }
1466 :
1467 946 : entity_pos_t GetEffectiveParabolicRange(entity_id_t source, entity_id_t target, entity_pos_t range, entity_pos_t yOrigin) const override
1468 : {
1469 : // For non-positive ranges, just return the range.
1470 946 : if (range < entity_pos_t::Zero())
1471 1 : return range;
1472 :
1473 945 : CmpPtr<ICmpPosition> cmpSourcePosition(GetSimContext(), source);
1474 945 : if (!cmpSourcePosition || !cmpSourcePosition->IsInWorld())
1475 1 : return NEVER_IN_RANGE;
1476 :
1477 944 : CmpPtr<ICmpPosition> cmpTargetPosition(GetSimContext(), target);
1478 944 : if (!cmpTargetPosition || !cmpTargetPosition->IsInWorld())
1479 1 : return NEVER_IN_RANGE;
1480 :
1481 : // GetPosition() returns the world height (terrain + water + offset)
1482 943 : CFixedVector3D sourcePos = cmpSourcePosition->GetPosition();
1483 943 : CFixedVector3D targetPos = cmpTargetPosition->GetPosition();
1484 :
1485 943 : entity_pos_t heightDiff = sourcePos.Y - targetPos.Y + yOrigin;
1486 943 : return ComputeParabolicRange(range, heightDiff);
1487 : }
1488 :
1489 156 : entity_pos_t GetMaxReachableParabolicHeight(entity_pos_t range, entity_pos_t yOrigin, entity_pos_t horizDistance) const override
1490 : {
1491 : // No range, no parabola - and no division below either.
1492 156 : if (range <= entity_pos_t::Zero())
1493 3 : return yOrigin;
1494 :
1495 : // EffectiveRange² = range² + 2 * range * heightDiff
1496 : // Solve for heightDiff when effectiveRange = horizDistance:
1497 : // heightDiff = (horizDistance² - range²) / (2 * range)
1498 : // Max target height above source = yOrigin - heightDiff
1499 : // = yOrigin + (range² - horizDistance²) / (2 * range)
1500 : //
1501 : // If horizDistance > range, the result is less than yOrigin (can be negative),
1502 : // meaning the source must be above the target to compensate for the extra horizontal distance.
1503 : // The caller can decide if that's acceptable.
1504 153 : std::int64_t rangeSq = SQUARE_U64_FIXED(range);
1505 153 : std::int64_t distSq = SQUARE_U64_FIXED(horizDistance);
1506 153 : std::int64_t numerator = rangeSq - distSq;
1507 :
1508 153 : entity_pos_t result;
1509 153 : result.SetInternalValue(static_cast<std::int32_t>(numerator /
1510 153 : (static_cast<std::int64_t>(range.GetInternalValue()) * 2)));
1511 153 : return yOrigin + result;
1512 : }
1513 :
1514 0 : entity_pos_t GetElevationAdaptedRange(const CFixedVector3D& pos1, const CFixedVector3D& rot, entity_pos_t range, entity_pos_t yOrigin, entity_pos_t angle) const override
1515 : {
1516 0 : entity_pos_t r = entity_pos_t::Zero();
1517 0 : CFixedVector3D pos(pos1);
1518 :
1519 0 : pos.Y += yOrigin;
1520 0 : entity_pos_t orientation = rot.Y;
1521 :
1522 0 : entity_pos_t maxAngle = orientation + angle/2;
1523 0 : entity_pos_t minAngle = orientation - angle/2;
1524 :
1525 0 : int numberOfSteps = 16;
1526 :
1527 0 : if (angle == entity_pos_t::Zero())
1528 0 : numberOfSteps = 1;
1529 :
1530 0 : std::vector<entity_pos_t> coords = getParabolicRangeForm(pos, range, range*2, minAngle, maxAngle, numberOfSteps);
1531 :
1532 0 : entity_pos_t part = entity_pos_t::FromInt(numberOfSteps);
1533 :
1534 0 : for (int i = 0; i < numberOfSteps; ++i)
1535 0 : r = r + CFixedVector2D(coords[2*i],coords[2*i+1]).Length() / part;
1536 :
1537 0 : return r;
1538 :
1539 0 : }
1540 :
1541 0 : std::vector<entity_pos_t> getParabolicRangeForm(CFixedVector3D pos, entity_pos_t maxRange, entity_pos_t cutoff, entity_pos_t minAngle, entity_pos_t maxAngle, int numberOfSteps) const
1542 : {
1543 0 : std::vector<entity_pos_t> r;
1544 :
1545 0 : CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
1546 0 : if (!cmpTerrain)
1547 : return r;
1548 :
1549 : // angle = 0 goes in the positive Z direction
1550 0 : std::uint64_t precisionSquared = SQUARE_U64_FIXED(PARABOLIC_RANGE_TOLERANCE);
1551 :
1552 0 : CmpPtr<ICmpWaterManager> cmpWaterManager(GetSystemEntity());
1553 0 : entity_pos_t waterLevel = cmpWaterManager ? cmpWaterManager->GetWaterLevel(pos.X, pos.Z) : entity_pos_t::Zero();
1554 0 : entity_pos_t thisHeight = pos.Y > waterLevel ? pos.Y : waterLevel;
1555 :
1556 0 : for (int i = 0; i < numberOfSteps; ++i)
1557 : {
1558 0 : entity_pos_t angle = minAngle + (maxAngle - minAngle) / numberOfSteps * i;
1559 0 : entity_pos_t sin;
1560 0 : entity_pos_t cos;
1561 0 : entity_pos_t minDistance = entity_pos_t::Zero();
1562 0 : entity_pos_t maxDistance = cutoff;
1563 0 : sincos_approx(angle, sin, cos);
1564 :
1565 0 : CFixedVector2D minVector = CFixedVector2D(entity_pos_t::Zero(), entity_pos_t::Zero());
1566 0 : CFixedVector2D maxVector = CFixedVector2D(sin, cos).Multiply(cutoff);
1567 0 : entity_pos_t targetHeight = cmpTerrain->GetGroundLevel(pos.X+maxVector.X, pos.Z+maxVector.Y);
1568 : // use water level to display range on water
1569 0 : targetHeight = targetHeight > waterLevel ? targetHeight : waterLevel;
1570 :
1571 0 : if (InParabolicRange(CFixedVector3D(maxVector.X, targetHeight-thisHeight, maxVector.Y), maxRange))
1572 : {
1573 0 : r.push_back(maxVector.X);
1574 0 : r.push_back(maxVector.Y);
1575 0 : continue;
1576 : }
1577 :
1578 : // Loop until vectors come close enough
1579 0 : while ((maxVector - minVector).CompareLengthSquared(precisionSquared) > 0)
1580 : {
1581 : // difference still bigger than precision, bisect to get smaller difference
1582 0 : entity_pos_t newDistance = (minDistance+maxDistance)/entity_pos_t::FromInt(2);
1583 :
1584 0 : CFixedVector2D newVector = CFixedVector2D(sin, cos).Multiply(newDistance);
1585 :
1586 : // get the height of the ground
1587 0 : targetHeight = cmpTerrain->GetGroundLevel(pos.X+newVector.X, pos.Z+newVector.Y);
1588 0 : targetHeight = targetHeight > waterLevel ? targetHeight : waterLevel;
1589 :
1590 0 : if (InParabolicRange(CFixedVector3D(newVector.X, targetHeight-thisHeight, newVector.Y), maxRange))
1591 : {
1592 : // new vector is in parabolic range, so this is a new minVector
1593 : minVector = newVector;
1594 : minDistance = newDistance;
1595 : }
1596 : else
1597 : {
1598 : // new vector is out parabolic range, so this is a new maxVector
1599 0 : maxVector = newVector;
1600 0 : maxDistance = newDistance;
1601 : }
1602 :
1603 : }
1604 0 : r.push_back(maxVector.X);
1605 0 : r.push_back(maxVector.Y);
1606 :
1607 : }
1608 0 : r.push_back(r[0]);
1609 0 : r.push_back(r[1]);
1610 :
1611 : return r;
1612 0 : }
1613 :
1614 236 : Query ConstructQuery(entity_id_t source,
1615 : entity_pos_t minRange, entity_pos_t maxRange,
1616 : const std::vector<int>& owners, int requiredInterface, std::uint8_t flagsMask,
1617 : bool accountForSize, bool preferMirages = false) const
1618 : {
1619 : // Min range must be non-negative.
1620 236 : if (minRange < entity_pos_t::Zero())
1621 : {
1622 0 : LOGWARNING("CCmpRangeManager: Invalid min range {:f} in query for entity {}",
1623 : minRange.ToDouble(), source);
1624 : }
1625 :
1626 : // Max range must be non-negative, or else ALWAYS_IN_RANGE.
1627 : // TODO add NEVER_IN_RANGE.
1628 236 : if (maxRange < entity_pos_t::Zero() && maxRange != ALWAYS_IN_RANGE)
1629 : {
1630 0 : LOGWARNING("CCmpRangeManager: Invalid max range {:f} in query for entity {}",
1631 : maxRange.ToDouble(), source);
1632 : }
1633 :
1634 236 : CmpPtr<ICmpOwnership> cmpOwnership(GetSimContext(), source);
1635 :
1636 236 : Query q;
1637 236 : q.enabled = false;
1638 236 : q.parabolic = false;
1639 236 : q.source = GetSimContext().GetComponentManager().LookupEntityHandle(source);
1640 236 : q.minRange = minRange;
1641 236 : q.maxRange = maxRange;
1642 236 : q.yOrigin = entity_pos_t::Zero();
1643 236 : q.accountForSize = accountForSize;
1644 236 : q.preferMirages = preferMirages;
1645 :
1646 236 : if (q.accountForSize && q.source.GetId() != INVALID_ENTITY && q.maxRange != ALWAYS_IN_RANGE)
1647 : {
1648 71 : std::uint32_t size = 0;
1649 71 : if (ENTITY_IS_LOCAL(q.source.GetId()))
1650 : {
1651 0 : CmpPtr<ICmpObstruction> cmpObstruction(GetSimContext(), q.source.GetId());
1652 0 : if (cmpObstruction)
1653 0 : size = cmpObstruction->GetSize().ToInt_RoundToInfinity();
1654 : }
1655 : else
1656 : {
1657 71 : EntityMap<EntityData>::const_iterator it = m_EntityData.find(q.source.GetId());
1658 71 : if (it != m_EntityData.end())
1659 71 : size = it->second.size;
1660 : }
1661 : // Adjust the range query based on the querier's obstruction radius.
1662 : // The smallest side of the obstruction isn't known here, so we can't safely adjust the min-range, only the max.
1663 : // 'size' is the diagonal size rounded up so this will cover all possible rotations of the querier.
1664 71 : q.maxRange += fixed::FromInt(size);
1665 : }
1666 :
1667 236 : q.ownersMask = 0;
1668 691 : for (size_t i = 0; i < owners.size(); ++i)
1669 910 : q.ownersMask |= CalcOwnerMask(owners[i]);
1670 :
1671 236 : if (q.ownersMask == 0)
1672 0 : LOGWARNING("CCmpRangeManager: No owners in query for entity {}", source);
1673 :
1674 236 : q.interface = requiredInterface;
1675 236 : q.flagsMask = flagsMask;
1676 :
1677 236 : return q;
1678 0 : }
1679 :
1680 55 : Query ConstructParabolicQuery(entity_id_t source,
1681 : entity_pos_t minRange, entity_pos_t maxRange, entity_pos_t baseRange, entity_pos_t yOrigin,
1682 : const std::vector<int>& owners, int requiredInterface, std::uint8_t flagsMask,
1683 : bool accountForSize, bool preferMirages = false) const
1684 : {
1685 55 : Query q = ConstructQuery(source, minRange, maxRange, owners, requiredInterface, flagsMask, accountForSize, preferMirages);
1686 55 : q.parabolic = true;
1687 55 : q.yOrigin = yOrigin;
1688 55 : q.baseRange = baseRange;
1689 55 : return q;
1690 : }
1691 :
1692 0 : void RenderSubmit(SceneCollector& collector)
1693 : {
1694 0 : if (!m_DebugOverlayEnabled)
1695 : return;
1696 0 : static CColor disabledRingColor(1, 0, 0, 1); // red
1697 0 : static CColor enabledRingColor(0, 1, 0, 1); // green
1698 0 : static CColor subdivColor(0, 0, 1, 1); // blue
1699 0 : static CColor rayColor(1, 1, 0, 0.2f);
1700 :
1701 0 : if (m_DebugOverlayDirty)
1702 : {
1703 0 : m_DebugOverlayLines.clear();
1704 :
1705 0 : for (std::map<tag_t, Query>::iterator it = m_Queries.begin(); it != m_Queries.end(); ++it)
1706 : {
1707 0 : Query& q = it->second;
1708 :
1709 0 : CmpPtr<ICmpPosition> cmpSourcePosition(q.source);
1710 0 : if (!cmpSourcePosition || !cmpSourcePosition->IsInWorld())
1711 0 : continue;
1712 0 : CFixedVector2D pos = cmpSourcePosition->GetPosition2D();
1713 :
1714 : // Draw the max range circle
1715 0 : if (!q.parabolic)
1716 : {
1717 0 : m_DebugOverlayLines.push_back(SOverlayLine());
1718 0 : m_DebugOverlayLines.back().m_Color = (q.enabled ? enabledRingColor : disabledRingColor);
1719 0 : SimRender::ConstructCircleOnGround(GetSimContext(), pos.X.ToFloat(), pos.Y.ToFloat(), q.maxRange.ToFloat(), m_DebugOverlayLines.back(), true);
1720 : }
1721 : else
1722 : {
1723 : // yOrigin is part of the 3D position. As if the unit is really that much higher.
1724 0 : CFixedVector3D pos3D = cmpSourcePosition->GetPosition();
1725 0 : pos3D.Y += q.yOrigin;
1726 :
1727 0 : std::vector<entity_pos_t> coords;
1728 :
1729 : // Get the outline from cache if possible
1730 0 : if (ParabolicRangesOutlines.find(q.source.GetId()) != ParabolicRangesOutlines.end())
1731 : {
1732 0 : EntityParabolicRangeOutline e = ParabolicRangesOutlines[q.source.GetId()];
1733 0 : if (e.position == pos3D && e.range == q.maxRange)
1734 : {
1735 : // outline is cached correctly, use it
1736 0 : coords = e.outline;
1737 : }
1738 : else
1739 : {
1740 : // outline was cached, but important parameters changed
1741 : // (position, elevation, range)
1742 : // update it
1743 0 : coords = getParabolicRangeForm(pos3D,q.maxRange,q.maxRange*2, entity_pos_t::Zero(), entity_pos_t::FromFloat(2.0f*3.14f),70);
1744 0 : e.outline = coords;
1745 0 : e.range = q.maxRange;
1746 0 : e.position = pos3D;
1747 0 : ParabolicRangesOutlines[q.source.GetId()] = e;
1748 : }
1749 0 : }
1750 : else
1751 : {
1752 : // outline wasn't cached (first time you enable the range overlay
1753 : // or you created a new entiy)
1754 : // cache a new outline
1755 0 : coords = getParabolicRangeForm(pos3D,q.maxRange,q.maxRange*2, entity_pos_t::Zero(), entity_pos_t::FromFloat(2.0f*3.14f),70);
1756 0 : EntityParabolicRangeOutline e;
1757 0 : e.source = q.source.GetId();
1758 0 : e.range = q.maxRange;
1759 0 : e.position = pos3D;
1760 0 : e.outline = coords;
1761 0 : ParabolicRangesOutlines[q.source.GetId()] = e;
1762 0 : }
1763 :
1764 0 : CColor thiscolor = q.enabled ? enabledRingColor : disabledRingColor;
1765 :
1766 : // draw the outline (piece by piece)
1767 0 : for (size_t i = 3; i < coords.size(); i += 2)
1768 : {
1769 0 : std::vector<float> c;
1770 0 : c.push_back((coords[i - 3] + pos3D.X).ToFloat());
1771 0 : c.push_back((coords[i - 2] + pos3D.Z).ToFloat());
1772 0 : c.push_back((coords[i - 1] + pos3D.X).ToFloat());
1773 0 : c.push_back((coords[i] + pos3D.Z).ToFloat());
1774 0 : m_DebugOverlayLines.push_back(SOverlayLine());
1775 0 : m_DebugOverlayLines.back().m_Color = thiscolor;
1776 0 : SimRender::ConstructLineOnGround(GetSimContext(), c, m_DebugOverlayLines.back(), true);
1777 0 : }
1778 0 : }
1779 :
1780 : // Draw the min range circle
1781 0 : if (!q.minRange.IsZero())
1782 0 : SimRender::ConstructCircleOnGround(GetSimContext(), pos.X.ToFloat(), pos.Y.ToFloat(), q.minRange.ToFloat(), m_DebugOverlayLines.back(), true);
1783 :
1784 : // Draw a ray from the source to each matched entity
1785 0 : for (size_t i = 0; i < q.lastMatch.size(); ++i)
1786 : {
1787 0 : CmpPtr<ICmpPosition> cmpTargetPosition(GetSimContext(), q.lastMatch[i]);
1788 0 : if (!cmpTargetPosition || !cmpTargetPosition->IsInWorld())
1789 0 : continue;
1790 0 : CFixedVector2D targetPos = cmpTargetPosition->GetPosition2D();
1791 :
1792 0 : std::vector<float> coords;
1793 0 : coords.push_back(pos.X.ToFloat());
1794 0 : coords.push_back(pos.Y.ToFloat());
1795 0 : coords.push_back(targetPos.X.ToFloat());
1796 0 : coords.push_back(targetPos.Y.ToFloat());
1797 :
1798 0 : m_DebugOverlayLines.push_back(SOverlayLine());
1799 0 : m_DebugOverlayLines.back().m_Color = rayColor;
1800 0 : SimRender::ConstructLineOnGround(GetSimContext(), coords, m_DebugOverlayLines.back(), true);
1801 0 : }
1802 : }
1803 :
1804 : // render subdivision grid
1805 0 : float divSize = m_Subdivision.GetDivisionSize();
1806 0 : int size = m_Subdivision.GetWidth();
1807 0 : for (int x = 0; x < size; ++x)
1808 : {
1809 0 : for (int y = 0; y < size; ++y)
1810 : {
1811 0 : m_DebugOverlayLines.push_back(SOverlayLine());
1812 0 : m_DebugOverlayLines.back().m_Color = subdivColor;
1813 :
1814 0 : float xpos = x*divSize + divSize/2;
1815 0 : float zpos = y*divSize + divSize/2;
1816 0 : SimRender::ConstructSquareOnGround(GetSimContext(), xpos, zpos, divSize, divSize, 0.0f,
1817 0 : m_DebugOverlayLines.back(), false, 1.0f);
1818 : }
1819 : }
1820 :
1821 0 : m_DebugOverlayDirty = false;
1822 : }
1823 :
1824 0 : for (size_t i = 0; i < m_DebugOverlayLines.size(); ++i)
1825 0 : collector.Submit(&m_DebugOverlayLines[i]);
1826 : }
1827 :
1828 305 : std::uint8_t GetEntityFlagMask(const std::string& identifier) const override
1829 : {
1830 305 : if (identifier == "normal")
1831 : return FlagMasks::Normal;
1832 69 : if (identifier == "injured")
1833 : return FlagMasks::Injured;
1834 :
1835 0 : LOGWARNING("CCmpRangeManager: Invalid flag identifier {}", identifier);
1836 0 : return FlagMasks::None;
1837 : }
1838 :
1839 69 : void SetEntityFlag(entity_id_t ent, const std::string& identifier, bool value) override
1840 : {
1841 69 : EntityMap<EntityData>::iterator it = m_EntityData.find(ent);
1842 :
1843 : // We don't have this entity
1844 69 : if (it == m_EntityData.end())
1845 69 : return;
1846 :
1847 69 : std::uint8_t flag = GetEntityFlagMask(identifier);
1848 :
1849 69 : if (flag == FlagMasks::None)
1850 : {
1851 0 : LOGWARNING("CCmpRangeManager: Invalid flag identifier {} for entity {}", identifier,
1852 : ent);
1853 : }
1854 : else
1855 138 : it->second.SetFlag(flag, value);
1856 : }
1857 :
1858 : // ****************************************************************
1859 :
1860 : // LOS implementation:
1861 :
1862 0 : CLosQuerier GetLosQuerier(player_id_t player) const override
1863 : {
1864 0 : if (GetLosRevealWholeMap(player))
1865 0 : return CLosQuerier(0xFFFFFFFFu, m_LosStateRevealed, m_LosVerticesPerSide);
1866 : else
1867 0 : return CLosQuerier(GetSharedLosMask(player), m_LosState, m_LosVerticesPerSide);
1868 : }
1869 :
1870 9 : void ActivateScriptedVisibility(entity_id_t ent, bool status) override
1871 : {
1872 9 : EntityMap<EntityData>::iterator it = m_EntityData.find(ent);
1873 9 : if (it != m_EntityData.end())
1874 0 : it->second.SetFlag<FlagMasks::ScriptedVisibility>(status);
1875 9 : }
1876 :
1877 116069 : LosVisibility ComputeLosVisibility(CEntityHandle ent, player_id_t player) const
1878 : {
1879 : // Entities not with positions in the world are never visible
1880 116069 : if (ent.GetId() == INVALID_ENTITY)
1881 : return LosVisibility::HIDDEN;
1882 116069 : CmpPtr<ICmpPosition> cmpPosition(ent);
1883 116069 : if (!cmpPosition || !cmpPosition->IsInWorld())
1884 0 : return LosVisibility::HIDDEN;
1885 :
1886 : // Mirage entities, whatever the situation, are visible for one specific player
1887 116069 : CmpPtr<ICmpMirage> cmpMirage(ent);
1888 116069 : if (cmpMirage && cmpMirage->GetPlayer() != player)
1889 : return LosVisibility::HIDDEN;
1890 :
1891 116069 : CFixedVector2D pos = cmpPosition->GetPosition2D();
1892 116069 : int i = (pos.X / LOS_TILE_SIZE).ToInt_RoundToNearest();
1893 116069 : int j = (pos.Y / LOS_TILE_SIZE).ToInt_RoundToNearest();
1894 :
1895 : // Reveal flag makes all positioned entities visible and all mirages useless
1896 116069 : if (GetLosRevealWholeMap(player))
1897 : {
1898 87807 : if (LosIsOffWorld(i, j) || cmpMirage)
1899 : return LosVisibility::HIDDEN;
1900 : return LosVisibility::VISIBLE;
1901 : }
1902 :
1903 : // Get visible regions
1904 28262 : CLosQuerier los(GetSharedLosMask(player), m_LosState, m_LosVerticesPerSide);
1905 :
1906 28262 : CmpPtr<ICmpVisibility> cmpVisibility(ent);
1907 :
1908 : // Possibly ask the scripted Visibility component
1909 28262 : EntityMap<EntityData>::const_iterator it = m_EntityData.find(ent.GetId());
1910 28262 : if (it != m_EntityData.end())
1911 : {
1912 28262 : if (it->second.HasFlag<FlagMasks::ScriptedVisibility>() && cmpVisibility)
1913 0 : return cmpVisibility->GetVisibility(player, los.IsVisible(i, j), los.IsExplored(i, j));
1914 : }
1915 : else
1916 : {
1917 0 : if (cmpVisibility && cmpVisibility->IsActivated())
1918 0 : return cmpVisibility->GetVisibility(player, los.IsVisible(i, j), los.IsExplored(i, j));
1919 : }
1920 :
1921 : // Else, default behavior
1922 :
1923 28262 : if (los.IsVisible(i, j))
1924 : {
1925 3570 : if (cmpMirage)
1926 : return LosVisibility::HIDDEN;
1927 :
1928 : return LosVisibility::VISIBLE;
1929 : }
1930 :
1931 24692 : if (!los.IsExplored(i, j))
1932 : return LosVisibility::HIDDEN;
1933 :
1934 : // Invisible if the 'retain in fog' flag is not set, and in a non-visible explored region
1935 : // Try using the 'retainInFog' flag in m_EntityData to save a script call
1936 0 : if (it != m_EntityData.end())
1937 : {
1938 0 : if (!it->second.HasFlag<FlagMasks::RetainInFog>())
1939 : return LosVisibility::HIDDEN;
1940 : }
1941 : else
1942 : {
1943 0 : if (!(cmpVisibility && cmpVisibility->GetRetainInFog()))
1944 0 : return LosVisibility::HIDDEN;
1945 : }
1946 :
1947 0 : if (cmpMirage)
1948 : return LosVisibility::FOGGED;
1949 :
1950 0 : CmpPtr<ICmpOwnership> cmpOwnership(ent);
1951 0 : if (!cmpOwnership)
1952 : return LosVisibility::FOGGED;
1953 :
1954 0 : if (cmpOwnership->GetOwner() == player)
1955 : {
1956 0 : CmpPtr<ICmpFogging> cmpFogging(ent);
1957 0 : if (!(cmpFogging && cmpFogging->IsMiraged(player)))
1958 0 : return LosVisibility::FOGGED;
1959 :
1960 : return LosVisibility::HIDDEN;
1961 : }
1962 :
1963 : // Fogged entities are hidden in two cases:
1964 : // - They were not scouted
1965 : // - A mirage replaces them
1966 0 : CmpPtr<ICmpFogging> cmpFogging(ent);
1967 0 : if (cmpFogging && cmpFogging->IsActivated() &&
1968 0 : (!cmpFogging->WasSeen(player) || cmpFogging->IsMiraged(player)))
1969 0 : return LosVisibility::HIDDEN;
1970 :
1971 : return LosVisibility::FOGGED;
1972 : }
1973 :
1974 115499 : LosVisibility ComputeLosVisibility(entity_id_t ent, player_id_t player) const
1975 : {
1976 115499 : CEntityHandle handle = GetSimContext().GetComponentManager().LookupEntityHandle(ent);
1977 115499 : return ComputeLosVisibility(handle, player);
1978 : }
1979 :
1980 1527 : LosVisibility GetLosVisibility(CEntityHandle ent, player_id_t player) const override
1981 : {
1982 1527 : entity_id_t entId = ent.GetId();
1983 :
1984 : // Entities not with positions in the world are never visible
1985 1527 : if (entId == INVALID_ENTITY)
1986 : return LosVisibility::HIDDEN;
1987 :
1988 1527 : CmpPtr<ICmpPosition> cmpPosition(ent);
1989 1527 : if (!cmpPosition || !cmpPosition->IsInWorld())
1990 0 : return LosVisibility::HIDDEN;
1991 :
1992 : // Gaia and observers do not have a visibility cache
1993 1527 : if (player <= 0)
1994 0 : return ComputeLosVisibility(ent, player);
1995 :
1996 1527 : CFixedVector2D pos = cmpPosition->GetPosition2D();
1997 :
1998 1527 : if (IsVisibilityDirty(m_DirtyVisibility[PosToLosRegionsHelper(pos.X, pos.Y)], player))
1999 342 : return ComputeLosVisibility(ent, player);
2000 :
2001 1185 : if (std::find(m_ModifiedEntities.begin(), m_ModifiedEntities.end(), entId) != m_ModifiedEntities.end())
2002 228 : return ComputeLosVisibility(ent, player);
2003 :
2004 957 : EntityMap<EntityData>::const_iterator it = m_EntityData.find(entId);
2005 957 : if (it == m_EntityData.end())
2006 0 : return ComputeLosVisibility(ent, player);
2007 :
2008 957 : return static_cast<LosVisibility>(GetPlayerVisibility(it->second.visibilities, player));
2009 : }
2010 :
2011 1527 : LosVisibility GetLosVisibility(entity_id_t ent, player_id_t player) const override
2012 : {
2013 1527 : CEntityHandle handle = GetSimContext().GetComponentManager().LookupEntityHandle(ent);
2014 1527 : return GetLosVisibility(handle, player);
2015 : }
2016 :
2017 0 : LosVisibility GetLosVisibilityPosition(entity_pos_t x, entity_pos_t z, player_id_t player) const override
2018 : {
2019 0 : int i = (x / LOS_TILE_SIZE).ToInt_RoundToNearest();
2020 0 : int j = (z / LOS_TILE_SIZE).ToInt_RoundToNearest();
2021 :
2022 : // Reveal flag makes all positioned entities visible and all mirages useless
2023 0 : if (GetLosRevealWholeMap(player))
2024 : {
2025 0 : if (LosIsOffWorld(i, j))
2026 : return LosVisibility::HIDDEN;
2027 : else
2028 : return LosVisibility::VISIBLE;
2029 : }
2030 :
2031 : // Get visible regions
2032 0 : CLosQuerier los(GetSharedLosMask(player), m_LosState, m_LosVerticesPerSide);
2033 :
2034 0 : if (los.IsVisible(i,j))
2035 : return LosVisibility::VISIBLE;
2036 0 : if (los.IsExplored(i,j))
2037 : return LosVisibility::FOGGED;
2038 : return LosVisibility::HIDDEN;
2039 : }
2040 :
2041 0 : size_t GetVerticesPerSide() const override
2042 : {
2043 0 : return m_LosVerticesPerSide;
2044 : }
2045 :
2046 6307252 : LosRegion LosVertexToLosRegionsHelper(std::uint16_t x, std::uint16_t z) const
2047 : {
2048 6307252 : return LosRegion {
2049 7884065 : Clamp(x/LOS_REGION_RATIO, 0, m_LosRegionsPerSide - 1),
2050 6111102 : Clamp(z/LOS_REGION_RATIO, 0, m_LosRegionsPerSide - 1)
2051 : };
2052 : }
2053 :
2054 20327 : LosRegion PosToLosRegionsHelper(entity_pos_t x, entity_pos_t z) const
2055 : {
2056 20327 : std::uint16_t i = Clamp(
2057 20327 : (x/(LOS_TILE_SIZE*LOS_REGION_RATIO)).ToInt_RoundToZero(),
2058 : 0,
2059 20327 : m_LosRegionsPerSide - 1);
2060 40654 : std::uint16_t j = Clamp(
2061 20327 : (z/(LOS_TILE_SIZE*LOS_REGION_RATIO)).ToInt_RoundToZero(),
2062 : 0,
2063 20327 : m_LosRegionsPerSide - 1);
2064 20327 : return std::make_pair(i, j);
2065 : }
2066 :
2067 2799 : void AddToRegion(LosRegion region, entity_id_t ent)
2068 : {
2069 4565 : m_LosRegions[region].insert(ent);
2070 1766 : }
2071 :
2072 1603 : void RemoveFromRegion(LosRegion region, entity_id_t ent)
2073 : {
2074 1603 : std::set<entity_id_t>::const_iterator regionIt = m_LosRegions[region].find(ent);
2075 1603 : if (regionIt != m_LosRegions[region].end())
2076 1603 : m_LosRegions[region].erase(regionIt);
2077 1603 : }
2078 :
2079 186 : void UpdateVisibilityData()
2080 : {
2081 186 : PROFILE("UpdateVisibilityData");
2082 :
2083 4602 : for (std::uint16_t i = 0; i < m_LosRegionsPerSide; ++i)
2084 109632 : for (std::uint16_t j = 0; j < m_LosRegionsPerSide; ++j)
2085 : {
2086 : LosRegion pos{i, j};
2087 1788672 : for (player_id_t player = 1; player < MAX_LOS_PLAYER_ID + 1; ++player)
2088 1683456 : if (IsVisibilityDirty(m_DirtyVisibility[pos], player) || m_GlobalPlayerVisibilityUpdate[player-1] == 1 || m_GlobalVisibilityUpdate)
2089 92967 : for (const entity_id_t& ent : m_LosRegions[pos])
2090 4171 : UpdateVisibility(ent, player);
2091 :
2092 105216 : m_DirtyVisibility[pos] = 0;
2093 : }
2094 :
2095 186 : std::fill(m_GlobalPlayerVisibilityUpdate.begin(), m_GlobalPlayerVisibilityUpdate.end(), false);
2096 186 : m_GlobalVisibilityUpdate = false;
2097 :
2098 : // Calling UpdateVisibility can modify m_ModifiedEntities, so be careful:
2099 : // infinite loops could be triggered by feedback between entities and their mirages.
2100 186 : std::map<entity_id_t, std::uint8_t> attempts;
2101 7174 : while (!m_ModifiedEntities.empty())
2102 : {
2103 6988 : entity_id_t ent = m_ModifiedEntities.back();
2104 6988 : m_ModifiedEntities.pop_back();
2105 :
2106 6988 : ++attempts[ent];
2107 6988 : ENSURE(attempts[ent] < 100 && "Infinite loop in UpdateVisibilityData");
2108 :
2109 6988 : UpdateVisibility(ent);
2110 : }
2111 186 : }
2112 :
2113 8965 : void RequestVisibilityUpdate(entity_id_t ent) override
2114 : {
2115 8965 : if (std::find(m_ModifiedEntities.begin(), m_ModifiedEntities.end(), ent) == m_ModifiedEntities.end())
2116 7126 : m_ModifiedEntities.push_back(ent);
2117 8965 : }
2118 :
2119 115979 : void UpdateVisibility(entity_id_t ent, player_id_t player)
2120 : {
2121 115979 : EntityMap<EntityData>::iterator itEnts = m_EntityData.find(ent);
2122 115979 : if (itEnts == m_EntityData.end())
2123 110553 : return;
2124 :
2125 115499 : LosVisibility oldVis = GetPlayerVisibility(itEnts->second.visibilities, player);
2126 115499 : LosVisibility newVis = ComputeLosVisibility(itEnts->first, player);
2127 :
2128 115499 : if (oldVis == newVis)
2129 : return;
2130 :
2131 5426 : itEnts->second.visibilities = (itEnts->second.visibilities & ~(0x3 << 2 * (player - 1))) |
2132 5426 : (static_cast<std::uint8_t>(newVis) << 2 * (player - 1));
2133 :
2134 5426 : CMessageVisibilityChanged msg(player, ent, static_cast<int>(oldVis), static_cast<int>(newVis));
2135 5426 : GetSimContext().GetComponentManager().PostMessage(ent, msg);
2136 5426 : }
2137 :
2138 6988 : void UpdateVisibility(entity_id_t ent)
2139 : {
2140 118796 : for (player_id_t player = 1; player < MAX_LOS_PLAYER_ID + 1; ++player)
2141 111808 : UpdateVisibility(ent, player);
2142 : }
2143 :
2144 4 : void SetLosRevealWholeMap(player_id_t player, bool enabled) override
2145 : {
2146 4 : m_LosRevealWholeMap.at(player) = enabled;
2147 :
2148 : // On next update, update the visibility of every entity in the world
2149 4 : m_GlobalVisibilityUpdate = true;
2150 4 : }
2151 :
2152 6 : void SetLosRevealWholeMapForAll(bool enabled) override {
2153 6 : m_LosRevealWholeMapForAll = enabled;
2154 :
2155 : // On next update, update the visibility of every entity in the world
2156 6 : m_GlobalVisibilityUpdate = true;
2157 6 : }
2158 :
2159 116069 : bool GetLosRevealWholeMap(player_id_t player) const override
2160 : {
2161 : // Always reveal the whole map to observers.
2162 116069 : if (m_LosRevealWholeMapForAll || player == -1)
2163 : return true;
2164 :
2165 28268 : ENSURE(player >= 0 && player < MAX_LOS_PLAYER_ID+1);
2166 28268 : if (m_LosRevealWholeMap[player])
2167 : return true;
2168 :
2169 : return false;
2170 : }
2171 :
2172 3 : bool GetLosRevealWholeMapForAll() const override {
2173 3 : return m_LosRevealWholeMapForAll;
2174 : }
2175 :
2176 3 : void SetLosCircular(bool enabled) override
2177 : {
2178 3 : m_LosCircular = enabled;
2179 :
2180 3 : ResetDerivedData();
2181 3 : }
2182 :
2183 3 : bool GetLosCircular() const override
2184 : {
2185 3 : return m_LosCircular;
2186 : }
2187 :
2188 18 : void SetSharedLos(player_id_t player, const std::vector<player_id_t>& players) override
2189 : {
2190 36 : m_SharedLosMasks[player] = CalcSharedLosMask(players);
2191 :
2192 : // Units belonging to any of 'players' can now trigger visibility updates for 'player'.
2193 : // If shared LOS partners have been removed, we disable visibility updates from them
2194 : // in order to improve performance. That also allows us to properly determine whether
2195 : // 'player' needs a global visibility update for this turn.
2196 18 : bool modified = false;
2197 :
2198 306 : for (player_id_t p = 1; p < MAX_LOS_PLAYER_ID+1; ++p)
2199 : {
2200 288 : bool inList = std::find(players.begin(), players.end(), p) != players.end();
2201 :
2202 432 : if (SetPlayerSharedDirtyVisibilityBit(m_SharedDirtyVisibilityMasks[p], player, inList))
2203 288 : modified = true;
2204 : }
2205 :
2206 18 : if (modified && (size_t)player <= m_GlobalPlayerVisibilityUpdate.size())
2207 6 : m_GlobalPlayerVisibilityUpdate[player-1] = 1;
2208 18 : }
2209 :
2210 28262 : std::uint32_t GetSharedLosMask(player_id_t player) const override
2211 : {
2212 28262 : return m_SharedLosMasks[player];
2213 : }
2214 :
2215 0 : void ExploreMap(player_id_t p) override
2216 : {
2217 0 : for (std::int32_t j = 0; j < m_LosVerticesPerSide; ++j)
2218 0 : for (std::int32_t i = 0; i < m_LosVerticesPerSide; ++i)
2219 : {
2220 0 : if (LosIsOffWorld(i,j))
2221 0 : continue;
2222 0 : std::uint32_t &explored = m_ExploredVertices.at(p);
2223 0 : explored += !(m_LosState.get(i, j) &
2224 0 : (static_cast<std::uint32_t>(LosState::EXPLORED) << (2*(p-1))));
2225 0 : m_LosState.get(i, j) |=
2226 0 : (static_cast<std::uint32_t>(LosState::EXPLORED) << (2*(p-1)));
2227 : }
2228 :
2229 0 : SeeExploredEntities(p);
2230 0 : }
2231 :
2232 3 : void ExploreTerritories() override
2233 : {
2234 3 : PROFILE3("ExploreTerritories");
2235 :
2236 3 : CmpPtr<ICmpTerritoryManager> cmpTerritoryManager(GetSystemEntity());
2237 3 : const Grid<std::uint8_t>& grid = cmpTerritoryManager->GetTerritoryGrid();
2238 :
2239 : // Territory data is stored per territory-tile (typically a multiple of terrain-tiles).
2240 : // LOS data is stored per los vertex (in reality tiles too, but it's the center that matters).
2241 : // This scales from LOS coordinates to Territory coordinates.
2242 111747 : auto scale = [](std::int32_t coord, std::int32_t max) -> std::int32_t {
2243 111747 : return std::min(max, (coord * LOS_TILE_SIZE + LOS_TILE_SIZE / 2) / (ICmpTerritoryManager::NAVCELLS_PER_TERRITORY_TILE * Pathfinding::NAVCELL_SIZE_INT));
2244 : };
2245 :
2246 : // For each territory-tile, if it is owned by a valid player then update the LOS
2247 : // for every vertex inside/around that tile, to mark them as explored.
2248 582 : for (std::int32_t j = 0; j < m_LosVerticesPerSide; ++j)
2249 112326 : for (std::int32_t i = 0; i < m_LosVerticesPerSide; ++i)
2250 : {
2251 : // TODO: This fetches data redundantly if the los grid is smaller than the territory grid
2252 : // (but it's unlikely to matter much).
2253 331767 : std::uint8_t p = grid.get(scale(i, grid.width() - 1), scale(j, grid.height() - 1)) & ICmpTerritoryManager::TERRITORY_PLAYER_MASK;
2254 111747 : if (p > 0 && p <= MAX_LOS_PLAYER_ID)
2255 : {
2256 0 : std::uint32_t& explored = m_ExploredVertices.at(p);
2257 :
2258 0 : if (LosIsOffWorld(i, j))
2259 0 : continue;
2260 :
2261 0 : std::uint32_t& losState = m_LosState.get(i, j);
2262 0 : if (!(losState &
2263 0 : (static_cast<std::uint32_t>(LosState::EXPLORED) << (2*(p-1)))))
2264 : {
2265 0 : ++explored;
2266 0 : losState |=
2267 0 : (static_cast<std::uint32_t>(LosState::EXPLORED) << (2*(p-1)));
2268 : }
2269 : }
2270 : }
2271 :
2272 51 : for (player_id_t p = 1; p < MAX_LOS_PLAYER_ID+1; ++p)
2273 48 : SeeExploredEntities(p);
2274 3 : }
2275 :
2276 2 : TileCircle WorldToTileCircle(entity_pos_t worldX, entity_pos_t worldZ, fixed radius)
2277 : {
2278 2 : const std::int32_t centerTileX{(worldX / LOS_TILE_SIZE).ToInt_RoundToNearest()};
2279 2 : const std::int32_t centerTileZ{(worldZ / LOS_TILE_SIZE).ToInt_RoundToNearest()};
2280 2 : const std::int32_t tileRadius{(radius / LOS_TILE_SIZE).ToInt_RoundToInfinity()};
2281 :
2282 2 : return TileCircle{
2283 : .centerX = centerTileX,
2284 : .centerZ = centerTileZ,
2285 : .radius = tileRadius,
2286 2 : .squaredRadius = tileRadius * tileRadius,
2287 6 : .minX = std::max(centerTileX - tileRadius, 0),
2288 6 : .maxX = std::min(centerTileX + tileRadius, m_LosVerticesPerSide - 1),
2289 6 : .minZ = std::max(centerTileZ - tileRadius, 0),
2290 4 : .maxZ = std::min(centerTileZ + tileRadius, m_LosVerticesPerSide - 1)
2291 5 : };
2292 : }
2293 :
2294 4 : void ExploreCircle(player_id_t playerId, entity_pos_t worldX, entity_pos_t worldZ, fixed radius) override
2295 : {
2296 4 : if (playerId <= 0 || playerId > MAX_LOS_PLAYER_ID)
2297 2 : return;
2298 :
2299 2 : const TileCircle circle{WorldToTileCircle(worldX, worldZ, radius)};
2300 2 : const std::uint32_t exploredBitMask{static_cast<std::uint32_t>(LosState::EXPLORED) << (2 * (playerId - 1))};
2301 2 : std::uint32_t& exploredCount = m_ExploredVertices.at(playerId);
2302 :
2303 2 : ForEachTileInCircle(circle,
2304 2 : [&](std::int32_t tileX, std::int32_t tileZ)
2305 : {
2306 4754 : if (LosIsOffWorld(tileX, tileZ))
2307 : return;
2308 :
2309 4010 : std::uint32_t& losState = m_LosState.get(tileX, tileZ);
2310 4010 : if (losState & exploredBitMask)
2311 : return;
2312 :
2313 3481 : losState |= exploredBitMask;
2314 3481 : ++exploredCount;
2315 3481 : MarkVisibilityDirtyAroundTile(playerId, tileX, tileZ);
2316 : }
2317 : );
2318 : }
2319 :
2320 : /**
2321 : * Force any entity in explored territory to appear for player p.
2322 : * This is useful for miraging entities inside the territory borders at the beginning of a game,
2323 : * or if the "Explore Map" option has been set.
2324 : */
2325 48 : void SeeExploredEntities(player_id_t p) const
2326 : {
2327 : // Warning: Code related to fogging (like ForceMiraging) shouldn't be
2328 : // invoked while iterating through m_EntityData.
2329 : // Otherwise, by deleting mirage entities and so on, that code will
2330 : // change the indexes in the map, leading to segfaults.
2331 : // So we just remember what entities to mirage and do that later.
2332 48 : std::vector<entity_id_t> miragableEntities;
2333 :
2334 96 : for (EntityMap<EntityData>::const_iterator it = m_EntityData.begin(); it != m_EntityData.end(); ++it)
2335 : {
2336 0 : CmpPtr<ICmpPosition> cmpPosition(GetSimContext(), it->first);
2337 0 : if (!cmpPosition || !cmpPosition->IsInWorld())
2338 0 : continue;
2339 :
2340 0 : CFixedVector2D pos = cmpPosition->GetPosition2D();
2341 0 : int i = (pos.X / LOS_TILE_SIZE).ToInt_RoundToNearest();
2342 0 : int j = (pos.Y / LOS_TILE_SIZE).ToInt_RoundToNearest();
2343 :
2344 0 : CLosQuerier los(GetSharedLosMask(p), m_LosState, m_LosVerticesPerSide);
2345 0 : if (!los.IsExplored(i,j) || los.IsVisible(i,j))
2346 0 : continue;
2347 :
2348 0 : CmpPtr<ICmpFogging> cmpFogging(GetSimContext(), it->first);
2349 0 : if (cmpFogging)
2350 0 : miragableEntities.push_back(it->first);
2351 : }
2352 :
2353 48 : for (std::vector<entity_id_t>::iterator it = miragableEntities.begin(); it != miragableEntities.end(); ++it)
2354 : {
2355 0 : CmpPtr<ICmpFogging> cmpFogging(GetSimContext(), *it);
2356 0 : ENSURE(cmpFogging && "Impossible to retrieve Fogging component, previously achieved");
2357 0 : cmpFogging->ForceMiraging(p);
2358 : }
2359 48 : }
2360 :
2361 0 : void RevealShore(player_id_t p, bool enable) override
2362 : {
2363 0 : if (p <= 0 || p > MAX_LOS_PLAYER_ID)
2364 0 : return;
2365 :
2366 : // Maximum distance to the shore
2367 0 : const std::uint16_t maxdist = 10;
2368 :
2369 0 : CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
2370 0 : const Grid<std::uint16_t>& shoreGrid = cmpPathfinder->ComputeShoreGrid(true);
2371 0 : ENSURE(shoreGrid.m_W == m_LosVerticesPerSide-1 && shoreGrid.m_H == m_LosVerticesPerSide-1);
2372 :
2373 0 : Grid<std::uint16_t>& counts = m_LosPlayerCounts.at(p);
2374 0 : ENSURE(!counts.blank());
2375 :
2376 0 : for (std::uint16_t j = 0; j < shoreGrid.m_H; ++j)
2377 0 : for (std::uint16_t i = 0; i < shoreGrid.m_W; ++i)
2378 : {
2379 0 : std::uint16_t shoredist = shoreGrid.get(i, j);
2380 0 : if (shoredist > maxdist)
2381 0 : continue;
2382 :
2383 : // Maybe we could be more clever and don't add dummy strips of one tile
2384 0 : if (enable)
2385 0 : LosAddStripHelper(p, i, i, j, counts);
2386 : else
2387 0 : LosRemoveStripHelper(p, i, i, j, counts);
2388 : }
2389 0 : }
2390 :
2391 : /**
2392 : * Returns whether the given vertex is outside the normal bounds of the world
2393 : * (i.e. outside the range of a circular map)
2394 : */
2395 36542147 : inline bool LosIsOffWorld(ssize_t i, ssize_t j) const
2396 : {
2397 36542147 : if (m_LosCircular)
2398 : {
2399 : // With a circular map, vertex is off-world if hypot(i - size/2, j - size/2) >= size/2:
2400 :
2401 0 : ssize_t dist2 = (i - m_LosVerticesPerSide/2)*(i - m_LosVerticesPerSide/2)
2402 0 : + (j - m_LosVerticesPerSide/2)*(j - m_LosVerticesPerSide/2);
2403 :
2404 0 : ssize_t r = m_LosVerticesPerSide / 2 - MAP_EDGE_TILES + 1;
2405 : // subtract a bit from the radius to ensure nice
2406 : // SoD blurring around the edges of the map
2407 :
2408 0 : return (dist2 >= r*r);
2409 : }
2410 : else
2411 : {
2412 : // With a square map, the outermost edge of the map should be off-world,
2413 : // so the SoD texture blends out nicely
2414 71453553 : return i < MAP_EDGE_TILES || j < MAP_EDGE_TILES ||
2415 36542147 : i >= m_LosVerticesPerSide - MAP_EDGE_TILES ||
2416 36542147 : j >= m_LosVerticesPerSide - MAP_EDGE_TILES;
2417 : }
2418 : }
2419 :
2420 : /**
2421 : * Update the LOS state of tiles within a given horizontal strip (i0,j) to (i1,j) (inclusive).
2422 : */
2423 332426 : inline void LosAddStripHelper(std::uint8_t owner, std::int32_t i0, std::int32_t i1, std::int32_t j,
2424 : Grid<std::uint16_t>& counts)
2425 : {
2426 332426 : if (i1 < i0)
2427 : return;
2428 :
2429 173707 : std::uint32_t &explored = m_ExploredVertices.at(owner);
2430 2038666 : for (std::int32_t i = i0; i <= i1; ++i)
2431 : {
2432 : // Increasing from zero to non-zero - move from unexplored/explored to visible+explored
2433 1864959 : if (counts.get(i, j) == 0)
2434 : {
2435 1583237 : if (!LosIsOffWorld(i, j))
2436 : {
2437 1524239 : explored += !(m_LosState.get(i, j) &
2438 1524239 : (static_cast<std::uint32_t>(LosState::EXPLORED) << (2*(owner-1))));
2439 1524239 : m_LosState.get(i, j) |= (((int)LosState::VISIBLE |
2440 1524239 : static_cast<std::uint32_t>(LosState::EXPLORED)) << (2*(owner-1)));
2441 : }
2442 :
2443 1583237 : MarkVisibilityDirtyAroundTile(owner, i, j);
2444 : }
2445 :
2446 1864959 : ENSURE(counts.get(i, j) < std::numeric_limits<std::uint16_t>::max());
2447 1864959 : counts.get(i, j) = static_cast<std::uint16_t>(counts.get(i, j) + 1); // ignore overflow; the player should never have 64K units
2448 : }
2449 : }
2450 :
2451 : /**
2452 : * Update the LOS state of tiles within a given horizontal strip (i0,j) to (i1,j) (inclusive).
2453 : */
2454 294929 : inline void LosRemoveStripHelper(std::uint8_t owner, std::int32_t i0, std::int32_t i1, std::int32_t j,
2455 : Grid<std::uint16_t>& counts)
2456 : {
2457 294929 : if (i1 < i0)
2458 : return;
2459 :
2460 1053219 : for (std::int32_t i = i0; i <= i1; ++i)
2461 : {
2462 916836 : ASSERT(counts.get(i, j) > 0);
2463 916836 : counts.get(i, j) = static_cast<std::uint16_t>(counts.get(i, j) - 1);
2464 :
2465 : // Decreasing from non-zero to zero - move from visible+explored to explored
2466 916836 : if (counts.get(i, j) == 0)
2467 : {
2468 : // (If LosIsOffWorld then this is a no-op, so don't bother doing the check)
2469 767820 : m_LosState.get(i, j) &= ~((int)LosState::VISIBLE << (2*(owner-1)));
2470 :
2471 767820 : MarkVisibilityDirtyAroundTile(owner, i, j);
2472 : }
2473 : }
2474 : }
2475 :
2476 2354538 : inline void MarkVisibilityDirtyAroundTile(std::uint8_t owner, std::int32_t i, std::int32_t j)
2477 : {
2478 : // If we're still in the deserializing process, we must not modify m_DirtyVisibility
2479 2354538 : if (m_Deserializing)
2480 2354538 : return;
2481 :
2482 : // Mark the LoS regions around the updated vertex
2483 : // 1: left-up, 2: right-up, 3: left-down, 4: right-down
2484 1576813 : LosRegion n1 = LosVertexToLosRegionsHelper(i-1, j-1);
2485 1576813 : LosRegion n2 = LosVertexToLosRegionsHelper(i-1, j);
2486 1576813 : LosRegion n3 = LosVertexToLosRegionsHelper(i, j-1);
2487 1576813 : LosRegion n4 = LosVertexToLosRegionsHelper(i, j);
2488 :
2489 1576813 : std::uint16_t sharedDirtyVisibilityMask = m_SharedDirtyVisibilityMasks[owner];
2490 :
2491 1576813 : if (j > 0 && i > 0)
2492 1576813 : m_DirtyVisibility[n1] |= sharedDirtyVisibilityMask;
2493 1576813 : if (n2 != n1 && j > 0 && i < m_LosVerticesPerSide)
2494 190721 : m_DirtyVisibility[n2] |= sharedDirtyVisibilityMask;
2495 1576813 : if (n3 != n1 && j < m_LosVerticesPerSide && i > 0)
2496 191278 : m_DirtyVisibility[n3] |= sharedDirtyVisibilityMask;
2497 1744355 : if (n4 != n1 && j < m_LosVerticesPerSide && i < m_LosVerticesPerSide)
2498 358820 : m_DirtyVisibility[n4] |= sharedDirtyVisibilityMask;
2499 : }
2500 :
2501 : /**
2502 : * Update the LOS state of tiles within a given circular range,
2503 : * either adding or removing visibility depending on the template parameter.
2504 : * Assumes owner is in the valid range.
2505 : */
2506 : template<bool adding>
2507 3179 : void LosUpdateHelper(std::uint8_t owner, entity_pos_t visionRange, CFixedVector2D pos)
2508 : {
2509 3179 : if (m_LosVerticesPerSide == 0) // do nothing if not initialised yet
2510 0 : return;
2511 :
2512 3179 : PROFILE("LosUpdateHelper");
2513 :
2514 3179 : Grid<std::uint16_t>& counts = m_LosPlayerCounts.at(owner);
2515 :
2516 : // Lazy initialisation of counts:
2517 3179 : if (counts.blank())
2518 1048 : counts.resize(m_LosVerticesPerSide, m_LosVerticesPerSide);
2519 :
2520 : // Compute the circular region as a series of strips.
2521 : // Rather than quantise pos to vertexes, we do more precise sub-tile computations
2522 : // to get smoother behaviour as a unit moves rather than jumping a whole tile
2523 : // at once.
2524 : // To avoid the cost of sqrt when computing the outline of the circle,
2525 : // we loop from the bottom to the top and estimate the width of the current
2526 : // strip based on the previous strip, then adjust each end of the strip
2527 : // inwards or outwards until it's the widest that still falls within the circle.
2528 :
2529 : // Compute top/bottom coordinates, and clamp to exclude the 1-tile border around the map
2530 : // (so that we never render the sharp edge of the map)
2531 3179 : std::int32_t j0 = ((pos.Y - visionRange)/LOS_TILE_SIZE).ToInt_RoundToInfinity();
2532 3179 : std::int32_t j1 = ((pos.Y + visionRange)/LOS_TILE_SIZE).ToInt_RoundToNegInfinity();
2533 3179 : std::int32_t j0clamp = std::max(j0, 1);
2534 3590 : std::int32_t j1clamp = std::min(j1, m_LosVerticesPerSide-2);
2535 :
2536 : // Translate world coordinates into fractional tile-space coordinates
2537 3179 : entity_pos_t x = pos.X / LOS_TILE_SIZE;
2538 3179 : entity_pos_t y = pos.Y / LOS_TILE_SIZE;
2539 3179 : entity_pos_t r = visionRange / LOS_TILE_SIZE;
2540 3179 : entity_pos_t r2 = r.Square();
2541 :
2542 : // Compute the integers on either side of x
2543 3179 : std::int32_t xfloor = (x - entity_pos_t::Epsilon()).ToInt_RoundToNegInfinity();
2544 3179 : std::int32_t xceil = (x + entity_pos_t::Epsilon()).ToInt_RoundToInfinity();
2545 :
2546 : // Initialise the strip (i0, i1) to a rough guess
2547 3179 : std::int32_t i0 = xfloor;
2548 3179 : std::int32_t i1 = xceil;
2549 :
2550 101430 : for (std::int32_t j = j0clamp; j <= j1clamp; ++j)
2551 : {
2552 : // Adjust i0 and i1 to be the outermost values that don't exceed
2553 : // the circle's radius (i.e. require dy^2 + dx^2 <= r^2).
2554 : // When moving the points inwards, clamp them to xceil+1 or xfloor-1
2555 : // so they don't accidentally shoot off in the wrong direction forever.
2556 :
2557 98251 : entity_pos_t dy = entity_pos_t::FromInt(j) - y;
2558 98251 : entity_pos_t dy2 = dy.Square();
2559 147956 : while (dy2 + (entity_pos_t::FromInt(i0-1) - x).Square() <= r2)
2560 49705 : --i0;
2561 135419 : while (i0 < xceil && dy2 + (entity_pos_t::FromInt(i0) - x).Square() > r2)
2562 37168 : ++i0;
2563 147822 : while (dy2 + (entity_pos_t::FromInt(i1+1) - x).Square() <= r2)
2564 49571 : ++i1;
2565 135225 : while (i1 > xfloor && dy2 + (entity_pos_t::FromInt(i1) - x).Square() > r2)
2566 36974 : --i1;
2567 :
2568 : #if DEBUG_RANGE_MANAGER_BOUNDS
2569 : if (i0 <= i1)
2570 : {
2571 : ENSURE(dy2 + (entity_pos_t::FromInt(i0) - x).Square() <= r2);
2572 : ENSURE(dy2 + (entity_pos_t::FromInt(i1) - x).Square() <= r2);
2573 : }
2574 : ENSURE(dy2 + (entity_pos_t::FromInt(i0 - 1) - x).Square() > r2);
2575 : ENSURE(dy2 + (entity_pos_t::FromInt(i1 + 1) - x).Square() > r2);
2576 : #endif
2577 :
2578 : // Clamp the strip to exclude the 1-tile border,
2579 : // then add or remove the strip as requested
2580 98251 : std::int32_t i0clamp = std::max(i0, 1);
2581 98251 : std::int32_t i1clamp = std::min(i1, m_LosVerticesPerSide-2);
2582 : if (adding)
2583 67812 : LosAddStripHelper(owner, i0clamp, i1clamp, j, counts);
2584 : else
2585 30439 : LosRemoveStripHelper(owner, i0clamp, i1clamp, j, counts);
2586 : }
2587 3179 : }
2588 :
2589 : /**
2590 : * Update the LOS state of tiles within a given circular range,
2591 : * by removing visibility around the 'from' position
2592 : * and then adding visibility around the 'to' position.
2593 : */
2594 7519 : void LosUpdateHelperIncremental(std::uint8_t owner, entity_pos_t visionRange, CFixedVector2D from, CFixedVector2D to)
2595 : {
2596 7519 : if (m_LosVerticesPerSide == 0) // do nothing if not initialised yet
2597 0 : return;
2598 :
2599 7519 : PROFILE("LosUpdateHelperIncremental");
2600 :
2601 7519 : Grid<std::uint16_t>& counts = m_LosPlayerCounts.at(owner);
2602 :
2603 : // Lazy initialisation of counts:
2604 7519 : if (counts.blank())
2605 0 : counts.resize(m_LosVerticesPerSide, m_LosVerticesPerSide);
2606 :
2607 : // See comments in LosUpdateHelper.
2608 : // This does exactly the same, except computing the strips for
2609 : // both circles simultaneously.
2610 : // (The idea is that the circles will be heavily overlapping,
2611 : // so we can compute the difference between the removed/added strips
2612 : // and only have to touch tiles that have a net change.)
2613 :
2614 7519 : std::int32_t j0_from = ((from.Y - visionRange)/LOS_TILE_SIZE).ToInt_RoundToInfinity();
2615 7519 : std::int32_t j1_from = ((from.Y + visionRange)/LOS_TILE_SIZE).ToInt_RoundToNegInfinity();
2616 7519 : std::int32_t j0_to = ((to.Y - visionRange)/LOS_TILE_SIZE).ToInt_RoundToInfinity();
2617 7519 : std::int32_t j1_to = ((to.Y + visionRange)/LOS_TILE_SIZE).ToInt_RoundToNegInfinity();
2618 7548 : std::int32_t j0clamp = std::max(std::min(j0_from, j0_to), 1);
2619 11440 : std::int32_t j1clamp = std::min(std::max(j1_from, j1_to), m_LosVerticesPerSide-2);
2620 :
2621 7519 : entity_pos_t x_from = from.X / LOS_TILE_SIZE;
2622 7519 : entity_pos_t y_from = from.Y / LOS_TILE_SIZE;
2623 7519 : entity_pos_t x_to = to.X / LOS_TILE_SIZE;
2624 7519 : entity_pos_t y_to = to.Y / LOS_TILE_SIZE;
2625 7519 : entity_pos_t r = visionRange / LOS_TILE_SIZE;
2626 7519 : entity_pos_t r2 = r.Square();
2627 :
2628 7519 : std::int32_t xfloor_from = (x_from - entity_pos_t::Epsilon()).ToInt_RoundToNegInfinity();
2629 7519 : std::int32_t xceil_from = (x_from + entity_pos_t::Epsilon()).ToInt_RoundToInfinity();
2630 7519 : std::int32_t xfloor_to = (x_to - entity_pos_t::Epsilon()).ToInt_RoundToNegInfinity();
2631 7519 : std::int32_t xceil_to = (x_to + entity_pos_t::Epsilon()).ToInt_RoundToInfinity();
2632 :
2633 7519 : std::int32_t i0_from = xfloor_from;
2634 7519 : std::int32_t i1_from = xceil_from;
2635 7519 : std::int32_t i0_to = xfloor_to;
2636 7519 : std::int32_t i1_to = xceil_to;
2637 :
2638 295379 : for (std::int32_t j = j0clamp; j <= j1clamp; ++j)
2639 : {
2640 287860 : entity_pos_t dy_from = entity_pos_t::FromInt(j) - y_from;
2641 287860 : entity_pos_t dy2_from = dy_from.Square();
2642 422239 : while (dy2_from + (entity_pos_t::FromInt(i0_from-1) - x_from).Square() <= r2)
2643 134379 : --i0_from;
2644 418752 : while (i0_from < xceil_from && dy2_from + (entity_pos_t::FromInt(i0_from) - x_from).Square() > r2)
2645 130892 : ++i0_from;
2646 422144 : while (dy2_from + (entity_pos_t::FromInt(i1_from+1) - x_from).Square() <= r2)
2647 134284 : ++i1_from;
2648 419122 : while (i1_from > xfloor_from && dy2_from + (entity_pos_t::FromInt(i1_from) - x_from).Square() > r2)
2649 131262 : --i1_from;
2650 :
2651 287860 : entity_pos_t dy_to = entity_pos_t::FromInt(j) - y_to;
2652 287860 : entity_pos_t dy2_to = dy_to.Square();
2653 426145 : while (dy2_to + (entity_pos_t::FromInt(i0_to-1) - x_to).Square() <= r2)
2654 138285 : --i0_to;
2655 402918 : while (i0_to < xceil_to && dy2_to + (entity_pos_t::FromInt(i0_to) - x_to).Square() > r2)
2656 115058 : ++i0_to;
2657 426035 : while (dy2_to + (entity_pos_t::FromInt(i1_to+1) - x_to).Square() <= r2)
2658 138175 : ++i1_to;
2659 403852 : while (i1_to > xfloor_to && dy2_to + (entity_pos_t::FromInt(i1_to) - x_to).Square() > r2)
2660 115992 : --i1_to;
2661 :
2662 : #if DEBUG_RANGE_MANAGER_BOUNDS
2663 : if (i0_from <= i1_from)
2664 : {
2665 : ENSURE(dy2_from + (entity_pos_t::FromInt(i0_from) - x_from).Square() <= r2);
2666 : ENSURE(dy2_from + (entity_pos_t::FromInt(i1_from) - x_from).Square() <= r2);
2667 : }
2668 : ENSURE(dy2_from + (entity_pos_t::FromInt(i0_from - 1) - x_from).Square() > r2);
2669 : ENSURE(dy2_from + (entity_pos_t::FromInt(i1_from + 1) - x_from).Square() > r2);
2670 : if (i0_to <= i1_to)
2671 : {
2672 : ENSURE(dy2_to + (entity_pos_t::FromInt(i0_to) - x_to).Square() <= r2);
2673 : ENSURE(dy2_to + (entity_pos_t::FromInt(i1_to) - x_to).Square() <= r2);
2674 : }
2675 : ENSURE(dy2_to + (entity_pos_t::FromInt(i0_to - 1) - x_to).Square() > r2);
2676 : ENSURE(dy2_to + (entity_pos_t::FromInt(i1_to + 1) - x_to).Square() > r2);
2677 : #endif
2678 :
2679 : // Check whether this strip moved at all
2680 287860 : if (!(i0_to == i0_from && i1_to == i1_from))
2681 : {
2682 138906 : std::int32_t i0clamp_from = std::max(i0_from, 1);
2683 138906 : std::int32_t i1clamp_from = std::min(i1_from, m_LosVerticesPerSide-2);
2684 138906 : std::int32_t i0clamp_to = std::max(i0_to, 1);
2685 138906 : std::int32_t i1clamp_to = std::min(i1_to, m_LosVerticesPerSide-2);
2686 :
2687 : // Check whether one strip is negative width,
2688 : // and we can just add/remove the entire other strip
2689 138906 : if (i1clamp_from < i0clamp_from)
2690 : {
2691 4482 : LosAddStripHelper(owner, i0clamp_to, i1clamp_to, j, counts);
2692 : }
2693 134424 : else if (i1clamp_to < i0clamp_to)
2694 : {
2695 4358 : LosRemoveStripHelper(owner, i0clamp_from, i1clamp_from, j, counts);
2696 : }
2697 : else
2698 : {
2699 : // There are four possible regions of overlap between the two strips
2700 : // (remove before add, remove after add, add before remove, add after remove).
2701 : // Process each of the regions as its own strip.
2702 : // (If this produces negative-width strips then they'll just get ignored
2703 : // which is fine.)
2704 : // (If the strips don't actually overlap (which is very rare with normal unit
2705 : // movement speeds), the region between them will be both added and removed,
2706 : // so we have to do the add first to avoid overflowing to -1 and triggering
2707 : // assertion failures.)
2708 130066 : LosAddStripHelper(owner, i0clamp_to, i0clamp_from-1, j, counts);
2709 130066 : LosAddStripHelper(owner, i1clamp_from+1, i1clamp_to, j, counts);
2710 130066 : LosRemoveStripHelper(owner, i0clamp_from, i0clamp_to-1, j, counts);
2711 130066 : LosRemoveStripHelper(owner, i1clamp_to+1, i1clamp_from, j, counts);
2712 : }
2713 : }
2714 : }
2715 7519 : }
2716 :
2717 1270 : void LosAdd(player_id_t owner, entity_pos_t visionRange, CFixedVector2D pos)
2718 : {
2719 1270 : if (visionRange.IsZero() || owner <= 0 || owner > MAX_LOS_PLAYER_ID)
2720 : return;
2721 :
2722 1218 : LosUpdateHelper<true>(static_cast<std::uint8_t>(owner), visionRange, pos);
2723 : }
2724 :
2725 0 : void SharingLosAdd(std::uint16_t visionSharing, entity_pos_t visionRange, CFixedVector2D pos)
2726 : {
2727 0 : if (visionRange.IsZero())
2728 : return;
2729 :
2730 0 : for (player_id_t i = 1; i < MAX_LOS_PLAYER_ID+1; ++i)
2731 0 : if (HasVisionSharing(visionSharing, i))
2732 0 : LosAdd(i, visionRange, pos);
2733 : }
2734 :
2735 44 : void LosRemove(player_id_t owner, entity_pos_t visionRange, CFixedVector2D pos)
2736 : {
2737 44 : if (visionRange.IsZero() || owner <= 0 || owner > MAX_LOS_PLAYER_ID)
2738 : return;
2739 :
2740 31 : LosUpdateHelper<false>(static_cast<std::uint8_t>(owner), visionRange, pos);
2741 : }
2742 :
2743 0 : void SharingLosRemove(std::uint16_t visionSharing, entity_pos_t visionRange, CFixedVector2D pos)
2744 : {
2745 0 : if (visionRange.IsZero())
2746 : return;
2747 :
2748 0 : for (player_id_t i = 1; i < MAX_LOS_PLAYER_ID+1; ++i)
2749 0 : if (HasVisionSharing(visionSharing, i))
2750 0 : LosRemove(i, visionRange, pos);
2751 : }
2752 :
2753 8772 : void LosMove(player_id_t owner, entity_pos_t visionRange, CFixedVector2D from, CFixedVector2D to)
2754 : {
2755 8772 : if (visionRange.IsZero() || owner <= 0 || owner > MAX_LOS_PLAYER_ID)
2756 : return;
2757 :
2758 8484 : if ((from - to).CompareLength(visionRange) > 0)
2759 : {
2760 : // If it's a very large move, then simply remove and add to the new position
2761 965 : LosUpdateHelper<false>(static_cast<std::uint8_t>(owner), visionRange, from);
2762 965 : LosUpdateHelper<true>(static_cast<std::uint8_t>(owner), visionRange, to);
2763 : }
2764 : else
2765 : // Otherwise use the version optimised for mostly-overlapping circles
2766 7519 : LosUpdateHelperIncremental(static_cast<std::uint8_t>(owner), visionRange, from, to);
2767 : }
2768 :
2769 0 : void SharingLosMove(std::uint16_t visionSharing, entity_pos_t visionRange, CFixedVector2D from, CFixedVector2D to)
2770 : {
2771 0 : if (visionRange.IsZero())
2772 : return;
2773 :
2774 0 : for (player_id_t i = 1; i < MAX_LOS_PLAYER_ID+1; ++i)
2775 0 : if (HasVisionSharing(visionSharing, i))
2776 0 : LosMove(i, visionRange, from, to);
2777 : }
2778 :
2779 33 : std::uint8_t GetPercentMapExplored(player_id_t player) const override
2780 : {
2781 33 : return m_ExploredVertices.at(static_cast<std::uint8_t>(player)) * 100 / m_TotalInworldVertices;
2782 : }
2783 :
2784 0 : std::uint8_t GetUnionPercentMapExplored(const std::vector<player_id_t>& players) const override
2785 : {
2786 0 : std::uint32_t exploredVertices = 0;
2787 0 : std::vector<player_id_t>::const_iterator playerIt;
2788 :
2789 0 : for (std::int32_t j = 0; j < m_LosVerticesPerSide; j++)
2790 0 : for (std::int32_t i = 0; i < m_LosVerticesPerSide; i++)
2791 : {
2792 0 : if (LosIsOffWorld(i, j))
2793 0 : continue;
2794 :
2795 0 : for (playerIt = players.begin(); playerIt != players.end(); ++playerIt)
2796 0 : if (m_LosState.get(i, j) & (static_cast<std::uint32_t>(LosState::EXPLORED) <<
2797 0 : (2*((*playerIt)-1))))
2798 : {
2799 0 : exploredVertices += 1;
2800 0 : break;
2801 : }
2802 : }
2803 :
2804 0 : return exploredVertices * 100 / m_TotalInworldVertices;
2805 : }
2806 : };
2807 :
2808 274 : REGISTER_COMPONENT_TYPE(RangeManager)
|