HeightfieldCollider.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #pragma once
  9. #include <AzCore/Jobs/Job.h>
  10. #include <AzCore/std/parallel/condition_variable.h>
  11. #include <AzFramework/Physics/Components/SimulatedBodyComponentBus.h>
  12. #include <AzFramework/Physics/HeightfieldProviderBus.h>
  13. #include <AzFramework/Physics/PhysicsScene.h>
  14. #include <AzFramework/Physics/Shape.h>
  15. #include <PhysX/ColliderShapeBus.h>
  16. namespace PhysX
  17. {
  18. //! PhysX Heightfield Collider base class.
  19. //! This contains all the logic shared between the Editor Heightfield Collider Component and the Heightfield Collider Component
  20. //! to create, update, and destroy the heightfield collider at runtime.
  21. class HeightfieldCollider
  22. : protected AzPhysics::SimulatedBodyComponentRequestsBus::Handler
  23. , protected Physics::HeightfieldProviderNotificationBus::Handler
  24. , protected PhysX::ColliderShapeRequestBus::Handler
  25. {
  26. public:
  27. //! Enum for specifying how Heightfield Collider should be created
  28. enum class DataSource
  29. {
  30. //! Generate a new heightfield using the data from the Terrain System.
  31. GenerateNewHeightfield,
  32. //! Use the cached heightfield data from shape configuration.
  33. //! Usually it comes loaded from a heightfield asset.
  34. UseCachedHeightfield
  35. };
  36. HeightfieldCollider() = default;
  37. ~HeightfieldCollider();
  38. //! Create a HeightfieldCollider that operates on the given set of data.
  39. //! @param entityId The entity Id for the entity that contains this heightfield collider
  40. //! @param entityName The enntity name for the entity that contains this heightfield collider (for debug purposes)
  41. //! @param sceneHandler The physics scene to create the collider in (Editor or runtime)
  42. //! @param colliderConfig The collider configuration to use. Some of its data will get modified based on the heightfield data.
  43. //! @param shapeConfig The shape configuration to use. All of its data will get modified based on the heightfield data.
  44. HeightfieldCollider(
  45. AZ::EntityId entityId,
  46. const AZStd::string& entityName,
  47. AzPhysics::SceneHandle sceneHandle,
  48. AZStd::shared_ptr<Physics::ColliderConfiguration> colliderConfig,
  49. AZStd::shared_ptr<Physics::HeightfieldShapeConfiguration> shapeConfig,
  50. DataSource dataSourceType);
  51. //! Get the currently-spawned heightfield shape.
  52. //! @return Pointer to the heightfield shape.
  53. AZStd::shared_ptr<Physics::Shape> GetHeightfieldShape();
  54. //! Notify the heightfield that it may need to refresh some or all of its data.
  55. //! @param changeMask The types of data changes causing the notification.
  56. //! @param dirtyRegion The area affected by the notification, or a Null Aabb if everything is affected.
  57. void RefreshHeightfield(
  58. Physics::HeightfieldProviderNotifications::HeightfieldChangeMask changeMask,
  59. const AZ::Aabb& dirtyRegion = AZ::Aabb::CreateNull());
  60. //! Get a pointer to the currently-spawned simulated body.
  61. //! @return Pointer to the simulated body.
  62. const AzPhysics::SimulatedBody* GetSimulatedBody() const;
  63. void BlockOnPendingJobs();
  64. // AzPhysics::SimulatedBodyComponentRequestsBus::Handler overrides ...
  65. void EnablePhysics() override;
  66. void DisablePhysics() override;
  67. bool IsPhysicsEnabled() const override;
  68. AZ::Aabb GetAabb() const override;
  69. AzPhysics::SimulatedBody* GetSimulatedBody() override;
  70. AzPhysics::SimulatedBodyHandle GetSimulatedBodyHandle() const override;
  71. AzPhysics::SceneQueryHit RayCast(const AzPhysics::RayCastRequest& request) override;
  72. protected:
  73. // Physics::HeightfieldProviderNotificationBus::Handler overrides ...
  74. void OnHeightfieldDataChanged(
  75. const AZ::Aabb& dirtyRegion, Physics::HeightfieldProviderNotifications::HeightfieldChangeMask changeMask) override;
  76. // ColliderShapeRequestBus
  77. AZ::Aabb GetColliderShapeAabb() override;
  78. bool IsTrigger() override
  79. {
  80. // PhysX Heightfields don't support triggers.
  81. return false;
  82. }
  83. void ClearHeightfield();
  84. void InitStaticRigidBody(const AZ::Transform& baseTransform);
  85. void InitStaticRigidBody();
  86. void UpdateHeightfieldMaterialSlots(const Physics::MaterialSlots& updatedMaterialSlots);
  87. private:
  88. //! Updates a subset of rows in the heightfield shape configuration.
  89. void UpdateShapeConfigRows(
  90. AZ::Job* updateCompleteJob, size_t startColumn, size_t startRow, size_t numColumns, size_t numRows);
  91. //! Updates a subset of rows in the PhysX heightfield based on the data in the heightfield shape configuration.
  92. //! Note that while this takes in column ranges, the expectation is that it is processing all the dirty columns for each
  93. //! row being updated. If this assumption changes, the dirty region tracking logic will also need to change.
  94. void UpdatePhysXHeightfieldRows(
  95. AzPhysics::Scene* scene, AZStd::shared_ptr<Physics::Shape> shape,
  96. size_t startColumn, size_t startRow, size_t numColumns, size_t numRows);
  97. //! Called once all of the asynchronous update jobs have completed.
  98. void RefreshComplete();
  99. //! Helper class to manage the spawned physics update jobs.
  100. class HeightfieldUpdateJobContext : public AZ::JobContext
  101. {
  102. public:
  103. AZ_CLASS_ALLOCATOR(HeightfieldUpdateJobContext, AZ::ThreadPoolAllocator)
  104. HeightfieldUpdateJobContext(AZ::JobManager& jobManager)
  105. : JobContext(jobManager)
  106. {
  107. }
  108. //! Cancel any running jobs
  109. void Cancel();
  110. //! Check to see if the jobs should be canceled.
  111. bool IsCanceled() const;
  112. //! Track that the refresh has been started.
  113. void OnRefreshStart();
  114. //! Track that the refresh has been completed.
  115. void OnRefreshComplete();
  116. //! Block until all jobs have been completed.
  117. void BlockUntilComplete();
  118. private:
  119. //! Track whether or not a refresh is currently happening.
  120. bool m_refreshInProgress = false;
  121. //! Mutex to protect the job-running state
  122. AZStd::mutex m_jobsRunningNotificationMutex;
  123. //! Notification mechanism for knowing when the jobs have stopped running.
  124. //! This uses a condition_variable instead of a semaphore so that there doesn't need to be an equal number of job starts
  125. //! vs "block on complete" calls.
  126. AZStd::condition_variable m_jobsRunning;
  127. //! Track whether or not the currently-running jobs should be canceled.
  128. AZStd::atomic_bool m_isCanceled = false;
  129. };
  130. //! Stores collision layers, whether the collider is a trigger, etc.
  131. AZStd::shared_ptr<Physics::ColliderConfiguration> m_colliderConfig;
  132. //! Stores all of the cached information for the heightfield shape.
  133. AZStd::shared_ptr<Physics::HeightfieldShapeConfiguration> m_shapeConfig;
  134. //! Handle to the body in the provided physics scene.
  135. AzPhysics::SimulatedBodyHandle m_staticRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle;
  136. //! Handle to the provided physics scene.
  137. AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle;
  138. //! Job context for managing the collider update jobs that get spawned.
  139. AZStd::unique_ptr<HeightfieldUpdateJobContext> m_jobContext;
  140. //! Cached entity ID for the entity this collider is attached to.
  141. AZ::EntityId m_entityId;
  142. //! Cached entity name for the entity this collider is attached to.
  143. AZStd::string m_entityName;
  144. //! Track the current dirty region for async heightfield refreshes.
  145. struct DirtyHeightfieldRegion
  146. {
  147. DirtyHeightfieldRegion();
  148. void SetNull();
  149. void AddAabb(const AZ::Aabb& dirtyRegion, AZ::EntityId entityId);
  150. size_t m_minRowVertex; //! the first dirty row vertex
  151. size_t m_minColumnVertex; //! the first dirty column vertex
  152. size_t m_maxRowVertex; //! one past the last dirty row vertex (i.e. max - min = num dirty)
  153. size_t m_maxColumnVertex; //! one past the last dirty column vertex
  154. };
  155. DirtyHeightfieldRegion m_dirtyRegion;
  156. //! Specifies the way of creating Heightfield Collider.
  157. DataSource m_dataSourceType = DataSource::GenerateNewHeightfield;
  158. };
  159. } // namespace PhysX