GradientSurfaceDataComponent.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. #include <GradientSignal/Components/GradientSurfaceDataComponent.h>
  9. #include <AzCore/Debug/Profiler.h>
  10. #include <AzCore/RTTI/BehaviorContext.h>
  11. #include <AzCore/Serialization/EditContext.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <SurfaceData/SurfaceDataSystemRequestBus.h>
  14. #include <SurfaceData/Utility/SurfaceDataUtility.h>
  15. #include <SurfaceData/MixedStackHeapAllocator.h>
  16. namespace GradientSignal
  17. {
  18. void GradientSurfaceDataConfig::Reflect(AZ::ReflectContext* context)
  19. {
  20. AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
  21. if (serialize)
  22. {
  23. serialize->Class<GradientSurfaceDataConfig, AZ::ComponentConfig>()
  24. ->Version(2)
  25. ->Field("ShapeConstraintEntityId", &GradientSurfaceDataConfig::m_shapeConstraintEntityId)
  26. ->Field("ThresholdMin", &GradientSurfaceDataConfig::m_thresholdMin)
  27. ->Field("ThresholdMax", &GradientSurfaceDataConfig::m_thresholdMax)
  28. ->Field("ModifierTags", &GradientSurfaceDataConfig::m_modifierTags)
  29. ;
  30. AZ::EditContext* edit = serialize->GetEditContext();
  31. if (edit)
  32. {
  33. edit->Class<GradientSurfaceDataConfig>(
  34. "Gradient Surface Tag Emitter", "")
  35. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  36. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  37. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  38. ->DataElement(AZ::Edit::UIHandlers::Default, &GradientSurfaceDataConfig::m_shapeConstraintEntityId, "Surface Bounds", "Optionally constrain surface data to the shape on the selected entity")
  39. ->Attribute(AZ::Edit::Attributes::RequiredService, AZ_CRC_CE("ShapeService"))
  40. ->DataElement(AZ::Edit::UIHandlers::Slider, &GradientSurfaceDataConfig::m_thresholdMin, "Threshold Min", "Minimum value accepted from input gradient that allows tags to be applied.")
  41. ->Attribute(AZ::Edit::Attributes::Min, 0.0f)
  42. ->Attribute(AZ::Edit::Attributes::Max, 1.0f)
  43. ->DataElement(AZ::Edit::UIHandlers::Slider, &GradientSurfaceDataConfig::m_thresholdMax, "Threshold Max", "Maximum value accepted from input gradient that allows tags to be applied.")
  44. ->Attribute(AZ::Edit::Attributes::Min, 0.0f)
  45. ->Attribute(AZ::Edit::Attributes::Max, 1.0f)
  46. ->DataElement(0, &GradientSurfaceDataConfig::m_modifierTags, "Extended Tags", "Surface tags to add to contained points")
  47. ;
  48. }
  49. }
  50. if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  51. {
  52. behaviorContext->Class<GradientSurfaceDataConfig>()
  53. ->Attribute(AZ::Script::Attributes::Category, "Vegetation")
  54. ->Constructor()
  55. ->Method("GetNumTags", &GradientSurfaceDataConfig::GetNumTags)
  56. ->Method("GetTag", &GradientSurfaceDataConfig::GetTag)
  57. ->Method("RemoveTag", &GradientSurfaceDataConfig::RemoveTag)
  58. ->Method("AddTag", &GradientSurfaceDataConfig::AddTag)
  59. ->Property("ShapeConstraintEntityId", BehaviorValueProperty(&GradientSurfaceDataConfig::m_shapeConstraintEntityId))
  60. ;
  61. }
  62. }
  63. size_t GradientSurfaceDataConfig::GetNumTags() const
  64. {
  65. return m_modifierTags.size();
  66. }
  67. AZ::Crc32 GradientSurfaceDataConfig::GetTag(int tagIndex) const
  68. {
  69. if (tagIndex < m_modifierTags.size() && tagIndex >= 0)
  70. {
  71. return m_modifierTags[tagIndex];
  72. }
  73. return AZ::Crc32();
  74. }
  75. void GradientSurfaceDataConfig::RemoveTag(int tagIndex)
  76. {
  77. if (tagIndex < m_modifierTags.size() && tagIndex >= 0)
  78. {
  79. m_modifierTags.erase(m_modifierTags.begin() + tagIndex);
  80. }
  81. }
  82. void GradientSurfaceDataConfig::AddTag(AZStd::string tag)
  83. {
  84. m_modifierTags.push_back(SurfaceData::SurfaceTag(tag));
  85. }
  86. void GradientSurfaceDataComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  87. {
  88. services.push_back(AZ_CRC_CE("SurfaceDataModifierService"));
  89. }
  90. void GradientSurfaceDataComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  91. {
  92. services.push_back(AZ_CRC_CE("SurfaceDataModifierService"));
  93. }
  94. void GradientSurfaceDataComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  95. {
  96. services.push_back(AZ_CRC_CE("GradientService"));
  97. }
  98. void GradientSurfaceDataComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& services)
  99. {
  100. // If there's a shape on this entity, start it before this component just in case it's the shape that we're using as our bounds.
  101. services.push_back(AZ_CRC_CE("ShapeService"));
  102. }
  103. void GradientSurfaceDataComponent::Reflect(AZ::ReflectContext* context)
  104. {
  105. GradientSurfaceDataConfig::Reflect(context);
  106. AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context);
  107. if (serialize)
  108. {
  109. serialize->Class<GradientSurfaceDataComponent, AZ::Component>()
  110. ->Version(0)
  111. ->Field("Configuration", &GradientSurfaceDataComponent::m_configuration)
  112. ;
  113. }
  114. if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  115. {
  116. behaviorContext->ConstantProperty("GradientSurfaceDataComponentTypeId", BehaviorConstant(GradientSurfaceDataComponentTypeId))
  117. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  118. ->Attribute(AZ::Script::Attributes::Module, "vegetation")
  119. ;
  120. behaviorContext->Class<GradientSurfaceDataComponent>()->RequestBus("GradientSurfaceDataRequestBus")
  121. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  122. ->Attribute(AZ::Script::Attributes::Module, "vegetation")
  123. ;
  124. behaviorContext->EBus<GradientSurfaceDataRequestBus>("GradientSurfaceDataRequestBus")
  125. ->Attribute(AZ::Script::Attributes::Category, "Vegetation")
  126. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  127. ->Attribute(AZ::Script::Attributes::Module, "vegetation")
  128. ->Event("GetShapeConstraintEntityId", &GradientSurfaceDataRequestBus::Events::GetShapeConstraintEntityId)
  129. ->Event("SetShapeConstraintEntityId", &GradientSurfaceDataRequestBus::Events::SetShapeConstraintEntityId)
  130. ->VirtualProperty("ShapeConstraintEntityId", "GetShapeConstraintEntityId", "SetShapeConstraintEntityId")
  131. ->Event("SetThresholdMin", &GradientSurfaceDataRequestBus::Events::SetThresholdMin)
  132. ->Event("GetThresholdMin", &GradientSurfaceDataRequestBus::Events::GetThresholdMin)
  133. ->VirtualProperty("ThresholdMin", "GetThresholdMin", "SetThresholdMin")
  134. ->Event("SetThresholdMax", &GradientSurfaceDataRequestBus::Events::SetThresholdMax)
  135. ->Event("GetThresholdMax", &GradientSurfaceDataRequestBus::Events::GetThresholdMax)
  136. ->VirtualProperty("ThresholdMax", "GetThresholdMax", "SetThresholdMax")
  137. ->Event("GetNumTags", &GradientSurfaceDataRequestBus::Events::GetNumTags)
  138. ->Event("GetTag", &GradientSurfaceDataRequestBus::Events::GetTag)
  139. ->Event("RemoveTag", &GradientSurfaceDataRequestBus::Events::RemoveTag)
  140. ->Event("AddTag", &GradientSurfaceDataRequestBus::Events::AddTag)
  141. ;
  142. }
  143. }
  144. GradientSurfaceDataComponent::GradientSurfaceDataComponent(const GradientSurfaceDataConfig& configuration)
  145. : m_configuration(configuration)
  146. {
  147. }
  148. void GradientSurfaceDataComponent::Activate()
  149. {
  150. m_gradientSampler.m_gradientId = GetEntityId();
  151. m_gradientSampler.m_ownerEntityId = GetEntityId();
  152. LmbrCentral::DependencyNotificationBus::Handler::BusConnect(GetEntityId());
  153. if (m_configuration.m_shapeConstraintEntityId.IsValid())
  154. {
  155. LmbrCentral::ShapeComponentNotificationsBus::Handler::BusConnect(m_configuration.m_shapeConstraintEntityId);
  156. }
  157. GradientSurfaceDataRequestBus::Handler::BusConnect(GetEntityId());
  158. // Register with the SurfaceData system and update our cached shape information if necessary.
  159. m_modifierHandle = SurfaceData::InvalidSurfaceDataRegistryHandle;
  160. UpdateRegistryAndCache(m_modifierHandle);
  161. SurfaceData::SurfaceDataModifierRequestBus::Handler::BusConnect(m_modifierHandle);
  162. }
  163. void GradientSurfaceDataComponent::Deactivate()
  164. {
  165. GradientSurfaceDataRequestBus::Handler::BusDisconnect();
  166. LmbrCentral::ShapeComponentNotificationsBus::Handler::BusDisconnect();
  167. LmbrCentral::DependencyNotificationBus::Handler::BusDisconnect();
  168. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UnregisterSurfaceDataModifier(m_modifierHandle);
  169. SurfaceData::SurfaceDataModifierRequestBus::Handler::BusDisconnect();
  170. m_modifierHandle = SurfaceData::InvalidSurfaceDataRegistryHandle;
  171. }
  172. bool GradientSurfaceDataComponent::ReadInConfig(const AZ::ComponentConfig* baseConfig)
  173. {
  174. if (auto config = azrtti_cast<const GradientSurfaceDataConfig*>(baseConfig))
  175. {
  176. m_configuration = *config;
  177. return true;
  178. }
  179. return false;
  180. }
  181. bool GradientSurfaceDataComponent::WriteOutConfig(AZ::ComponentConfig* outBaseConfig) const
  182. {
  183. if (auto config = azrtti_cast<GradientSurfaceDataConfig*>(outBaseConfig))
  184. {
  185. *config = m_configuration;
  186. return true;
  187. }
  188. return false;
  189. }
  190. void GradientSurfaceDataComponent::ModifySurfacePoints(
  191. AZStd::span<const AZ::Vector3> positions,
  192. [[maybe_unused]] AZStd::span<const AZ::EntityId> creatorEntityIds,
  193. AZStd::span<SurfaceData::SurfaceTagWeights> weights) const
  194. {
  195. AZ_Assert(
  196. (positions.size() == creatorEntityIds.size()) && (positions.size() == weights.size()),
  197. "Sizes of the passed-in spans don't match");
  198. // If we don't have any modifier tags, there's nothing to modify.
  199. if (m_configuration.m_modifierTags.empty())
  200. {
  201. return;
  202. }
  203. // This method can be called from any thread, but our shape bounds can get updated from the main thread.
  204. // If we have an optional constraining shape bounds, grab a copy of it with minimized mutex lock times. Avoid mutex
  205. // locking entirely if we aren't using the shape bounds option at all.
  206. // (m_validShapeBounds is an atomic bool, so it can be queried outside of the mutex)
  207. AZ::Aabb shapeConstraintBounds = AZ::Aabb::CreateNull();
  208. if (m_validShapeBounds)
  209. {
  210. AZStd::lock_guard<decltype(m_cacheMutex)> lock(m_cacheMutex);
  211. shapeConstraintBounds = m_cachedShapeConstraintBounds;
  212. }
  213. // Optimization: For our temporary vectors, if the input is below a certain size, allocate the temporary data off the stack.
  214. // Otherwise, allocate from the heap.
  215. constexpr size_t SmallQuerySize = 16;
  216. // Start by assuming an unbounded surface modifier and default to allowing *all* points through the shape check.
  217. AZStd::vector<bool, SurfaceData::mixed_stack_heap_allocator<bool, SmallQuerySize>> inBounds;
  218. // If we have an optional shape bounds, adjust the inBounds flags based on whether or not each point is inside the bounds.
  219. if (shapeConstraintBounds.IsValid())
  220. {
  221. LmbrCentral::ShapeComponentRequestsBus::Event(
  222. m_configuration.m_shapeConstraintEntityId,
  223. [positions, shapeConstraintBounds, &inBounds](LmbrCentral::ShapeComponentRequestsBus::Events* shape)
  224. {
  225. inBounds.resize(positions.size(), false);
  226. for (size_t index = 0; index < positions.size(); index++)
  227. {
  228. // Check the AABB first.
  229. if (shapeConstraintBounds.Contains(positions[index]))
  230. {
  231. // The point is in the AABB, so check against the actual shape geometry.
  232. inBounds[index] = shape->IsPointInside(positions[index]);
  233. }
  234. }
  235. });
  236. }
  237. // Get all of the potential gradient values in one bulk call.
  238. AZStd::vector<float, SurfaceData::mixed_stack_heap_allocator<float, SmallQuerySize>> gradientValues(positions.size());
  239. m_gradientSampler.GetValues(positions, gradientValues);
  240. for (size_t index = 0; index < positions.size(); index++)
  241. {
  242. // If the point is within our allowed shape bounds, verify that it meets the gradient thresholds.
  243. // If so, then add the value to the surface tags.
  244. if (inBounds.empty() || inBounds[index])
  245. {
  246. if (gradientValues[index] >= m_configuration.m_thresholdMin && gradientValues[index] <= m_configuration.m_thresholdMax)
  247. {
  248. weights[index].AddSurfaceTagWeights(m_configuration.m_modifierTags, gradientValues[index]);
  249. }
  250. }
  251. }
  252. }
  253. void GradientSurfaceDataComponent::OnCompositionChanged()
  254. {
  255. AZ_PROFILE_FUNCTION(Entity);
  256. UpdateRegistryAndCache(m_modifierHandle);
  257. }
  258. void GradientSurfaceDataComponent::SetThresholdMin(float thresholdMin)
  259. {
  260. m_configuration.m_thresholdMin = thresholdMin;
  261. LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
  262. }
  263. float GradientSurfaceDataComponent::GetThresholdMin() const
  264. {
  265. return m_configuration.m_thresholdMin;
  266. }
  267. void GradientSurfaceDataComponent::SetThresholdMax(float thresholdMax)
  268. {
  269. m_configuration.m_thresholdMax = thresholdMax;
  270. LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
  271. }
  272. float GradientSurfaceDataComponent::GetThresholdMax() const
  273. {
  274. return m_configuration.m_thresholdMax;
  275. }
  276. size_t GradientSurfaceDataComponent::GetNumTags() const
  277. {
  278. return m_configuration.GetNumTags();
  279. }
  280. AZ::Crc32 GradientSurfaceDataComponent::GetTag(int tagIndex) const
  281. {
  282. return m_configuration.GetTag(tagIndex);
  283. }
  284. void GradientSurfaceDataComponent::RemoveTag(int tagIndex)
  285. {
  286. m_configuration.RemoveTag(tagIndex);
  287. LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
  288. }
  289. void GradientSurfaceDataComponent::AddTag(AZStd::string tag)
  290. {
  291. m_configuration.AddTag(tag);
  292. LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
  293. }
  294. void GradientSurfaceDataComponent::UpdateRegistryAndCache(SurfaceData::SurfaceDataRegistryHandle& registryHandle)
  295. {
  296. // Set up the registry information for this component.
  297. SurfaceData::SurfaceDataRegistryEntry registryEntry;
  298. registryEntry.m_entityId = GetEntityId();
  299. registryEntry.m_tags = m_configuration.m_modifierTags;
  300. registryEntry.m_bounds = AZ::Aabb::CreateNull();
  301. LmbrCentral::ShapeComponentRequestsBus::EventResult(registryEntry.m_bounds, m_configuration.m_shapeConstraintEntityId, &LmbrCentral::ShapeComponentRequestsBus::Events::GetEncompassingAabb);
  302. // Update our cached shape bounds within a mutex lock so that we don't have data contention
  303. // with ModifySurfacePoints() on the vegetation thread.
  304. {
  305. AZStd::lock_guard<decltype(m_cacheMutex)> lock(m_cacheMutex);
  306. // Cache our new shape bounds so that we don't have to look it up for every surface point.
  307. m_cachedShapeConstraintBounds = registryEntry.m_bounds;
  308. // Separately keep track of whether or not the bounds are valid in an atomic bool so that we can easily check
  309. // validity without requiring the mutex.
  310. m_validShapeBounds = m_cachedShapeConstraintBounds.IsValid();
  311. }
  312. // If this is our first time calling this, we need to register with the SurfaceData system. On subsequent
  313. // calls, just update the entry that already exists.
  314. if (registryHandle == SurfaceData::InvalidSurfaceDataRegistryHandle)
  315. {
  316. // Register with the SurfaceData system and get a valid registryHandle.
  317. registryHandle = AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->RegisterSurfaceDataModifier(registryEntry);
  318. }
  319. else
  320. {
  321. // Update the registry entry with the SurfaceData system using the existing registryHandle.
  322. AZ::Interface<SurfaceData::SurfaceDataSystem>::Get()->UpdateSurfaceDataModifier(registryHandle, registryEntry);
  323. }
  324. }
  325. void GradientSurfaceDataComponent::OnShapeChanged([[maybe_unused]] LmbrCentral::ShapeComponentNotifications::ShapeChangeReasons reasons)
  326. {
  327. LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
  328. }
  329. AZ::EntityId GradientSurfaceDataComponent::GetShapeConstraintEntityId() const
  330. {
  331. return m_configuration.m_shapeConstraintEntityId;
  332. }
  333. void GradientSurfaceDataComponent::SetShapeConstraintEntityId(AZ::EntityId entityId)
  334. {
  335. if (m_configuration.m_shapeConstraintEntityId != entityId)
  336. {
  337. m_configuration.m_shapeConstraintEntityId = entityId;
  338. LmbrCentral::ShapeComponentNotificationsBus::Handler::BusDisconnect();
  339. if (m_configuration.m_shapeConstraintEntityId.IsValid())
  340. {
  341. LmbrCentral::ShapeComponentNotificationsBus::Handler::BusConnect(m_configuration.m_shapeConstraintEntityId);
  342. }
  343. // If our shape constraint entity has changed, trigger a notification that our component's composition has changed.
  344. // This will lead to a refresh of any surface data that this component intersects with.
  345. LmbrCentral::DependencyNotificationBus::Event(GetEntityId(), &LmbrCentral::DependencyNotificationBus::Events::OnCompositionChanged);
  346. }
  347. }
  348. }