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 "ICmpVisual.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/Decal.h"
24 : #include "graphics/Model.h"
25 : #include "graphics/ModelAbstract.h"
26 : #include "graphics/ObjectBase.h"
27 : #include "graphics/ObjectEntry.h"
28 : #include "graphics/Unit.h"
29 : #include "graphics/UnitAnimation.h"
30 : #include "graphics/UnitManager.h"
31 : #include "lib/debug.h"
32 : #include "lib/path.h"
33 : #include "lib/utf8.h"
34 : #include "maths/BoundingBoxAligned.h"
35 : #include "maths/BoundingBoxOriented.h"
36 : #include "maths/BoundingSphere.h"
37 : #include "maths/Fixed.h"
38 : #include "maths/FixedVector3D.h"
39 : #include "maths/Matrix3D.h"
40 : #include "maths/Vector3D.h"
41 : #include "ps/CLogger.h"
42 : #include "ps/CStr.h"
43 : #include "ps/algorithm.h"
44 : #include "simulation2/MessageTypes.h"
45 : #include "simulation2/components/ICmpFootprint.h"
46 : #include "simulation2/components/ICmpIdentity.h"
47 : #include "simulation2/components/ICmpMirage.h"
48 : #include "simulation2/components/ICmpOwnership.h"
49 : #include "simulation2/components/ICmpPosition.h"
50 : #include "simulation2/components/ICmpSound.h"
51 : #include "simulation2/components/ICmpTemplateManager.h"
52 : #include "simulation2/components/ICmpUnitRenderer.h"
53 : #include "simulation2/components/ICmpValueModificationManager.h"
54 : #include "simulation2/components/ICmpVisibility.h"
55 : #include "simulation2/helpers/Player.h"
56 : #include "simulation2/helpers/Position.h"
57 : #include "simulation2/serialization/SerializeTemplates.h"
58 : #include "simulation2/serialization/SerializedTypes.h"
59 : #include "simulation2/system/Component.h"
60 : #include "simulation2/system/Component.h"
61 : #include "simulation2/system/Interface.h"
62 : #include "simulation2/system/Message.h"
63 :
64 : #include <cstddef>
65 : #include <js/Value.h>
66 : #include <map>
67 : #include <memory>
68 : #include <string>
69 : #include <utility>
70 :
71 195 : class CCmpVisualActor final : public ICmpVisual
72 : {
73 : public:
74 137 : static void ClassInit(CComponentManager& componentManager)
75 : {
76 137 : componentManager.SubscribeToMessageType(MT_InterpolatedPositionChanged);
77 137 : componentManager.SubscribeToMessageType(MT_OwnershipChanged);
78 137 : componentManager.SubscribeToMessageType(MT_ValueModification);
79 137 : componentManager.SubscribeToMessageType(MT_Create);
80 137 : componentManager.SubscribeToMessageType(MT_Destroy);
81 137 : }
82 :
83 390 : DEFAULT_COMPONENT_ALLOCATOR(VisualActor)
84 :
85 : private:
86 : std::wstring m_BaseActorName, m_ActorName;
87 : bool m_IsFoundationActor;
88 :
89 : // Not initialized in non-visual mode
90 : CUnit* m_Unit;
91 : CModelAbstract::CustomSelectionShape* m_ShapeDescriptor = nullptr;
92 :
93 : fixed m_R, m_G, m_B; // shading color
94 :
95 : // Current animation state
96 : std::string m_AnimName;
97 : bool m_AnimOnce;
98 : fixed m_AnimSpeed;
99 : std::wstring m_SoundGroup;
100 : fixed m_AnimDesync;
101 : fixed m_AnimSyncRepeatTime; // 0.0 if not synced
102 : fixed m_AnimSyncOffsetTime;
103 :
104 : std::map<CStr, CStr> m_VariantSelections;
105 :
106 : std::uint32_t m_Seed; // seed used for random variations
107 :
108 : bool m_ConstructionPreview;
109 :
110 : bool m_VisibleInAtlasOnly;
111 : bool m_IsActorOnly; // an in-world entity should not have this or it might not be rendered.
112 :
113 : bool m_SilhouetteDisplay;
114 : bool m_SilhouetteOccluder;
115 : bool m_ShadowsCast;
116 : bool m_ShadowsReceive;
117 :
118 : ICmpUnitRenderer::tag_t m_ModelTag;
119 :
120 : public:
121 137 : static std::string GetSchema()
122 : {
123 137 : return
124 : "<a:help>Display the unit using the engine's actor system.</a:help>"
125 : "<a:example>"
126 : "<Actor>units/hellenes/infantry_spearman_b.xml</Actor>"
127 : "</a:example>"
128 : "<a:example>"
129 : "<Actor>structures/hellenes/barracks.xml</Actor>"
130 : "<FoundationActor>structures/fndn_4x4.xml</FoundationActor>"
131 : "</a:example>"
132 : "<element name='Actor' a:help='Filename of the actor to be used for this unit'>"
133 : "<text/>"
134 : "</element>"
135 : "<optional>"
136 : "<element name='FoundationActor' a:help='Filename of the actor to be used the foundation while this unit is being constructed'>"
137 : "<text/>"
138 : "</element>"
139 : "</optional>"
140 : "<optional>"
141 : "<element name='Foundation' a:help='Used internally; if present, the unit will be rendered as a foundation'>"
142 : "<empty/>"
143 : "</element>"
144 : "</optional>"
145 : "<optional>"
146 : "<element name='ConstructionPreview' a:help='If present, the unit should have a construction preview'>"
147 : "<empty/>"
148 : "</element>"
149 : "</optional>"
150 : "<optional>"
151 : "<element name='ActorOnly' a:help='Used internally; if present, the unit will only be rendered if the user has high enough graphical settings.'>"
152 : "<empty/>"
153 : "</element>"
154 : "</optional>"
155 : "<element name='SilhouetteDisplay'>"
156 : "<data type='boolean'/>"
157 : "</element>"
158 : "<element name='SilhouetteOccluder'>"
159 : "<data type='boolean'/>"
160 : "</element>"
161 : "<optional>"
162 : "<element name='SelectionShape'>"
163 : "<choice>"
164 : "<element name='Bounds' a:help='Determines the selection box based on the model bounds'>"
165 : "<empty/>"
166 : "</element>"
167 : "<element name='Footprint' a:help='Determines the selection box based on the entity Footprint component'>"
168 : "<empty/>"
169 : "</element>"
170 : "<element name='Box' a:help='Sets the selection shape to a box of specified dimensions'>"
171 : "<attribute name='width'>"
172 : "<data type='decimal'>"
173 : "<param name='minExclusive'>0.0</param>"
174 : "</data>"
175 : "</attribute>"
176 : "<attribute name='height'>"
177 : "<data type='decimal'>"
178 : "<param name='minExclusive'>0.0</param>"
179 : "</data>"
180 : "</attribute>"
181 : "<attribute name='depth'>"
182 : "<data type='decimal'>"
183 : "<param name='minExclusive'>0.0</param>"
184 : "</data>"
185 : "</attribute>"
186 : "</element>"
187 : "<element name='Cylinder' a:help='Sets the selection shape to a cylinder of specified dimensions'>"
188 : "<attribute name='radius'>"
189 : "<data type='decimal'>"
190 : "<param name='minExclusive'>0.0</param>"
191 : "</data>"
192 : "</attribute>"
193 : "<attribute name='height'>"
194 : "<data type='decimal'>"
195 : "<param name='minExclusive'>0.0</param>"
196 : "</data>"
197 : "</attribute>"
198 : "</element>"
199 : "</choice>"
200 : "</element>"
201 : "</optional>"
202 : "<element name='VisibleInAtlasOnly'>"
203 : "<data type='boolean'/>"
204 : "</element>"
205 : "<optional>"
206 : "<element name='ShadowsCast'>"
207 : "<a:help>If true (default), the entity will cast dynamic shadows onto the environment. "
208 : "Set to false to avoid unnecessary shadow computation for objects that do not need to affect scene lighting, "
209 : "such as transparent effects, previews, or decorative visuals.</a:help>"
210 : "<data type='boolean'/>"
211 : "</element>"
212 : "</optional>"
213 : "<optional>"
214 : "<element name='ShadowsReceive'>"
215 : "<a:help>If true (default), the entity will receive dynamic shadows from other objects. "
216 : "Set to false if the object should appear fully lit regardless of surrounding shadows, which can be useful "
217 : "for performance tuning or effects that simulate glowing or volumetric visuals.</a:help>"
218 : "<data type='boolean'/>"
219 : "</element>"
220 137 : "</optional>";
221 : }
222 :
223 195 : void Init(const CParamNode& paramNode) override
224 : {
225 195 : m_Unit = NULL;
226 195 : m_R = m_G = m_B = fixed::FromInt(1);
227 :
228 195 : m_ConstructionPreview = paramNode.GetChild("ConstructionPreview").IsOk();
229 :
230 195 : m_Seed = GetEntityId();
231 :
232 195 : m_IsFoundationActor = paramNode.GetChild("Foundation").IsOk() && paramNode.GetChild("FoundationActor").IsOk();
233 :
234 585 : m_BaseActorName = paramNode.GetChild(m_IsFoundationActor ? "FoundationActor" : "Actor").ToWString();
235 195 : ParseActorName(m_BaseActorName);
236 :
237 195 : m_VisibleInAtlasOnly = paramNode.GetChild("VisibleInAtlasOnly").ToBool();
238 195 : m_IsActorOnly = paramNode.GetChild("ActorOnly").IsOk();
239 :
240 195 : m_SilhouetteDisplay = paramNode.GetChild("SilhouetteDisplay").ToBool();
241 195 : m_SilhouetteOccluder = paramNode.GetChild("SilhouetteOccluder").ToBool();
242 :
243 195 : m_ShadowsCast = m_VisibleInAtlasOnly ? false : (paramNode.GetChild("ShadowsCast").IsOk() ? paramNode.GetChild("ShadowsCast").ToBool() : true);
244 195 : m_ShadowsReceive = m_VisibleInAtlasOnly ? false : (paramNode.GetChild("ShadowsReceive").IsOk() ? paramNode.GetChild("ShadowsReceive").ToBool() : true);
245 :
246 : // Initialize the model's selection shape descriptor. This currently relies on the component initialization order; the
247 : // Footprint component must be initialized before this component (VisualActor) to support the ability to use the footprint
248 : // shape for the selection box (instead of the default recursive bounding box). See TypeList.h for the order in
249 : // which components are initialized; if for whatever reason you need to get rid of this dependency, you can always just
250 : // initialize the selection shape descriptor on-demand.
251 195 : InitSelectionShapeDescriptor(paramNode);
252 195 : }
253 :
254 195 : void Deinit() override
255 : {
256 195 : if (m_Unit)
257 : {
258 0 : GetSimContext().GetUnitManager().DeleteUnit(m_Unit);
259 0 : m_Unit = NULL;
260 : }
261 195 : }
262 :
263 : template<typename S>
264 1032 : void SerializeCommon(S& serialize)
265 : {
266 1032 : serialize.NumberFixed_Unbounded("r", m_R);
267 1032 : serialize.NumberFixed_Unbounded("g", m_G);
268 1032 : serialize.NumberFixed_Unbounded("b", m_B);
269 :
270 1032 : serialize.StringASCII("anim name", m_AnimName, 0, 256);
271 1032 : serialize.Bool("anim once", m_AnimOnce);
272 1032 : serialize.NumberFixed_Unbounded("anim speed", m_AnimSpeed);
273 1032 : serialize.String("sound group", m_SoundGroup, 0, 256);
274 1032 : serialize.NumberFixed_Unbounded("anim desync", m_AnimDesync);
275 1032 : serialize.NumberFixed_Unbounded("anim sync repeat time", m_AnimSyncRepeatTime);
276 1032 : serialize.NumberFixed_Unbounded("anim sync offset time", m_AnimSyncOffsetTime);
277 :
278 1032 : Serializer(serialize, "variation", m_VariantSelections);
279 :
280 1032 : serialize.NumberU32_Unbounded("seed", m_Seed);
281 1032 : serialize.String("actor", m_ActorName, 0, 256);
282 :
283 : // TODO: store actor variables?
284 1032 : }
285 :
286 1032 : void Serialize(ISerializer& serialize) override
287 : {
288 : // TODO: store the actor name, if !debug and it differs from the template
289 :
290 1032 : if (serialize.IsDebug())
291 : {
292 0 : serialize.String("base actor", m_BaseActorName, 0, 256);
293 : }
294 :
295 1032 : SerializeCommon(serialize);
296 1032 : }
297 :
298 0 : void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
299 : {
300 0 : Init(paramNode);
301 :
302 0 : std::uint32_t oldSeed = GetActorSeed();
303 :
304 0 : SerializeCommon(deserialize);
305 :
306 0 : InitModel();
307 :
308 : // If we serialized a different seed or different actor, reload actor
309 0 : if (oldSeed != GetActorSeed() || m_BaseActorName != m_ActorName)
310 0 : ReloadActor();
311 : else
312 0 : ReloadUnitAnimation();
313 :
314 0 : if (m_Unit)
315 : {
316 0 : CmpPtr<ICmpOwnership> cmpOwnership(GetEntityHandle());
317 0 : if (cmpOwnership)
318 0 : m_Unit->GetModel().SetPlayerID(cmpOwnership->GetOwner());
319 : }
320 0 : }
321 :
322 7779 : void HandleMessage(const CMessage& msg, bool /*global*/) override
323 : {
324 7779 : switch (msg.GetType())
325 : {
326 225 : case MT_OwnershipChanged:
327 225 : {
328 225 : RecomputeActorName();
329 :
330 225 : if (!m_Unit)
331 : break;
332 :
333 0 : const CMessageOwnershipChanged& msgData = static_cast<const CMessageOwnershipChanged&> (msg);
334 0 : m_Unit->GetModel().SetPlayerID(msgData.to);
335 :
336 0 : break;
337 : }
338 186 : case MT_ValueModification:
339 186 : {
340 : // Mirages don't respond to technology modifications.
341 186 : CmpPtr<ICmpMirage> cmpMirage(GetEntityHandle());
342 186 : if (cmpMirage)
343 7779 : return;
344 :
345 186 : const CMessageValueModification& msgData = static_cast<const CMessageValueModification&> (msg);
346 186 : if (msgData.component != L"VisualActor")
347 : break;
348 :
349 0 : RecomputeActorName();
350 :
351 : break;
352 : }
353 7143 : case MT_InterpolatedPositionChanged:
354 7143 : {
355 7143 : const CMessageInterpolatedPositionChanged& msgData = static_cast<const CMessageInterpolatedPositionChanged&> (msg);
356 7143 : if (m_ModelTag.valid())
357 : {
358 0 : CmpPtr<ICmpUnitRenderer> cmpModelRenderer(GetSystemEntity());
359 0 : cmpModelRenderer->UpdateUnitPos(m_ModelTag, msgData.inWorld, msgData.pos0, msgData.pos1);
360 : }
361 : break;
362 : }
363 195 : case MT_Create:
364 195 : {
365 195 : InitModel();
366 :
367 195 : SelectAnimation("idle");
368 195 : break;
369 : }
370 30 : case MT_Destroy:
371 30 : {
372 30 : if (m_ModelTag.valid())
373 : {
374 0 : CmpPtr<ICmpUnitRenderer> cmpModelRenderer(GetSystemEntity());
375 0 : cmpModelRenderer->RemoveUnit(m_ModelTag);
376 0 : m_ModelTag = ICmpUnitRenderer::tag_t();
377 : }
378 : break;
379 : }
380 : }
381 : }
382 :
383 0 : CBoundingBoxAligned GetBounds() const override
384 : {
385 0 : if (!m_Unit)
386 0 : return CBoundingBoxAligned::EMPTY;
387 0 : return m_Unit->GetModel().GetWorldBounds();
388 : }
389 :
390 0 : CUnit* GetUnit() override
391 : {
392 0 : return m_Unit;
393 : }
394 :
395 0 : CBoundingBoxOriented GetSelectionBox() const override
396 : {
397 0 : if (!m_Unit)
398 0 : return CBoundingBoxOriented::EMPTY;
399 0 : return m_Unit->GetModel().GetSelectionBox();
400 : }
401 :
402 0 : CVector3D GetPosition() const override
403 : {
404 0 : if (!m_Unit)
405 0 : return CVector3D(0, 0, 0);
406 0 : return m_Unit->GetModel().GetTransform().GetTranslation();
407 : }
408 :
409 120 : std::wstring GetProjectileActor() const override
410 : {
411 120 : if (!m_Unit)
412 120 : return L"";
413 0 : return m_Unit->GetObject().m_ProjectileModelName;
414 : }
415 :
416 120 : CFixedVector3D GetProjectileLaunchPoint() const override
417 : {
418 120 : if (!m_Unit)
419 120 : return CFixedVector3D();
420 :
421 0 : if (m_Unit->GetModel().ToCModel())
422 : {
423 : // Ensure the prop transforms are correct
424 0 : CmpPtr<ICmpUnitRenderer> cmpUnitRenderer(GetSystemEntity());
425 0 : CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
426 0 : if (cmpUnitRenderer && cmpPosition)
427 : {
428 0 : float frameOffset = cmpUnitRenderer->GetFrameOffset();
429 0 : CMatrix3D transform(cmpPosition->GetInterpolatedTransform(frameOffset));
430 0 : m_Unit->GetModel().SetTransform(transform);
431 0 : m_Unit->GetModel().ValidatePosition();
432 : }
433 :
434 0 : CModelAbstract* ammo = m_Unit->GetModel().ToCModel()->FindFirstAmmoProp();
435 0 : if (ammo)
436 : {
437 0 : CVector3D vector = ammo->GetTransform().GetTranslation();
438 0 : return CFixedVector3D(fixed::FromFloat(vector.X), fixed::FromFloat(vector.Y), fixed::FromFloat(vector.Z));
439 : }
440 : }
441 :
442 0 : return CFixedVector3D();
443 : }
444 :
445 3231 : void SetVariant(const CStr& key, const CStr& selection) override
446 : {
447 3231 : if (m_VariantSelections[key] == selection)
448 : return;
449 :
450 1320 : m_VariantSelections[key] = selection;
451 :
452 1320 : if (m_Unit)
453 : {
454 0 : m_Unit->SetEntitySelection(key, selection);
455 0 : if (m_Unit->GetAnimation())
456 0 : m_Unit->GetAnimation()->ReloadAnimation();
457 : }
458 : }
459 :
460 0 : std::string GetAnimationName() const override
461 : {
462 0 : return m_AnimName;
463 : }
464 :
465 2637 : void SelectAnimation(const std::string& name, bool once = false, fixed speed = fixed::FromInt(1)) override
466 : {
467 2637 : m_AnimName = name;
468 2637 : m_AnimOnce = once;
469 2637 : m_AnimSpeed = speed;
470 2637 : m_SoundGroup = L"";
471 2637 : m_AnimDesync = fixed::FromInt(1)/20; // TODO: make this an argument
472 2637 : m_AnimSyncRepeatTime = fixed::Zero();
473 2637 : m_AnimSyncOffsetTime = fixed::Zero();
474 :
475 7911 : SetVariant("animation", m_AnimName);
476 :
477 2637 : CmpPtr<ICmpSound> cmpSound(GetEntityHandle());
478 2637 : if (cmpSound)
479 6801 : m_SoundGroup = cmpSound->GetSoundGroup(wstring_from_utf8(m_AnimName));
480 :
481 2637 : if (!m_Unit || !m_Unit->GetAnimation() || !m_Unit->GetID())
482 2637 : return;
483 :
484 0 : m_Unit->GetAnimation()->SetAnimationState(m_AnimName, m_AnimOnce, m_AnimSpeed.ToFloat(), m_AnimDesync.ToFloat(), m_SoundGroup.c_str());
485 : }
486 :
487 7278 : void SelectMovementAnimation(const std::string& name, fixed speed) override
488 : {
489 7278 : ENSURE(name == "idle" || name == "walk" || name == "run");
490 7278 : if (m_AnimName != "idle" && m_AnimName != "walk" && m_AnimName != "run")
491 : return;
492 7026 : if (m_AnimName == name && speed == m_AnimSpeed)
493 : return;
494 1746 : SelectAnimation(name, false, speed);
495 : }
496 :
497 258 : void SetAnimationSyncRepeat(fixed repeattime) override
498 : {
499 258 : m_AnimSyncRepeatTime = repeattime;
500 :
501 258 : if (m_Unit && m_Unit->GetAnimation())
502 0 : m_Unit->GetAnimation()->SetAnimationSyncRepeat(m_AnimSyncRepeatTime.ToFloat());
503 258 : }
504 :
505 258 : void SetAnimationSyncOffset(fixed actiontime) override
506 : {
507 258 : m_AnimSyncOffsetTime = actiontime;
508 :
509 258 : if (m_Unit && m_Unit->GetAnimation())
510 0 : m_Unit->GetAnimation()->SetAnimationSyncOffset(m_AnimSyncOffsetTime.ToFloat());
511 258 : }
512 :
513 : // TODO: Why is `a` even an argument?
514 0 : void SetShadingColor(fixed r, fixed g, fixed b, fixed /*a*/) override
515 : {
516 0 : m_R = r;
517 0 : m_G = g;
518 0 : m_B = b;
519 :
520 0 : if (m_Unit)
521 : {
522 0 : CModelAbstract& model = m_Unit->GetModel();
523 0 : model.SetShadingColor(CColor(m_R.ToFloat(), m_G.ToFloat(), m_B.ToFloat(), 1.0f));
524 : }
525 0 : }
526 :
527 0 : void SetVariable(const std::string& name, float value) override
528 : {
529 0 : if (m_Unit)
530 0 : m_Unit->GetModel().SetEntityVariable(name, value);
531 0 : }
532 :
533 210 : std::uint32_t GetActorSeed() const override
534 : {
535 0 : return m_Seed;
536 : }
537 :
538 15 : void SetActorSeed(std::uint32_t seed) override
539 : {
540 15 : if (seed == m_Seed)
541 : return;
542 :
543 15 : m_Seed = seed;
544 15 : ReloadActor();
545 : }
546 :
547 234 : void RecomputeActorName() override
548 : {
549 234 : CmpPtr<ICmpValueModificationManager> cmpValueModificationManager(GetSystemEntity());
550 234 : std::wstring newActorName;
551 234 : if (m_IsFoundationActor)
552 0 : newActorName = cmpValueModificationManager->ApplyModifications(L"VisualActor/FoundationActor", m_BaseActorName, GetEntityId());
553 : else
554 936 : newActorName = cmpValueModificationManager->ApplyModifications(L"VisualActor/Actor", m_BaseActorName, GetEntityId());
555 :
556 234 : if (newActorName != m_ActorName)
557 : {
558 90 : ParseActorName(newActorName);
559 45 : ReloadActor();
560 : }
561 234 : }
562 :
563 0 : bool HasConstructionPreview() const override
564 : {
565 0 : return m_ConstructionPreview;
566 : }
567 :
568 0 : void Hotload(const VfsPath& name) override
569 : {
570 0 : if (!m_Unit)
571 : return;
572 :
573 0 : if (!name.empty() && name != m_ActorName)
574 : return;
575 :
576 0 : ReloadActor();
577 : }
578 :
579 : private:
580 : // Replace {phenotype} and {civ} with the correct value in m_ActorName
581 : void ParseActorName(std::wstring base);
582 :
583 : /// Helper function shared by component init and actor reloading
584 : void InitModel();
585 :
586 : /// Helper method; initializes the model selection shape descriptor from XML. Factored out for readability of @ref Init.
587 : void InitSelectionShapeDescriptor(const CParamNode& paramNode);
588 :
589 : // ReloadActor is used when the actor or seed changes.
590 : void ReloadActor();
591 : // ReloadUnitAnimation is used for a minimal reloading upon deserialization, when the actor and seed are identical.
592 : // It is also used by ReloadActor.
593 : void ReloadUnitAnimation();
594 : };
595 :
596 274 : REGISTER_COMPONENT_TYPE(VisualActor)
597 :
598 : // ------------------------------------------------------------------------------------------------------------------
599 :
600 240 : void CCmpVisualActor::ParseActorName(std::wstring base)
601 : {
602 240 : CmpPtr<ICmpIdentity> cmpIdentity(GetEntityHandle());
603 240 : if (cmpIdentity)
604 : {
605 240 : PS::ReplaceSubrange(base, L"{phenotype}", cmpIdentity->GetPhenotype());
606 480 : PS::ReplaceSubrange(base, L"{civ}", cmpIdentity->GetCiv());
607 : }
608 :
609 240 : m_ActorName = std::move(base);
610 240 : }
611 :
612 195 : void CCmpVisualActor::InitModel()
613 : {
614 195 : if (!GetSimContext().HasUnitManager())
615 195 : return;
616 :
617 195 : std::wstring actorName = m_ActorName;
618 195 : if (actorName.find(L".xml") == std::wstring::npos)
619 0 : actorName += L".xml";
620 390 : m_Unit = GetSimContext().GetUnitManager().CreateUnit(actorName, GetEntityId(), GetActorSeed());
621 195 : if (!m_Unit)
622 195 : return;
623 :
624 0 : CModelAbstract& model = m_Unit->GetModel();
625 0 : if (model.ToCModel())
626 : {
627 0 : std::uint32_t modelFlags = 0;
628 :
629 0 : if (m_SilhouetteDisplay)
630 0 : modelFlags |= ModelFlag::SILHOUETTE_DISPLAY;
631 :
632 0 : if (m_SilhouetteOccluder)
633 0 : modelFlags |= ModelFlag::SILHOUETTE_OCCLUDER;
634 :
635 0 : CmpPtr<ICmpVisibility> cmpVisibility(GetEntityHandle());
636 0 : if (cmpVisibility && cmpVisibility->GetAlwaysVisible())
637 0 : modelFlags |= ModelFlag::IGNORE_LOS;
638 :
639 0 : model.ToCModel()->AddFlagsRec(modelFlags);
640 : }
641 :
642 0 : if (!m_ShadowsCast && model.ToCModel())
643 0 : model.ToCModel()->RemoveShadowsCast();
644 :
645 0 : if (!m_ShadowsReceive)
646 : {
647 0 : if (model.ToCModel())
648 0 : model.ToCModel()->RemoveShadowsReceive();
649 0 : else if (model.ToCModelDecal())
650 0 : model.ToCModelDecal()->RemoveShadowsReceive();
651 : }
652 :
653 0 : CStr anchor = m_Unit->GetObject().m_Base->m_Properties.m_AnchorType;
654 0 : bool floating = m_Unit->GetObject().m_Base->m_Properties.m_FloatOnWater;
655 0 : CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
656 0 : if (cmpPosition)
657 : {
658 0 : if (!anchor.empty())
659 0 : cmpPosition->SetActorAnchor(anchor);
660 0 : cmpPosition->SetActorFloating(floating);
661 : }
662 :
663 0 : if (!m_ModelTag.valid())
664 : {
665 0 : CmpPtr<ICmpUnitRenderer> cmpModelRenderer(GetSystemEntity());
666 0 : if (cmpModelRenderer)
667 : {
668 : // TODO: this should account for all possible props, animations, etc,
669 : // else we might accidentally cull the unit when it should be visible
670 0 : CBoundingBoxAligned bounds = m_Unit->GetModel().GetWorldBoundsRec();
671 0 : CBoundingSphere boundSphere = CBoundingSphere::FromSweptBox(bounds);
672 :
673 0 : int flags = 0;
674 0 : if (m_IsActorOnly)
675 0 : flags |= ICmpUnitRenderer::ACTOR_ONLY;
676 0 : if (m_VisibleInAtlasOnly)
677 0 : flags |= ICmpUnitRenderer::VISIBLE_IN_ATLAS_ONLY;
678 :
679 0 : m_ModelTag = cmpModelRenderer->AddUnit(GetEntityHandle(), m_Unit, boundSphere, flags);
680 : }
681 : }
682 :
683 : // the model is now responsible for cleaning up the descriptor
684 0 : if (m_ShapeDescriptor != nullptr)
685 0 : m_Unit->GetModel().SetCustomSelectionShape(m_ShapeDescriptor);
686 195 : }
687 :
688 195 : void CCmpVisualActor::InitSelectionShapeDescriptor(const CParamNode& paramNode)
689 : {
690 : // by default, we don't need a custom selection shape and we can just keep the default behaviour
691 195 : m_ShapeDescriptor = nullptr;
692 :
693 195 : const CParamNode& shapeNode = paramNode.GetChild("SelectionShape");
694 195 : if (shapeNode.IsOk())
695 : {
696 0 : if (shapeNode.GetChild("Bounds").IsOk())
697 : {
698 : // default; no need to take action
699 : }
700 0 : else if (shapeNode.GetChild("Footprint").IsOk())
701 : {
702 0 : CmpPtr<ICmpFootprint> cmpFootprint(GetEntityHandle());
703 0 : if (cmpFootprint)
704 : {
705 0 : ICmpFootprint::EShape fpShape; // fp stands for "footprint"
706 0 : entity_pos_t fpSize0, fpSize1, fpHeight; // fp stands for "footprint"
707 0 : cmpFootprint->GetShape(fpShape, fpSize0, fpSize1, fpHeight);
708 :
709 0 : float size0 = fpSize0.ToFloat();
710 0 : float size1 = fpSize1.ToFloat();
711 :
712 : // TODO: we should properly distinguish between CIRCLE and SQUARE footprint shapes here, but since cylinders
713 : // aren't implemented yet and are almost indistinguishable from boxes for small enough sizes anyway,
714 : // we'll just use boxes for either case. However, for circular footprints the size0 and size1 values both
715 : // represent the radius, so we do have to adjust them to match the size1 and size0's of square footprints
716 : // (which represent the full width and depth).
717 0 : if (fpShape == ICmpFootprint::CIRCLE)
718 : {
719 0 : size0 *= 2;
720 0 : size1 *= 2;
721 : }
722 :
723 0 : m_ShapeDescriptor = new CModelAbstract::CustomSelectionShape;
724 0 : m_ShapeDescriptor->m_Type = CModelAbstract::CustomSelectionShape::BOX;
725 0 : m_ShapeDescriptor->m_Size0 = size0;
726 0 : m_ShapeDescriptor->m_Size1 = size1;
727 0 : m_ShapeDescriptor->m_Height = fpHeight.ToFloat();
728 : }
729 : else
730 : {
731 0 : LOGERROR("[VisualActor] Cannot apply footprint-based SelectionShape; Footprint component not initialized.");
732 : }
733 : }
734 0 : else if (shapeNode.GetChild("Box").IsOk())
735 : {
736 : // TODO: we might need to support the ability to specify a different box center in the future
737 0 : m_ShapeDescriptor = new CModelAbstract::CustomSelectionShape;
738 0 : m_ShapeDescriptor->m_Type = CModelAbstract::CustomSelectionShape::BOX;
739 0 : m_ShapeDescriptor->m_Size0 = shapeNode.GetChild("Box").GetChild("@width").ToFixed().ToFloat();
740 0 : m_ShapeDescriptor->m_Size1 = shapeNode.GetChild("Box").GetChild("@depth").ToFixed().ToFloat();
741 0 : m_ShapeDescriptor->m_Height = shapeNode.GetChild("Box").GetChild("@height").ToFixed().ToFloat();
742 : }
743 0 : else if (shapeNode.GetChild("Cylinder").IsOk())
744 : {
745 0 : LOGWARNING("[VisualActor] TODO: Cylinder selection shapes are not yet implemented; defaulting to recursive bounding boxes");
746 : }
747 : else
748 : {
749 : // shouldn't happen by virtue of validation against schema
750 0 : LOGERROR("[VisualActor] No selection shape specified");
751 : }
752 : }
753 195 : }
754 :
755 60 : void CCmpVisualActor::ReloadActor()
756 : {
757 60 : if (!m_Unit)
758 60 : return;
759 :
760 : // Save some data from the old unit
761 0 : CColor shading = m_Unit->GetModel().GetShadingColor();
762 0 : player_id_t playerID = m_Unit->GetModel().GetPlayerID();
763 :
764 : // Replace with the new unit
765 0 : GetSimContext().GetUnitManager().DeleteUnit(m_Unit);
766 :
767 : // HACK: selection shape needs template data, but rather than storing all that data
768 : // in the component, we load the template here and pass it into a helper function
769 0 : CmpPtr<ICmpTemplateManager> cmpTemplateManager(GetSystemEntity());
770 0 : const CParamNode* node = cmpTemplateManager->LoadLatestTemplate(GetEntityId());
771 0 : ENSURE(node && node->GetChild("VisualActor").IsOk());
772 :
773 0 : InitSelectionShapeDescriptor(node->GetChild("VisualActor"));
774 :
775 0 : InitModel();
776 :
777 0 : if (!m_Unit)
778 : {
779 0 : if (m_ModelTag.valid())
780 : {
781 0 : CmpPtr<ICmpUnitRenderer> cmpModelRenderer(GetSystemEntity());
782 0 : if (cmpModelRenderer)
783 0 : cmpModelRenderer->RemoveUnit(m_ModelTag);
784 0 : m_ModelTag = ICmpUnitRenderer::tag_t{};
785 : }
786 0 : return;
787 : }
788 :
789 0 : ReloadUnitAnimation();
790 :
791 0 : m_Unit->GetModel().SetShadingColor(shading);
792 :
793 0 : m_Unit->GetModel().SetPlayerID(playerID);
794 :
795 0 : if (m_ModelTag.valid())
796 : {
797 0 : CmpPtr<ICmpUnitRenderer> cmpModelRenderer(GetSystemEntity());
798 0 : CBoundingBoxAligned bounds = m_Unit->GetModel().GetWorldBoundsRec();
799 0 : CBoundingSphere boundSphere = CBoundingSphere::FromSweptBox(bounds);
800 0 : cmpModelRenderer->UpdateUnit(m_ModelTag, m_Unit, boundSphere);
801 : }
802 : }
803 :
804 0 : void CCmpVisualActor::ReloadUnitAnimation()
805 : {
806 0 : if (!m_Unit)
807 : return;
808 :
809 0 : m_Unit->SetEntitySelection(m_VariantSelections);
810 :
811 0 : if (!m_Unit->GetAnimation())
812 : return;
813 :
814 0 : m_Unit->GetAnimation()->SetAnimationState(m_AnimName, m_AnimOnce, m_AnimSpeed.ToFloat(), m_AnimDesync.ToFloat(), m_SoundGroup.c_str());
815 :
816 : // We'll lose the exact synchronisation but we should at least make sure it's going at the correct rate
817 0 : if (!m_AnimSyncRepeatTime.IsZero())
818 0 : m_Unit->GetAnimation()->SetAnimationSyncRepeat(m_AnimSyncRepeatTime.ToFloat());
819 0 : if (!m_AnimSyncOffsetTime.IsZero())
820 0 : m_Unit->GetAnimation()->SetAnimationSyncOffset(m_AnimSyncOffsetTime.ToFloat());
821 : }
|