EnergyBallComponent.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  3. *
  4. * SPDX-License-Identifier: Apache-2.0 OR MIT
  5. *
  6. */
  7. #include <Source/Components/Multiplayer/EnergyBallComponent.h>
  8. #include <Source/AutoGen/NetworkHealthComponent.AutoComponent.h>
  9. #include <Multiplayer/Components/NetworkTransformComponent.h>
  10. #include <Multiplayer/Components/NetworkRigidBodyComponent.h>
  11. #include <MultiplayerSampleTypes.h>
  12. #include <AzCore/Component/TransformBus.h>
  13. #include <AzCore/EBus/IEventScheduler.h>
  14. #include <AzFramework/Physics/Components/SimulatedBodyComponentBus.h>
  15. #include <AzFramework/Physics/RigidBodyBus.h>
  16. #include <WeaponNotificationBus.h>
  17. #if AZ_TRAIT_CLIENT
  18. # include <PopcornFX/PopcornFXBus.h>
  19. # include <DebugDraw/DebugDrawBus.h>
  20. #endif
  21. namespace MultiplayerSample
  22. {
  23. AZ_CVAR(float, sv_EnergyBallImpulseScalar, 500.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "A fudge factor for imparting impulses on rigid bodies due to weapon hits");
  24. AZ_CVAR(bool, cl_EnergyBallDebugDraw, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "When turned on this will draw the current energy ball location");
  25. void EnergyBallComponent::Reflect(AZ::ReflectContext* context)
  26. {
  27. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  28. if (serializeContext)
  29. {
  30. serializeContext->Class<EnergyBallComponent, EnergyBallComponentBase>()
  31. ->Version(1);
  32. }
  33. EnergyBallComponentBase::Reflect(context);
  34. }
  35. void EnergyBallComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  36. {
  37. m_effect = GetExplosionEffect();
  38. m_effect.Initialize();
  39. #if AZ_TRAIT_CLIENT
  40. BallActiveAddEvent(m_ballActiveHandler);
  41. #endif
  42. }
  43. void EnergyBallComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  44. {
  45. #if AZ_TRAIT_CLIENT
  46. m_ballActiveHandler.Disconnect();
  47. #endif
  48. }
  49. #if AZ_TRAIT_CLIENT
  50. void EnergyBallComponent::OnBallActiveChanged(bool active)
  51. {
  52. if (active)
  53. {
  54. bool startSuccess = false;
  55. // Set to true to call "Kill" which is deferred, or false to call "Terminate" which is immediate.
  56. constexpr bool KillOnRestart = true;
  57. PopcornFX::PopcornFXEmitterComponentRequestBus::EventResult(startSuccess,
  58. GetEntity()->GetId(), &PopcornFX::PopcornFXEmitterComponentRequestBus::Events::Restart, KillOnRestart);
  59. AZ_Error("EnergyBall", startSuccess, "Restart call for Energy Ball was unsuccessful.");
  60. if (cl_EnergyBallDebugDraw)
  61. {
  62. m_debugDrawEvent.Enqueue(AZ::TimeMs{ 0 }, true);
  63. }
  64. }
  65. else
  66. {
  67. // Crate an explosion effect wherever the ball was last at.
  68. m_effect.TriggerEffect(GetEntity()->GetTransform()->GetWorldTM());
  69. bool killSuccess = false;
  70. // This would ideally use Kill instead of Terminate, but there is a bug in PopcornFX 2.15.4 that if Kill is
  71. // called on the first tick (which can happen), then the effect will get stuck in a permanent waiting-to-die state,
  72. // and no amount of Restart calls will ever make it show up again.
  73. PopcornFX::PopcornFXEmitterComponentRequestBus::EventResult(killSuccess,
  74. GetEntity()->GetId(), &PopcornFX::PopcornFXEmitterComponentRequestBus::Events::Terminate);
  75. AZ_Error("EnergyBall", killSuccess, "Kill call for Energy Ball was unsuccessful.");
  76. m_debugDrawEvent.RemoveFromQueue();
  77. }
  78. }
  79. void EnergyBallComponent::HandleRPC_BallExplosion([[maybe_unused]] AzNetworking::IConnection* invokingConnection, const HitEvent& hitEvent)
  80. {
  81. // Create an explosion effect at our current location.
  82. m_effect.TriggerEffect(GetEntity()->GetTransform()->GetWorldTM());
  83. // Notify every entity that was hit that they've received a weapon impact, this allows for blast decals.
  84. for (const HitEntity& hitEntity : hitEvent.m_hitEntities)
  85. {
  86. const AZ::Transform hitTransform = AZ::Transform::CreateLookAt(hitEntity.m_hitPosition, hitEntity.m_hitPosition + hitEntity.m_hitNormal, AZ::Transform::Axis::ZPositive);
  87. const Multiplayer::ConstNetworkEntityHandle handle = Multiplayer::GetNetworkEntityManager()->GetEntity(hitEntity.m_hitNetEntityId);
  88. const AZ::EntityId hitEntityId = handle.Exists() ? handle.GetEntity()->GetId() : AZ::EntityId();
  89. WeaponNotificationBus::Broadcast(&WeaponNotificationBus::Events::OnWeaponImpact, GetEntity()->GetId(), hitTransform, hitEntityId);
  90. }
  91. }
  92. void EnergyBallComponent::DebugDraw()
  93. {
  94. if (cl_EnergyBallDebugDraw)
  95. {
  96. // Each draw only lasts one frame.
  97. constexpr float DrawDuration = 0.0f;
  98. auto* shapeConfig = GetGatherParams().GetCurrentShapeConfiguration();
  99. if (shapeConfig->GetShapeType() == Physics::ShapeType::Sphere)
  100. {
  101. const Physics::SphereShapeConfiguration* sphere = static_cast<const Physics::SphereShapeConfiguration*>(shapeConfig);
  102. float debugRadius = sphere->m_radius;
  103. DebugDraw::DebugDrawRequestBus::Broadcast(
  104. &DebugDraw::DebugDrawRequestBus::Events::DrawSphereAtLocation,
  105. GetEntity()->GetTransform()->GetWorldTM().GetTranslation(),
  106. debugRadius,
  107. AZ::Colors::Green,
  108. DrawDuration
  109. );
  110. }
  111. else if (shapeConfig->GetShapeType() == Physics::ShapeType::Box)
  112. {
  113. const Physics::BoxShapeConfiguration* box = static_cast<const Physics::BoxShapeConfiguration*>(shapeConfig);
  114. AZ::Obb obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(
  115. GetEntity()->GetTransform()->GetWorldTM().GetTranslation(),
  116. GetEntity()->GetTransform()->GetWorldTM().GetRotation(),
  117. box->m_dimensions / 2.0f
  118. );
  119. DebugDraw::DebugDrawRequestBus::Broadcast(
  120. &DebugDraw::DebugDrawRequestBus::Events::DrawObb,
  121. obb,
  122. AZ::Colors::Green,
  123. DrawDuration
  124. );
  125. }
  126. else if (shapeConfig->GetShapeType() == Physics::ShapeType::Capsule)
  127. {
  128. AZ_Error("EnergyBall", false, "Capsule shape type not currently supported with energy ball debug visualization.");
  129. }
  130. }
  131. }
  132. #endif
  133. EnergyBallComponentController::EnergyBallComponentController(EnergyBallComponent& parent)
  134. : EnergyBallComponentControllerBase(parent)
  135. {
  136. }
  137. void EnergyBallComponentController::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  138. {
  139. #if AZ_TRAIT_SERVER
  140. SetBallActive(false);
  141. #endif
  142. }
  143. void EnergyBallComponentController::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  144. {
  145. #if AZ_TRAIT_SERVER
  146. SetBallActive(false);
  147. #endif
  148. }
  149. #if AZ_TRAIT_SERVER
  150. void EnergyBallComponentController::HandleRPC_LaunchBall(AzNetworking::IConnection* invokingConnection, const AZ::Vector3& startingPosition, const AZ::Vector3& direction, const Multiplayer::NetEntityId& owningNetEntityId)
  151. {
  152. if (GetBallActive())
  153. {
  154. return;
  155. }
  156. m_collisionCheckEvent.Enqueue(AZ::TimeMs{ 10 }, true);
  157. SetBallActive(true);
  158. SetVelocity(direction * GetGatherParams().m_travelSpeed);
  159. m_hitEvent.m_hitEntities.clear();
  160. m_filteredNetEntityIds.clear();
  161. m_filteredNetEntityIds.insert(owningNetEntityId);
  162. m_filteredNetEntityIds.insert(GetNetEntityId());
  163. m_direction = direction;
  164. // Move the entity to the start position
  165. GetNetworkTransformComponentController()->HandleMultiplayerTeleport(invokingConnection, startingPosition);
  166. // We want to sweep our transform during intersect tests to avoid the ball tunneling through targets
  167. m_lastSweepTransform = GetEntity()->GetTransform()->GetWorldTM();
  168. // Enqueue our kill event
  169. m_killEvent.Enqueue(GetLifetimeMs(), false);
  170. }
  171. void EnergyBallComponentController::CheckForCollisions()
  172. {
  173. if (!GetBallActive())
  174. {
  175. return;
  176. }
  177. const AZ::Vector3& position = GetEntity()->GetTransform()->GetWorldTM().GetTranslation();
  178. const HitEffect& effect = GetHitEffect();
  179. // Sweep from our last checked transform to our current position to avoid tunneling
  180. const ActivateEvent activateEvent{ m_lastSweepTransform, position, m_shooterNetEntityId, GetNetEntityId() };
  181. IntersectResults results;
  182. GatherEntities(GetGatherParams(), activateEvent, m_filteredNetEntityIds, results);
  183. if (!results.empty())
  184. {
  185. for (const IntersectResult& result : results)
  186. {
  187. const HitEntity hitEntity{ result.m_position, result.m_normal, result.m_netEntityId };
  188. m_hitEvent.m_hitEntities.emplace_back(hitEntity);
  189. const Multiplayer::ConstNetworkEntityHandle handle = Multiplayer::GetNetworkEntityManager()->GetEntity(result.m_netEntityId);
  190. if (handle.Exists())
  191. {
  192. // Presently set to 1 until we capture falloff range
  193. float hitDistance = 1.f;
  194. float maxDistance = 1.f;
  195. float damage = effect.m_hitMagnitude * powf((effect.m_hitFalloff * (1.0f - hitDistance / maxDistance)), effect.m_hitExponent);
  196. // Look for physics rigid body component and make impact updates
  197. if (Multiplayer::NetworkRigidBodyComponent* rigidBodyComponent = handle.GetEntity()->FindComponent<Multiplayer::NetworkRigidBodyComponent>())
  198. {
  199. const AZ::Vector3 explosionCentre = position;
  200. const AZ::Vector3 hitObject = handle.GetEntity()->GetTransform()->GetWorldTM().GetTranslation();
  201. const AZ::Vector3 impulse = (hitObject - position).GetNormalized() * damage * sv_EnergyBallImpulseScalar;
  202. rigidBodyComponent->SendApplyImpulse(impulse, position);
  203. }
  204. // Look for health component and directly update health based on hit parameters
  205. if (NetworkHealthComponent* healthComponent = handle.GetEntity()->FindComponent<NetworkHealthComponent>())
  206. {
  207. healthComponent->SendHealthDelta(damage * -1.0f);
  208. }
  209. }
  210. }
  211. KillEnergyBall();
  212. }
  213. // Update our last sweep transform for the next time we check collision
  214. m_lastSweepTransform = GetEntity()->GetTransform()->GetWorldTM();
  215. }
  216. void EnergyBallComponentController::KillEnergyBall()
  217. {
  218. if (!GetBallActive())
  219. {
  220. return;
  221. }
  222. SetBallActive(false);
  223. m_collisionCheckEvent.RemoveFromQueue();
  224. m_hitEvent.m_target = GetEntity()->GetTransform()->GetWorldTM().GetTranslation();
  225. m_hitEvent.m_shooterNetEntityId = m_shooterNetEntityId;
  226. m_hitEvent.m_projectileNetEntityId = GetNetEntityId();
  227. RPC_BallExplosion(m_hitEvent);
  228. // Wait 5 seconds before cleaning up the entity so that the explosion effect has a chance to play out
  229. // Capture just the netEntityId in case we have a level change or some other operation that clears out entities before our lamda triggers
  230. const Multiplayer::NetEntityId netEntityId = GetNetEntityId();
  231. AZ::Interface<AZ::IEventScheduler>::Get()->AddCallback([netEntityId]
  232. {
  233. // Fetch the entity handle, ensure its still valid
  234. const Multiplayer::ConstNetworkEntityHandle entityHandle = Multiplayer::GetNetworkEntityManager()->GetEntity(netEntityId);
  235. if (entityHandle.Exists())
  236. {
  237. Multiplayer::GetNetworkEntityManager()->MarkForRemoval(entityHandle);
  238. }
  239. },
  240. AZ::Name("Cleanup"),
  241. AZ::TimeMs{ 5000 }
  242. );
  243. }
  244. #endif
  245. }