Line data Source code
1 : /* Copyright (C) 2025 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 "ICmpUnitRenderer.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/ModelAbstract.h"
24 : #include "graphics/Overlay.h"
25 : #include "graphics/Unit.h"
26 : #include "lib/debug.h"
27 : #include "maths/BoundingBoxAligned.h"
28 : #include "maths/BoundingBoxOriented.h"
29 : #include "maths/BoundingSphere.h"
30 : #include "maths/Frustum.h"
31 : #include "maths/Matrix3D.h"
32 : #include "maths/Vector3D.h"
33 : #include "ps/Profile.h"
34 : #include "renderer/RenderingOptions.h"
35 : #include "renderer/Scene.h"
36 : #include "simulation2/MessageTypes.h"
37 : #include "simulation2/components/ICmpPosition.h"
38 : #include "simulation2/components/ICmpRangeManager.h"
39 : #include "simulation2/components/ICmpSelectable.h"
40 : #include "simulation2/components/ICmpVisibility.h"
41 : #include "simulation2/components/ICmpVisual.h"
42 : #include "simulation2/system/Component.h"
43 : #include "simulation2/system/Entity.h"
44 : #include "simulation2/system/Message.h"
45 : #include "tools/atlas/GameInterface/GameLoop.h"
46 :
47 : #include <cstddef>
48 : #include <string>
49 : #include <utility>
50 : #include <vector>
51 :
52 : /**
53 : * Efficiently(ish) renders all the units in the world.
54 : *
55 : * The class maintains a list of all units that currently exist, and the data
56 : * needed for frustum-culling them. To minimise the amount of work done per
57 : * frame (despite a unit's interpolated position changing every frame), the
58 : * culling data is only updated once per turn: we store the position at the
59 : * start of the turn, and the position at the end of the turn, and assume the
60 : * unit might be anywhere between those two points (linearly).
61 : *
62 : * (Note this is a slightly invalid assumption: units don't always move linearly,
63 : * since their interpolated position depends on terrain and water. But over a
64 : * single turn it's probably going to be a good enough approximation, and will
65 : * only break for units that both start and end the turn off-screen.)
66 : *
67 : * We want to ignore rotation entirely, since it's a complex function of
68 : * interpolated position and terrain. So we store a bounding sphere, which
69 : * is rotation-independent, instead of a bounding box.
70 : */
71 7 : class CCmpUnitRenderer final : public ICmpUnitRenderer
72 : {
73 : public:
74 0 : struct SUnit
75 : {
76 : CEntityHandle entity;
77 :
78 : CUnit* actor;
79 :
80 : int flags;
81 :
82 : /**
83 : * m_FrameNumber from when the model's transform was last updated.
84 : * This is used to avoid recomputing it multiple times per frame
85 : * if a model is visible in multiple cull groups.
86 : */
87 : int lastTransformFrame;
88 :
89 : /**
90 : * Worst-case bounding shape, relative to position. Needs to account
91 : * for all possible animations, orientations, etc.
92 : */
93 : CBoundingSphere boundsApprox;
94 :
95 : /**
96 : * Cached LOS visibility status.
97 : */
98 : LosVisibility visibility;
99 : bool visibilityDirty;
100 :
101 : /**
102 : * Whether the unit has a valid position. If false, pos0 and pos1
103 : * are meaningless.
104 : */
105 : bool inWorld;
106 :
107 : /**
108 : * World-space positions to interpolate between.
109 : */
110 : CVector3D pos0;
111 : CVector3D pos1;
112 :
113 : /**
114 : * Bounds encompassing the unit's bounds when it is anywhere between
115 : * pos0 and pos1.
116 : */
117 : CBoundingSphere sweptBounds;
118 :
119 : /**
120 : * For debug overlay.
121 : */
122 : bool culled;
123 : };
124 :
125 : std::vector<SUnit> m_Units;
126 : std::vector<tag_t> m_UnitTagsFree;
127 :
128 : int m_FrameNumber;
129 : float m_FrameOffset;
130 :
131 : bool m_EnableDebugOverlays;
132 : std::vector<SOverlaySphere> m_DebugSpheres;
133 :
134 137 : static void ClassInit(CComponentManager& componentManager)
135 : {
136 137 : componentManager.SubscribeToMessageType(MT_TurnStart);
137 137 : componentManager.SubscribeToMessageType(MT_Interpolate);
138 137 : componentManager.SubscribeToMessageType(MT_RenderSubmit);
139 137 : }
140 :
141 14 : DEFAULT_COMPONENT_ALLOCATOR(UnitRenderer)
142 :
143 137 : static std::string GetSchema()
144 : {
145 274 : return "<a:component type='system'/><empty/>";
146 : }
147 :
148 7 : void Init(const CParamNode&) override
149 : {
150 7 : m_FrameNumber = 0;
151 7 : m_FrameOffset = 0.0f;
152 7 : m_EnableDebugOverlays = false;
153 7 : }
154 :
155 7 : void Deinit() override
156 : {
157 7 : }
158 :
159 18 : void Serialize(ISerializer&) override
160 : {
161 18 : }
162 :
163 0 : void Deserialize(const CParamNode& paramNode, IDeserializer&) override
164 : {
165 0 : Init(paramNode);
166 0 : }
167 :
168 184 : void HandleMessage(const CMessage& msg, bool /*global*/) override
169 : {
170 184 : switch (msg.GetType())
171 : {
172 181 : case MT_TurnStart:
173 181 : {
174 181 : TurnStart();
175 181 : break;
176 : }
177 3 : case MT_Interpolate:
178 3 : {
179 3 : const CMessageInterpolate& msgData = static_cast<const CMessageInterpolate&> (msg);
180 3 : Interpolate(msgData.deltaSimTime, msgData.offset);
181 3 : break;
182 : }
183 0 : case MT_RenderSubmit:
184 0 : {
185 0 : const CMessageRenderSubmit& msgData = static_cast<const CMessageRenderSubmit&> (msg);
186 0 : RenderSubmit(msgData.collector, msgData.frustum, msgData.culling);
187 0 : break;
188 : }
189 : }
190 184 : }
191 :
192 0 : SUnit* LookupUnit(tag_t tag)
193 : {
194 0 : if (tag.n < 1 || tag.n - 1 >= m_Units.size())
195 : return NULL;
196 0 : return &m_Units[tag.n - 1];
197 : }
198 :
199 0 : tag_t AddUnit(CEntityHandle entity, CUnit* actor, const CBoundingSphere& boundsApprox, int flags) override
200 : {
201 0 : ENSURE(actor != NULL);
202 :
203 0 : tag_t tag;
204 0 : if (!m_UnitTagsFree.empty())
205 : {
206 0 : tag = m_UnitTagsFree.back();
207 0 : m_UnitTagsFree.pop_back();
208 : }
209 : else
210 : {
211 0 : m_Units.push_back(SUnit());
212 0 : tag.n = m_Units.size();
213 : }
214 :
215 0 : SUnit* unit = LookupUnit(tag);
216 0 : unit->entity = entity;
217 0 : unit->actor = actor;
218 0 : unit->lastTransformFrame = -1;
219 0 : unit->flags = flags;
220 0 : unit->boundsApprox = boundsApprox;
221 0 : unit->inWorld = false;
222 0 : unit->visibilityDirty = true;
223 0 : unit->pos0 = unit->pos1 = CVector3D();
224 :
225 0 : return tag;
226 : }
227 :
228 0 : void RemoveUnit(tag_t tag) override
229 : {
230 0 : SUnit* unit = LookupUnit(tag);
231 0 : unit->actor = NULL;
232 0 : unit->inWorld = false;
233 0 : m_UnitTagsFree.push_back(tag);
234 0 : }
235 :
236 0 : void RecomputeSweptBounds(SUnit* unit)
237 : {
238 : // Compute the bounding sphere of the capsule formed by
239 : // sweeping boundsApprox from pos0 to pos1
240 0 : CVector3D mid = (unit->pos0 + unit->pos1) * 0.5f + unit->boundsApprox.GetCenter();
241 0 : float radius = (unit->pos1 - unit->pos0).Length() * 0.5f + unit->boundsApprox.GetRadius();
242 0 : unit->sweptBounds = CBoundingSphere(mid, radius);
243 0 : }
244 :
245 0 : void UpdateUnit(tag_t tag, CUnit* actor, const CBoundingSphere& boundsApprox) override
246 : {
247 0 : SUnit* unit = LookupUnit(tag);
248 0 : unit->actor = actor;
249 0 : unit->boundsApprox = boundsApprox;
250 0 : RecomputeSweptBounds(unit);
251 0 : }
252 :
253 0 : void UpdateUnitPos(tag_t tag, bool inWorld, const CVector3D& pos0, const CVector3D& pos1) override
254 : {
255 0 : SUnit* unit = LookupUnit(tag);
256 0 : unit->inWorld = inWorld;
257 0 : unit->pos0 = pos0;
258 0 : unit->pos1 = pos1;
259 0 : unit->visibilityDirty = true;
260 0 : RecomputeSweptBounds(unit);
261 0 : }
262 :
263 : void TurnStart();
264 : void Interpolate(float frameTime, float frameOffset);
265 : void RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling);
266 :
267 : void UpdateVisibility(SUnit& unit) const;
268 :
269 0 : float GetFrameOffset() const override
270 : {
271 0 : return m_FrameOffset;
272 : }
273 :
274 0 : void SetDebugOverlay(bool enabled) override
275 : {
276 0 : m_EnableDebugOverlays = enabled;
277 0 : }
278 :
279 0 : void PickAllEntitiesAtPoint(std::vector<std::pair<CEntityHandle, CVector3D> >& outEntities, const CVector3D& origin, const CVector3D& dir, bool allowEditorSelectables) const override
280 : {
281 : // First, make a rough test with the worst-case bounding boxes to pick all
282 : // entities/models that could possibly be hit by the ray.
283 0 : std::vector<const SUnit*> candidates;
284 0 : for (const SUnit& unit : m_Units)
285 : {
286 0 : if (!unit.actor || !unit.inWorld)
287 0 : continue;
288 0 : if (unit.sweptBounds.RayIntersect(origin, dir))
289 0 : candidates.push_back(&unit);
290 : }
291 :
292 : // Now make a more precise test to get rid of the remaining false positives
293 0 : float tmin, tmax;
294 0 : CVector3D center;
295 0 : for (size_t i = 0; i< candidates.size(); ++i)
296 : {
297 0 : const SUnit& unit = *candidates[i];
298 :
299 0 : CmpPtr<ICmpVisual> cmpVisual(unit.entity);
300 0 : if (!cmpVisual)
301 0 : continue;
302 :
303 0 : CBoundingBoxOriented selectionBox = cmpVisual->GetSelectionBox();
304 0 : if (selectionBox.IsEmpty())
305 : {
306 0 : if (!allowEditorSelectables)
307 0 : continue;
308 :
309 : // Fall back to using old AABB selection method for decals
310 : // see: https://gitea.wildfiregames.com/0ad/0ad/issues/1032
311 : // Decals are flat objects without a selectionShape defined,
312 : // but they should still be selectable in the editor to move them
313 : // around or delete them after they are placed.
314 : // Check campaigns/labels/ in the Actors tab of atlas for examples.
315 0 : CBoundingBoxAligned aABBox = cmpVisual->GetBounds();
316 0 : if (aABBox.IsEmpty())
317 0 : continue;
318 :
319 0 : if (!aABBox.RayIntersect(origin, dir, tmin, tmax))
320 0 : continue;
321 :
322 0 : aABBox.GetCenter(center);
323 : }
324 : else
325 : {
326 0 : if (!selectionBox.RayIntersect(origin, dir, tmin, tmax))
327 0 : continue;
328 :
329 0 : center = selectionBox.m_Center;
330 : }
331 0 : outEntities.emplace_back(unit.entity, center);
332 : }
333 0 : }
334 : };
335 :
336 181 : void CCmpUnitRenderer::TurnStart()
337 : {
338 181 : PROFILE3("UnitRenderer::TurnStart");
339 :
340 : // Assume units have stopped moving after the previous turn. If that assumption is not
341 : // correct, we will get a UpdateUnitPos to tell us about its movement in the new turn.
342 181 : for (size_t i = 0; i < m_Units.size(); i++)
343 : {
344 0 : SUnit& unit = m_Units[i];
345 0 : unit.pos0 = unit.pos1;
346 0 : unit.sweptBounds = CBoundingSphere(unit.pos1, unit.boundsApprox.GetRadius());
347 :
348 : // Visibility must be recomputed on the first frame during this turn
349 0 : unit.visibilityDirty = true;
350 : }
351 181 : }
352 :
353 3 : void CCmpUnitRenderer::Interpolate(float frameTime, float frameOffset)
354 : {
355 3 : PROFILE3("UnitRenderer::Interpolate");
356 :
357 3 : ++m_FrameNumber;
358 3 : m_FrameOffset = frameOffset;
359 :
360 : // TODO: we shouldn't update all the animations etc for units that are off-screen
361 : // (but need to be careful about e.g. sounds triggered by animations of off-screen
362 : // units)
363 3 : for (size_t i = 0; i < m_Units.size(); i++)
364 : {
365 0 : SUnit& unit = m_Units[i];
366 0 : if (unit.actor)
367 0 : unit.actor->UpdateModel(frameTime);
368 : }
369 :
370 3 : m_DebugSpheres.clear();
371 3 : if (m_EnableDebugOverlays)
372 : {
373 0 : for (const SUnit& unit : m_Units)
374 : {
375 0 : if (!(unit.actor && unit.inWorld))
376 0 : continue;
377 :
378 0 : SOverlaySphere sphere;
379 0 : sphere.m_Center = unit.sweptBounds.GetCenter();
380 0 : sphere.m_Radius = unit.sweptBounds.GetRadius();
381 0 : if (unit.culled)
382 0 : sphere.m_Color = CColor(1.0f, 0.5f, 0.5f, 0.5f);
383 : else
384 0 : sphere.m_Color = CColor(0.5f, 0.5f, 1.0f, 0.5f);
385 :
386 0 : m_DebugSpheres.push_back(sphere);
387 : }
388 : }
389 3 : }
390 :
391 0 : void CCmpUnitRenderer::RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling)
392 : {
393 : // TODO: need a coarse culling pass based on some kind of spatial data
394 : // structure - that's the main point of this design. Once we've got a
395 : // rough list of possibly-visible units, then we can do the more precise
396 : // culling. (And once it's cheap enough, we can do multiple culling passes
397 : // per frame - one for shadow generation, one for water reflections, etc.)
398 :
399 0 : PROFILE3("UnitRenderer::RenderSubmit");
400 :
401 0 : for (size_t i = 0; i < m_Units.size(); ++i)
402 : {
403 0 : SUnit& unit = m_Units[i];
404 :
405 0 : unit.culled = true;
406 :
407 0 : if (!unit.actor)
408 0 : continue;
409 :
410 0 : if (unit.visibilityDirty)
411 0 : UpdateVisibility(unit);
412 :
413 0 : if (unit.visibility == LosVisibility::HIDDEN)
414 0 : continue;
415 :
416 0 : if (!g_AtlasGameLoop->running && !g_RenderingOptions.GetRenderActors() && (unit.flags & ACTOR_ONLY))
417 0 : continue;
418 :
419 0 : if (!g_AtlasGameLoop->running && (unit.flags & VISIBLE_IN_ATLAS_ONLY))
420 0 : continue;
421 :
422 0 : if (culling && !frustum.IsSphereVisible(unit.sweptBounds.GetCenter(), unit.sweptBounds.GetRadius()))
423 0 : continue;
424 :
425 0 : unit.culled = false;
426 :
427 0 : CModelAbstract& unitModel = unit.actor->GetModel();
428 :
429 0 : if (unit.lastTransformFrame != m_FrameNumber)
430 : {
431 0 : CmpPtr<ICmpPosition> cmpPosition(unit.entity);
432 0 : if (!cmpPosition)
433 0 : continue;
434 :
435 0 : CMatrix3D transform(cmpPosition->GetInterpolatedTransform(m_FrameOffset));
436 :
437 0 : unitModel.SetTransform(transform);
438 :
439 0 : unit.lastTransformFrame = m_FrameNumber;
440 : }
441 :
442 0 : if (culling && !frustum.IsBoxVisible(unitModel.GetWorldBoundsRec()))
443 0 : continue;
444 :
445 0 : collector.SubmitRecursive(&unitModel);
446 : }
447 :
448 0 : for (size_t i = 0; i < m_DebugSpheres.size(); ++i)
449 0 : collector.Submit(&m_DebugSpheres[i]);
450 0 : }
451 :
452 0 : void CCmpUnitRenderer::UpdateVisibility(SUnit& unit) const
453 : {
454 0 : if (unit.inWorld)
455 : {
456 : // The 'always visible' flag means we should always render the unit
457 : // (regardless of whether the LOS system thinks it's visible)
458 0 : CmpPtr<ICmpVisibility> cmpVisibility(unit.entity);
459 0 : if (cmpVisibility && cmpVisibility->GetAlwaysVisible())
460 0 : unit.visibility = LosVisibility::VISIBLE;
461 : else
462 : {
463 0 : CmpPtr<ICmpRangeManager> cmpRangeManager(GetSystemEntity());
464 0 : unit.visibility = cmpRangeManager->GetLosVisibility(unit.entity,
465 0 : GetSimContext().GetCurrentDisplayedPlayer());
466 : }
467 : }
468 : else
469 0 : unit.visibility = LosVisibility::HIDDEN;
470 :
471 : // Change the visibility of the visual actor's selectable if it has one.
472 0 : CmpPtr<ICmpSelectable> cmpSelectable(unit.entity);
473 0 : if (cmpSelectable)
474 0 : cmpSelectable->SetVisibility(unit.visibility != LosVisibility::HIDDEN);
475 :
476 0 : unit.visibilityDirty = false;
477 0 : }
478 :
479 274 : REGISTER_COMPONENT_TYPE(UnitRenderer)
|