LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpDecay.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 27 82 32.9 %
Date: 2026-12-02 01:21:50 Functions: 6 9 66.7 %

          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 "ICmpDecay.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "maths/BoundingBoxAligned.h"
      24             : #include "maths/Fixed.h"
      25             : #include "maths/FixedVector3D.h"
      26             : #include "maths/Vector3D.h"
      27             : #include "ps/Profile.h"
      28             : #include "simulation2/MessageTypes.h"
      29             : #include "simulation2/components/ICmpPosition.h"
      30             : #include "simulation2/components/ICmpTerrain.h"
      31             : #include "simulation2/components/ICmpVisual.h"
      32             : #include "simulation2/helpers/Position.h"
      33             : #include "simulation2/system/Component.h"
      34             : #include "simulation2/system/Entity.h"
      35             : #include "simulation2/system/Message.h"
      36             : 
      37             : #include <algorithm>
      38             : #include <cmath>
      39             : #include <optional>
      40             : #include <random>
      41             : #include <string>
      42             : 
      43             : /**
      44             :  * Fairly basic decay implementation, for units and buildings etc.
      45             :  * The decaying entity remains stationary for some time period, then falls downwards
      46             :  * with some initial speed and some acceleration, until it has fully sunk.
      47             :  * The sinking depth is determined from the actor's bounding box and the terrain.
      48             :  *
      49             :  * This currently doesn't work with entities whose ICmpPosition has an initial Y offset.
      50             :  *
      51             :  * This isn't very efficient (we'll store data and iterate every frame for every entity,
      52             :  * not just for corpse entities) - it could be designed more optimally if that's a real problem.
      53             :  *
      54             :  * Eventually we might want to adjust the decay rate based on user configuration (low-spec
      55             :  * machines could have fewer corpses), number of corpses, etc.
      56             :  *
      57             :  * Must not be used on network-synchronised entities, unless \<Inactive\> is present.
      58             :  */
      59         189 : class CCmpDecay final : public ICmpDecay
      60             : {
      61             : public:
      62             :     static void ClassInit(CComponentManager&)
      63             :     {
      64             :     }
      65             : 
      66         378 :     DEFAULT_COMPONENT_ALLOCATOR(Decay)
      67             : 
      68             :     bool m_Active;
      69             :     bool m_ShipSink;
      70             :     bool m_Stochastic;
      71             : 
      72             :     std::optional<std::minstd_rand> m_Generator;
      73             :     std::negative_binomial_distribution<> m_Distribution{ 6, 0.032 };
      74             :     std::geometric_distribution<>::result_type m_NextSink;
      75             : 
      76             :     float m_SinkProb;
      77             :     float m_DelayTime;
      78             :     float m_SinkRate;
      79             :     float m_SinkAccel;
      80             : 
      81             :     entity_pos_t m_InitialXRotation;
      82             :     entity_pos_t m_InitialZRotation;
      83             : 
      84             :     // Used to randomize ship-like sinking
      85             :     float m_SinkingAngleX;
      86             :     float m_SinkingAngleZ;
      87             : 
      88             :     float m_CurrentTime;
      89             :     float m_TotalSinkDepth; // distance we need to sink (derived from bounding box), or -1 if undetermined
      90             : 
      91         137 :     static std::string GetSchema()
      92             :     {
      93         137 :         return
      94             :             "<element name='Active' a:help='If false, the entity will not do any decaying'>"
      95             :                 "<data type='boolean'/>"
      96             :             "</element>"
      97             :             "<element name='SinkingAnim' a:help='If true, the entity will decay in a ship-like manner'>"
      98             :                 "<data type='boolean'/>"
      99             :             "</element>"
     100             :             "<element name='SinkProb' a:help='The entity decays according to the supplied probability each frame.'>"
     101             :                 "<ref name='nonNegativeDecimal'/>"
     102             :             "</element>"
     103             :             "<element name='DelayTime' a:help='Time to wait before starting to sink, in seconds'>"
     104             :                 "<ref name='nonNegativeDecimal'/>"
     105             :             "</element>"
     106             :             "<element name='SinkRate' a:help='Initial rate of sinking, in meters per second'>"
     107             :                 "<ref name='nonNegativeDecimal'/>"
     108             :             "</element>"
     109             :             "<element name='SinkAccel' a:help='Acceleration rate of sinking, in meters per second per second'>"
     110             :                 "<ref name='nonNegativeDecimal'/>"
     111         137 :             "</element>";
     112             :     }
     113             : 
     114         189 :     void Init(const CParamNode& paramNode) override
     115             :     {
     116         189 :         m_Active = paramNode.GetChild("Active").ToBool();
     117         189 :         m_ShipSink = paramNode.GetChild("SinkingAnim").ToBool();
     118         189 :         m_SinkProb = paramNode.GetChild("SinkProb").ToFixed().ToFloat();
     119         189 :         m_DelayTime = paramNode.GetChild("DelayTime").ToFixed().ToFloat();
     120         189 :         m_SinkRate = paramNode.GetChild("SinkRate").ToFixed().ToFloat();
     121         189 :         m_SinkAccel = paramNode.GetChild("SinkAccel").ToFixed().ToFloat();
     122             : 
     123         189 :         m_CurrentTime = 0.f;
     124         189 :         m_TotalSinkDepth = -1.f;
     125             : 
     126         189 :         m_Stochastic = m_SinkProb < 1.0f;
     127             : 
     128         189 :         std::negative_binomial_distribution<int>::param_type new_params(
     129         378 :             6, Clamp(m_SinkProb, 1e-3f, 1.0f));
     130         189 :         m_Distribution.param(new_params);
     131             : 
     132             :         // Detect unsafe misconfiguration
     133         189 :         if (m_Active && !ENTITY_IS_LOCAL(GetEntityId()))
     134             :         {
     135           0 :             debug_warn(L"CCmpDecay must not be used on non-local (network-synchronised) entities");
     136           0 :             m_Active = false;
     137             :         }
     138             : 
     139         189 :         if (m_Active)
     140           9 :             GetSimContext().GetComponentManager().DynamicSubscriptionNonsync(MT_Interpolate, this, true);
     141         189 :     }
     142             : 
     143         189 :     void Deinit() override
     144             :     {
     145         189 :     }
     146             : 
     147        1020 :     void Serialize(ISerializer&) override
     148             :     {
     149             :         // This component isn't network-synchronised, so don't serialize anything
     150        1020 :     }
     151             : 
     152           0 :     void Deserialize(const CParamNode& paramNode, IDeserializer&) override
     153             :     {
     154           0 :         Init(paramNode);
     155           0 :     }
     156             : 
     157           0 :     void HandleMessage(const CMessage& msg, bool /*global*/) override
     158             :     {
     159           0 :         switch (msg.GetType())
     160             :         {
     161           0 :         case MT_Interpolate:
     162           0 :         {
     163           0 :             PROFILE("Decay::Interpolate");
     164             : 
     165           0 :             if (!m_Active)
     166             :                 break;
     167             : 
     168           0 :             const CMessageInterpolate& msgData = static_cast<const CMessageInterpolate&> (msg);
     169             : 
     170           0 :             CmpPtr<ICmpPosition> cmpPosition(GetEntityHandle());
     171           0 :             if (!cmpPosition || !cmpPosition->IsInWorld())
     172             :             {
     173             :                 // If there's no position (this usually shouldn't happen), destroy the unit immediately
     174           0 :                 GetSimContext().GetComponentManager().DestroyComponentsSoon(GetEntityId());
     175             :                 break;
     176             :             }
     177             : 
     178             :             // Compute the depth the first time this is called
     179             :             // (This is a bit of an ugly place to do it but at least we'll be sure
     180             :             // the actor component was loaded already)
     181           0 :             if (m_TotalSinkDepth < 0.f)
     182             :             {
     183           0 :                 m_TotalSinkDepth = 1.f; // minimum so we always sink at least a little
     184             : 
     185           0 :                 CmpPtr<ICmpVisual> cmpVisual(GetEntityHandle());
     186           0 :                 if (cmpVisual)
     187             :                 {
     188           0 :                     CBoundingBoxAligned bound = cmpVisual->GetBounds();
     189           0 :                     m_TotalSinkDepth = std::max(m_TotalSinkDepth, bound[1].Y - bound[0].Y);
     190             :                 }
     191             : 
     192             :                 // If this is a floating unit, we want it to sink all the way under the terrain,
     193             :                 // so find the difference between its current position and the terrain
     194             : 
     195           0 :                 CFixedVector3D pos = cmpPosition->GetPosition();
     196             : 
     197             :                 //Use the entities position upon decay start to vary the pseudorandom seed.
     198           0 :                 if (!m_Generator.has_value())
     199             :                 {
     200           0 :                     m_Generator.emplace(pos.X.ToInt_RoundToNearest() * pos.Z.ToInt_RoundToNearest());
     201           0 :                     m_NextSink = m_Distribution(m_Generator.value());
     202             :                 }
     203             : 
     204           0 :                 CmpPtr<ICmpTerrain> cmpTerrain(GetSystemEntity());
     205           0 :                 if (cmpTerrain)
     206             :                 {
     207           0 :                     fixed ground = cmpTerrain->GetGroundLevel(pos.X, pos.Z);
     208           0 :                     m_TotalSinkDepth += std::max(0.f, (pos.Y - ground).ToFloat());
     209             :                 }
     210             : 
     211             :                 // Sink it further down if it sinks like a ship, as it will rotate.
     212           0 :                 if (m_ShipSink)
     213             :                 {
     214             :                     // lacking randomness we'll trick
     215           0 :                     m_SinkingAngleX = (pos.X.ToInt_RoundToNearest() % 30 - 15) / 15.0;
     216           0 :                     m_SinkingAngleZ = (pos.Z.ToInt_RoundToNearest() % 30) / 40.0;
     217           0 :                     m_TotalSinkDepth += 10.f;
     218             :                 }
     219             :                 // probably 0 in both cases but we'll remember it anyway.
     220           0 :                 m_InitialXRotation = cmpPosition->GetRotation().X;
     221           0 :                 m_InitialZRotation = cmpPosition->GetRotation().Z;
     222             :             }
     223             : 
     224           0 :             m_CurrentTime += msgData.deltaSimTime;
     225             : 
     226           0 :             if (m_CurrentTime >= m_DelayTime)
     227             :             {
     228             :                 //If the entity should sink stochastically, use the negative binomial distribution to see if it should sink each frame.
     229           0 :                 if ((m_Stochastic && (m_NextSink-- == 0)) || !m_Stochastic)
     230             :                 {
     231           0 :                     m_NextSink = m_Distribution(m_Generator.value());
     232           0 :                     float t = m_CurrentTime - m_DelayTime;
     233           0 :                     float depth = (m_SinkRate * t) + (m_SinkAccel * t * t);
     234             : 
     235           0 :                     if (m_ShipSink)
     236             :                     {
     237             :                         // exponential sinking with tilting
     238           0 :                         float tilt_time = t > 5.f ? 5.f : t;
     239           0 :                         float tiltSink = tilt_time * tilt_time / 5.f;
     240           0 :                         entity_pos_t RotX = entity_pos_t::FromFloat(((m_InitialXRotation.ToFloat() * (5.f - tiltSink)) + (m_SinkingAngleX * tiltSink)) / 5.f);
     241           0 :                         entity_pos_t RotZ = entity_pos_t::FromFloat(((m_InitialZRotation.ToFloat() * (3.f - tilt_time)) + (m_SinkingAngleZ * tilt_time)) / 3.f);
     242           0 :                         cmpPosition->SetXZRotation(RotX,RotZ);
     243             : 
     244           0 :                         depth = m_SinkRate * (exp(t - 1.f) - 0.54881163609f) + (m_SinkAccel * exp(t - 4.f) - 0.01831563888f);
     245           0 :                         if (depth < 0.f)
     246           0 :                             depth = 0.f;
     247             :                     }
     248             : 
     249           0 :                     cmpPosition->SetHeightOffset(entity_pos_t::FromFloat(-depth));
     250             : 
     251           0 :                     if (depth > m_TotalSinkDepth)
     252           0 :                         GetSimContext().GetComponentManager().DestroyComponentsSoon(GetEntityId());
     253             :                 }
     254             :             }
     255             : 
     256             :             break;
     257           0 :         }
     258             :         }
     259           0 :     }
     260             : };
     261             : 
     262         274 : REGISTER_COMPONENT_TYPE(Decay)

Generated by: LCOV version 1.16