TerrainDetailMaterialManager.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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 <TerrainRenderer/TerrainDetailMaterialManager.h>
  9. #include <TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.h>
  10. #include <AzCore/Console/Console.h>
  11. #include <AzCore/std/parallel/semaphore.h>
  12. #include <Atom/RHI/RHISystemInterface.h>
  13. #include <Atom/RPI.Public/Image/AttachmentImagePool.h>
  14. #include <Atom/RPI.Public/Image/ImageSystemInterface.h>
  15. #include <Atom/RPI.Public/Shader/ShaderSystemInterface.h>
  16. #include <Atom/Utils/MaterialUtils.h>
  17. #include <SurfaceData/SurfaceDataSystemRequestBus.h>
  18. #include <SurfaceData/Utility/SurfaceDataUtility.h>
  19. namespace Terrain
  20. {
  21. namespace
  22. {
  23. [[maybe_unused]] static const char* TerrainDetailMaterialManagerName = "TerrainDetailMaterialManager";
  24. static const char* TerrainDetailChars = "TerrainDetail";
  25. }
  26. namespace DetailMaterialInputs
  27. {
  28. static const char* const BaseColorColor("baseColor.color");
  29. static const char* const BaseColorMap("baseColor.textureMap");
  30. static const char* const BaseColorUseTexture("baseColor.useTexture");
  31. static const char* const BaseColorFactor("baseColor.factor");
  32. static const char* const BaseColorBlendMode("baseColor.textureBlendMode");
  33. static const char* const MetallicMap("metallic.textureMap");
  34. static const char* const MetallicUseTexture("metallic.useTexture");
  35. static const char* const MetallicFactor("metallic.factor");
  36. static const char* const RoughnessMap("roughness.textureMap");
  37. static const char* const RoughnessUseTexture("roughness.useTexture");
  38. static const char* const RoughnessFactor("roughness.factor");
  39. static const char* const RoughnessLowerBound("roughness.lowerBound");
  40. static const char* const RoughnessUpperBound("roughness.upperBound");
  41. static const char* const SpecularF0Map("specularF0.textureMap");
  42. static const char* const SpecularF0UseTexture("specularF0.useTexture");
  43. static const char* const SpecularF0Factor("specularF0.factor");
  44. static const char* const NormalMap("normal.textureMap");
  45. static const char* const NormalUseTexture("normal.useTexture");
  46. static const char* const NormalFactor("normal.factor");
  47. static const char* const NormalFlipX("normal.flipX");
  48. static const char* const NormalFlipY("normal.flipY");
  49. static const char* const DiffuseOcclusionMap("occlusion.diffuseTextureMap");
  50. static const char* const DiffuseOcclusionUseTexture("occlusion.diffuseUseTexture");
  51. static const char* const DiffuseOcclusionFactor("occlusion.diffuseFactor");
  52. static const char* const HeightMap("parallax.textureMap");
  53. static const char* const HeightUseTexture("parallax.useTexture");
  54. static const char* const ParallaxHeightFactor("parallax.factor");
  55. static const char* const ParallaxHeightOffset("parallax.offset");
  56. static const char* const TerrainSettingsOverrideParallax("terrain.overrideParallaxSettings");
  57. static const char* const TerrainHeightFactor("terrain.heightScale");
  58. static const char* const TerrainHeightOffset("terrain.heightOffset");
  59. static const char* const HeightBlendFactor("terrain.blendFactor");
  60. static const char* const HeightWeightClampFactor("terrain.weightClampFactor");
  61. static const char* const UvCenter("uv.center");
  62. static const char* const UvScale("uv.scale");
  63. static const char* const UvTileU("uv.tileU");
  64. static const char* const UvTileV("uv.tileV");
  65. static const char* const UvOffsetU("uv.offsetU");
  66. static const char* const UvOffsetV("uv.offsetV");
  67. static const char* const UvRotateDegrees("uv.rotateDegrees");
  68. }
  69. namespace TerrainSrgInputs
  70. {
  71. static const char* const DetailMaterialIdImage("m_detailMaterialIdImage");
  72. static const char* const DetailMaterialData("m_detailMaterialData");
  73. static const char* const DetailMaterialScale("m_detailMaterialIdScale");
  74. }
  75. AZ_CVAR(bool,
  76. r_terrainDebugDetailMaterials,
  77. false,
  78. [](const bool& value)
  79. {
  80. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(AZ::Name{ "o_debugDetailMaterialIds" }, AZ::RPI::ShaderOptionValue{ value });
  81. },
  82. AZ::ConsoleFunctorFlags::Null,
  83. "Turns on debugging for detail material ids for terrain."
  84. );
  85. AZ_CVAR(bool,
  86. r_terrainDebugDetailImageUpdates,
  87. false,
  88. nullptr,
  89. AZ::ConsoleFunctorFlags::Null,
  90. "Turns on debugging for detail material update regions for terrain."
  91. );
  92. void TerrainDetailMaterialManager::Initialize(
  93. const AZ::Data::Instance<AZ::RPI::ShaderResourceGroup>& terrainSrg,
  94. const AZ::Data::Instance<AZ::RPI::Material>& terrainMaterial)
  95. {
  96. AZ_Error(TerrainDetailMaterialManagerName, terrainSrg, "terrainSrg must not be null.");
  97. AZ_Error(TerrainDetailMaterialManagerName, !m_isInitialized, "Already initialized.");
  98. if (!terrainSrg || m_isInitialized)
  99. {
  100. return;
  101. }
  102. auto deviceCount = AZ::RHI::RHISystemInterface::Get()->GetDeviceCount();
  103. for (auto deviceIndex{0}; deviceIndex < deviceCount; ++deviceIndex)
  104. {
  105. if (terrainSrg->GetRHIShaderResourceGroup()->IsDeviceSet(deviceIndex))
  106. {
  107. m_detailMaterialShaderData[deviceIndex] = {};
  108. }
  109. }
  110. m_terrainMaterial = terrainMaterial;
  111. UpdateTerrainMaterial();
  112. InitializePassthroughDetailMaterial();
  113. InitializeTextureParams();
  114. if (UpdateSrgIndices(terrainSrg))
  115. {
  116. // Find any detail material areas that have already been created.
  117. TerrainAreaMaterialRequestBus::EnumerateHandlers(
  118. [&](TerrainAreaMaterialRequests* handler)
  119. {
  120. const AZ::Aabb& bounds = handler->GetTerrainSurfaceMaterialRegion();
  121. const AZStd::vector<TerrainSurfaceMaterialMapping> materialMappings = handler->GetSurfaceMaterialMappings();
  122. AZ::EntityId entityId = *(Terrain::TerrainAreaMaterialRequestBus::GetCurrentBusId());
  123. DetailMaterialListRegion& materialRegion = FindOrCreateByEntityId(entityId, m_detailMaterialRegions);
  124. materialRegion.m_region = bounds;
  125. if (handler->GetDefaultMaterial().m_materialInstance)
  126. {
  127. OnTerrainDefaultSurfaceMaterialCreated(entityId, handler->GetDefaultMaterial().m_materialInstance);
  128. }
  129. for (const auto& materialMapping : materialMappings)
  130. {
  131. if (materialMapping.m_materialInstance)
  132. {
  133. OnTerrainSurfaceMaterialMappingCreated(entityId, materialMapping.m_surfaceTag, materialMapping.m_materialInstance);
  134. }
  135. }
  136. return true;
  137. }
  138. );
  139. TerrainAreaMaterialNotificationBus::Handler::BusConnect();
  140. AZ::Aabb worldBounds = AZ::Aabb::CreateNull();
  141. AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(
  142. worldBounds, &AzFramework::Terrain::TerrainDataRequests::GetTerrainAabb);
  143. OnTerrainDataChanged(worldBounds, TerrainDataChangedMask::SurfaceData);
  144. AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusConnect();
  145. m_isInitialized = true;
  146. }
  147. }
  148. bool TerrainDetailMaterialManager::UpdateSrgIndices(const AZ::Data::Instance<AZ::RPI::ShaderResourceGroup>& terrainSrg)
  149. {
  150. const AZ::RHI::ShaderResourceGroupLayout* terrainSrgLayout = terrainSrg->GetLayout();
  151. m_detailMaterialIdPropertyIndex = terrainSrgLayout->FindShaderInputImageIndex(AZ::Name(TerrainSrgInputs::DetailMaterialIdImage));
  152. AZ_Error(TerrainDetailMaterialManagerName, m_detailMaterialIdPropertyIndex.IsValid(), "Failed to find terrain srg input constant %s.", TerrainSrgInputs::DetailMaterialIdImage);
  153. m_detailScalePropertyIndex = terrainSrgLayout->FindShaderInputConstantIndex(AZ::Name(TerrainSrgInputs::DetailMaterialScale));
  154. AZ_Error(TerrainDetailMaterialManagerName, m_detailScalePropertyIndex.IsValid(), "Failed to find terrain srg input constant %s.", TerrainSrgInputs::DetailMaterialScale);
  155. // Set up the gpu buffer for detail material data
  156. AZ::Render::GpuBufferHandler::Descriptor desc;
  157. desc.m_bufferName = "Detail Material Data";
  158. desc.m_bufferSrgName = TerrainSrgInputs::DetailMaterialData;
  159. desc.m_elementSize = sizeof(DetailMaterialShaderData);
  160. desc.m_srgLayout = terrainSrgLayout;
  161. m_detailMaterialDataBuffer = AZ::Render::GpuBufferHandler(desc);
  162. bool IndicesValid =
  163. m_detailMaterialIdPropertyIndex.IsValid() &&
  164. m_detailScalePropertyIndex.IsValid();
  165. m_detailImageNeedsUpdate = true;
  166. m_detailMaterialBufferNeedsUpdate = true;
  167. return IndicesValid && m_detailMaterialDataBuffer.IsValid();
  168. }
  169. bool TerrainDetailMaterialManager::IsInitialized() const
  170. {
  171. return m_isInitialized;
  172. }
  173. void TerrainDetailMaterialManager::Reset()
  174. {
  175. m_detailTextureImage = {};
  176. m_detailMaterials.Clear();
  177. m_detailMaterialRegions.Clear();
  178. m_detailMaterialShaderIndex.Clear();
  179. m_detailMaterialDataBuffer.Release();
  180. for (auto& [deviceIndex, data] : m_detailMaterialShaderData)
  181. {
  182. data.clear();
  183. }
  184. m_dirtyDetailRegion = AZ::Aabb::CreateNull();
  185. m_detailMaterialBufferNeedsUpdate = false;
  186. m_detailImageNeedsUpdate = false;
  187. TerrainAreaMaterialNotificationBus::Handler::BusDisconnect();
  188. AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusDisconnect();
  189. m_isInitialized = false;
  190. }
  191. void TerrainDetailMaterialManager::Update(const AZ::Vector3& cameraPosition, AZ::Data::Instance<AZ::RPI::ShaderResourceGroup>& terrainSrg)
  192. {
  193. if (m_terrainMaterial->NeedsCompile())
  194. {
  195. UpdateTerrainMaterial();
  196. }
  197. if (m_detailMaterialBufferNeedsUpdate)
  198. {
  199. m_detailMaterialBufferNeedsUpdate = false;
  200. AZStd::unordered_map<int, const void*> rawData;
  201. for (auto& [deviceIndex, data] : m_detailMaterialShaderData)
  202. {
  203. rawData[deviceIndex] = data.data();
  204. }
  205. m_detailMaterialDataBuffer.UpdateBuffer(rawData, aznumeric_cast<uint32_t>(m_detailMaterialShaderIndex.GetSize()));
  206. }
  207. CheckUpdateDetailTexture(cameraPosition);
  208. if (m_detailImageNeedsUpdate)
  209. {
  210. terrainSrg->SetConstant(m_detailScalePropertyIndex, 1.0f / m_detailTextureScale);
  211. terrainSrg->SetImage(m_detailMaterialIdPropertyIndex, m_detailTextureImage);
  212. m_detailMaterialDataBuffer.UpdateSrg(terrainSrg.get());
  213. m_detailImageNeedsUpdate = false;
  214. }
  215. }
  216. void TerrainDetailMaterialManager::InitializeTextureParams()
  217. {
  218. AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(
  219. m_detailTextureScale, &AzFramework::Terrain::TerrainDataRequests::GetTerrainSurfaceDataQueryResolution);
  220. // Texture size needs to be twice the render distance because the camera is positioned in the middle of the texture.
  221. // Clamp the value to be at least 1 pixel in size in case the render distance is smaller than the detail texture scale.
  222. m_detailTextureSize = AZStd::max(1, static_cast<int32_t>(lroundf(m_config.m_renderDistance / m_detailTextureScale) * 2));
  223. ClipmapBoundsDescriptor desc;
  224. desc.m_clipmapUpdateMultiple = 1;
  225. desc.m_clipmapToWorldScale = m_detailTextureScale;
  226. desc.m_size = m_detailTextureSize;
  227. // Initialize world space to a value that won't match the initial camera position.
  228. desc.m_worldSpaceCenter = AZ::Vector2(AZStd::numeric_limits<float>::max(), 0.0f);
  229. m_detailMaterialIdBounds = ClipmapBounds(desc);
  230. m_detailTextureImage = {}; // Force the image to rebuild
  231. m_detailImageNeedsUpdate = true;
  232. }
  233. void TerrainDetailMaterialManager::UpdateTerrainMaterial()
  234. {
  235. AZ::RPI::MaterialPropertyIndex detailTextureMultiplierIndex = m_terrainMaterial->FindPropertyIndex(AZ::Name("settings.detailTextureMultiplier"));
  236. AZ::RPI::MaterialPropertyIndex detailTextureFadeDistanceIndex = m_terrainMaterial->FindPropertyIndex(AZ::Name("settings.detailFadeDistance"));
  237. AZ::RPI::MaterialPropertyIndex detailTextureFadeLengthIndex = m_terrainMaterial->FindPropertyIndex(AZ::Name("settings.detailFadeLength"));
  238. AZ_Assert(detailTextureMultiplierIndex.IsValid(), "Terrain Feature Processor unable to find settings.detailTextureMultiplier in the terrain material.");
  239. AZ_Assert(detailTextureFadeDistanceIndex.IsValid(), "Terrain Feature Processor unable to find settings.detailFadeDistance in the terrain material.");
  240. AZ_Assert(detailTextureFadeLengthIndex.IsValid(), "Terrain Feature Processor unable to find settings.detailFadeLength in the terrain material.");
  241. m_terrainMaterial->SetPropertyValue(detailTextureMultiplierIndex, m_config.m_scale);
  242. m_terrainMaterial->SetPropertyValue(detailTextureFadeDistanceIndex, AZStd::GetMax<float>(0.0f, m_config.m_renderDistance - m_config.m_fadeDistance));
  243. m_terrainMaterial->SetPropertyValue(detailTextureFadeLengthIndex, m_config.m_fadeDistance);
  244. }
  245. void TerrainDetailMaterialManager::SetDetailMaterialConfiguration(const DetailMaterialConfiguration& config)
  246. {
  247. m_config = config;
  248. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(
  249. AZ::Name{ "o_terrainUseHeightBasedBlending" },
  250. AZ::RPI::ShaderOptionValue{ m_config.m_useHeightBasedBlending }
  251. );
  252. if (IsInitialized())
  253. {
  254. UpdateTerrainMaterial();
  255. InitializeTextureParams();
  256. }
  257. }
  258. void TerrainDetailMaterialManager::OnTerrainDataChanged(const AZ::Aabb& dirtyRegion, TerrainDataChangedMask dataChangedMask)
  259. {
  260. if ((dataChangedMask & TerrainDataChangedMask::SurfaceData) == TerrainDataChangedMask::SurfaceData)
  261. {
  262. m_dirtyDetailRegion.AddAabb(dirtyRegion);
  263. }
  264. if ((dataChangedMask & TerrainDataChangedMask::Settings) == TerrainDataChangedMask::Settings)
  265. {
  266. InitializeTextureParams();
  267. }
  268. }
  269. bool TerrainDetailMaterialManager::ForSurfaceTag(DetailMaterialListRegion& materialRegion,
  270. SurfaceData::SurfaceTag surfaceTag, DefaultMaterialSurfaceCallback callback)
  271. {
  272. for (DetailMaterialSurface& surface : materialRegion.m_materialsForSurfaces)
  273. {
  274. if (surface.m_surfaceTag == surfaceTag)
  275. {
  276. callback(surface);
  277. return true;
  278. }
  279. }
  280. return false;
  281. }
  282. void TerrainDetailMaterialManager::OnTerrainDefaultSurfaceMaterialCreated(AZ::EntityId entityId, MaterialInstance material)
  283. {
  284. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  285. if (materialRegion == nullptr)
  286. {
  287. AZ_Assert(false, "OnTerrainDefaultSurfaceMaterialCreated() called for region that doesn't exist.");
  288. return;
  289. }
  290. AZ_Error("TerrainDetailMaterialManager", materialRegion->m_defaultDetailMaterialId == InvalidDetailMaterialId,
  291. "Default detail material created but was already set for this region.");
  292. materialRegion->m_defaultDetailMaterialId = CreateOrUpdateDetailMaterial(material);
  293. m_detailMaterials.GetData(materialRegion->m_defaultDetailMaterialId).m_refCount++;
  294. m_dirtyDetailRegion.AddAabb(materialRegion->m_region);
  295. }
  296. void TerrainDetailMaterialManager::OnTerrainDefaultSurfaceMaterialDestroyed(AZ::EntityId entityId)
  297. {
  298. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  299. if (materialRegion == nullptr)
  300. {
  301. AZ_Assert(false, "OnTerrainDefaultSurfaceMaterialDestroyed() called for region that doesn't exist.");
  302. return;
  303. }
  304. if (materialRegion->m_defaultDetailMaterialId == InvalidDetailMaterialId)
  305. {
  306. AZ_Assert(false, "OnTerrainDefaultSurfaceMaterialDestroyed() called for a region without a default material");
  307. return;
  308. }
  309. CheckDetailMaterialForDeletion(materialRegion->m_defaultDetailMaterialId);
  310. materialRegion->m_defaultDetailMaterialId = InvalidDetailMaterialId;
  311. m_dirtyDetailRegion.AddAabb(materialRegion->m_region);
  312. }
  313. void TerrainDetailMaterialManager::OnTerrainDefaultSurfaceMaterialChanged(AZ::EntityId entityId, MaterialInstance newMaterial)
  314. {
  315. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  316. if (materialRegion == nullptr)
  317. {
  318. AZ_Assert(false, "OnTerrainDefaultSurfaceMaterialChanged() called for region that doesn't exist.");
  319. return;
  320. }
  321. // Update existing entry or create a new material entry
  322. uint16_t materialId = CreateOrUpdateDetailMaterial(newMaterial);
  323. if (materialRegion->m_defaultDetailMaterialId != materialId)
  324. {
  325. m_detailMaterials.GetData(materialId).m_refCount++;
  326. CheckDetailMaterialForDeletion(materialRegion->m_defaultDetailMaterialId);
  327. materialRegion->m_defaultDetailMaterialId = materialId;
  328. }
  329. m_dirtyDetailRegion.AddAabb(materialRegion->m_region);
  330. }
  331. void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingCreated(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material)
  332. {
  333. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  334. if (materialRegion == nullptr)
  335. {
  336. AZ_Assert(false, "OnTerrainSurfaceMaterialMappingCreated() called for region that doesn't exist.");
  337. return;
  338. }
  339. // Validate that the surface tag is new
  340. ForSurfaceTag(*materialRegion, surfaceTag, [](DetailMaterialSurface&)
  341. {
  342. AZ_Error(TerrainDetailMaterialManagerName, false, "Already have a surface material mapping for this surface tag.");
  343. });
  344. uint16_t detailMaterialId = CreateOrUpdateDetailMaterial(material);
  345. materialRegion->m_materialsForSurfaces.push_back({ surfaceTag, detailMaterialId });
  346. m_detailMaterials.GetData(detailMaterialId).m_refCount++;
  347. m_dirtyDetailRegion.AddAabb(materialRegion->m_region);
  348. }
  349. void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingDestroyed(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag)
  350. {
  351. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  352. if (materialRegion == nullptr)
  353. {
  354. AZ_Assert(false, "OnTerrainSurfaceMaterialMappingDestroyed() called for region that doesn't exist.");
  355. return;
  356. }
  357. [[maybe_unused]] bool found = ForSurfaceTag(*materialRegion, surfaceTag,
  358. [&](DetailMaterialSurface& surface)
  359. {
  360. CheckDetailMaterialForDeletion(surface.m_detailMaterialId);
  361. if (surface.m_surfaceTag != materialRegion->m_materialsForSurfaces.back().m_surfaceTag)
  362. {
  363. AZStd::swap(surface, materialRegion->m_materialsForSurfaces.back());
  364. }
  365. materialRegion->m_materialsForSurfaces.pop_back();
  366. m_dirtyDetailRegion.AddAabb(materialRegion->m_region);
  367. });
  368. AZ_Error(TerrainDetailMaterialManagerName, found, "Could not find surface tag to destroy for OnTerrainSurfaceMaterialMappingDestroyed().");
  369. }
  370. void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingMaterialChanged(
  371. AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material)
  372. {
  373. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  374. if (materialRegion == nullptr)
  375. {
  376. AZ_Assert(false, "OnTerrainSurfaceMaterialMappingMaterialChanged() called for region that doesn't exist.");
  377. return;
  378. }
  379. // Update existing entry or create a new material entry
  380. uint16_t materialId = CreateOrUpdateDetailMaterial(material);
  381. [[maybe_unused]] bool found = ForSurfaceTag(*materialRegion, surfaceTag,
  382. [&](DetailMaterialSurface& surface)
  383. {
  384. if (surface.m_detailMaterialId != materialId)
  385. {
  386. // Updated material was a different asset than the old material, decrement ref count and
  387. // delete if no other surface tags are using it.
  388. m_detailMaterials.GetData(materialId).m_refCount++;
  389. CheckDetailMaterialForDeletion(surface.m_detailMaterialId);
  390. surface.m_detailMaterialId = materialId;
  391. }
  392. m_dirtyDetailRegion.AddAabb(materialRegion->m_region);
  393. });
  394. AZ_Assert(found, "OnTerrainSurfaceMaterialMappingMaterialChanged() called for tag that doesn't exist.");
  395. }
  396. void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingTagChanged(
  397. AZ::EntityId entityId, SurfaceData::SurfaceTag oldTag, SurfaceData::SurfaceTag newTag)
  398. {
  399. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  400. if (materialRegion == nullptr)
  401. {
  402. AZ_Assert(false, "OnTerrainSurfaceMaterialMappingTagChanged() called for region that doesn't exist.");
  403. return;
  404. }
  405. [[maybe_unused]] bool found = ForSurfaceTag(*materialRegion, oldTag,
  406. [&](DetailMaterialSurface& surface)
  407. {
  408. surface.m_surfaceTag = newTag;
  409. m_dirtyDetailRegion.AddAabb(materialRegion->m_region);
  410. });
  411. AZ_Assert(found, "OnTerrainSurfaceMaterialMappingTagChanged() called for tag that doesn't exist.");
  412. }
  413. void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingRegionCreated(AZ::EntityId entityId, const AZ::Aabb& region)
  414. {
  415. DetailMaterialListRegion& materialRegion = FindOrCreateByEntityId(entityId, m_detailMaterialRegions);
  416. materialRegion.m_region = region;
  417. if (materialRegion.HasMaterials())
  418. {
  419. m_dirtyDetailRegion.AddAabb(region);
  420. }
  421. }
  422. void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingRegionDestroyed(AZ::EntityId entityId, const AZ::Aabb& oldRegion)
  423. {
  424. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  425. if (materialRegion == nullptr)
  426. {
  427. AZ_Assert(false, "OnTerrainSurfaceMaterialMappingRegionDestroyed() called for region that doesn't exist.");
  428. return;
  429. }
  430. if (materialRegion->HasMaterials())
  431. {
  432. m_dirtyDetailRegion.AddAabb(oldRegion);
  433. }
  434. m_detailMaterialRegions.RemoveData(materialRegion);
  435. }
  436. void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingRegionChanged(AZ::EntityId entityId, const AZ::Aabb& oldRegion, const AZ::Aabb& newRegion)
  437. {
  438. DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions);
  439. if (materialRegion == nullptr)
  440. {
  441. AZ_Assert(false, "OnTerrainSurfaceMaterialMappingRegionChanged() called for region that doesn't exist.");
  442. return;
  443. }
  444. materialRegion->m_region = newRegion;
  445. if (materialRegion->HasMaterials())
  446. {
  447. m_dirtyDetailRegion.AddAabb(oldRegion);
  448. m_dirtyDetailRegion.AddAabb(newRegion);
  449. }
  450. }
  451. void TerrainDetailMaterialManager::CheckDetailMaterialForDeletion(uint16_t detailMaterialId)
  452. {
  453. auto& detailMaterialData = m_detailMaterials.GetData(detailMaterialId);
  454. if (--detailMaterialData.m_refCount == 0)
  455. {
  456. uint16_t bufferIndex = detailMaterialData.m_detailMaterialBufferIndex;
  457. m_detailMaterialShaderIndex.Release(bufferIndex);
  458. m_detailMaterials.RemoveIndex(detailMaterialId);
  459. m_detailMaterialBufferNeedsUpdate = true;
  460. }
  461. }
  462. uint16_t TerrainDetailMaterialManager::CreateOrUpdateDetailMaterial(MaterialInstance material)
  463. {
  464. static constexpr uint16_t InvalidDetailMaterial = 0xFFFF;
  465. uint16_t detailMaterialId = InvalidDetailMaterial;
  466. for (const auto& detailMaterialData : m_detailMaterials.GetDataVector())
  467. {
  468. if (detailMaterialData.m_assetId == material->GetAssetId())
  469. {
  470. detailMaterialId = m_detailMaterials.GetIndexForData(&detailMaterialData);
  471. UpdateDetailMaterialData(detailMaterialId, material);
  472. break;
  473. }
  474. }
  475. AZ_Assert(m_detailMaterialShaderIndex.GetSize() < 0xFF, "Only 255 detail materials supported.");
  476. if (detailMaterialId == InvalidDetailMaterial && m_detailMaterialShaderIndex.GetSize() < 0xFF)
  477. {
  478. detailMaterialId = m_detailMaterials.GetFreeSlotIndex();
  479. auto& detailMaterialData = m_detailMaterials.GetData(detailMaterialId);
  480. detailMaterialData.m_detailMaterialBufferIndex = aznumeric_cast<uint16_t>(m_detailMaterialShaderIndex.Reserve());
  481. UpdateDetailMaterialData(detailMaterialId, material);
  482. }
  483. return detailMaterialId;
  484. }
  485. void TerrainDetailMaterialManager::UpdateDetailMaterialData(uint16_t detailMaterialIndex, MaterialInstance material)
  486. {
  487. DetailMaterialData& materialData = m_detailMaterials.GetData(detailMaterialIndex);
  488. materialData.m_assetId = material->GetAssetId();
  489. for (auto& [deviceIndex, data] : m_detailMaterialShaderData)
  490. {
  491. if (m_detailMaterialShaderIndex.GetSize() > data.size())
  492. {
  493. data.resize(m_detailMaterialShaderIndex.GetSize());
  494. }
  495. auto& shaderData = data.at(materialData.m_detailMaterialBufferIndex);
  496. shaderData = DetailMaterialShaderData();
  497. DetailTextureFlags& flags = shaderData.m_flags;
  498. flags = DetailTextureFlags::None;
  499. auto getIndex = [&](const char* const indexName) -> AZ::RPI::MaterialPropertyIndex
  500. {
  501. const AZ::RPI::MaterialPropertyIndex index = material->FindPropertyIndex(AZ::Name(indexName));
  502. AZ_Warning(TerrainDetailMaterialManagerName, index.IsValid(), "Failed to find shader input constant %s.", indexName);
  503. return index;
  504. };
  505. auto applyProperty = [&](const char* const indexName, auto& ref) -> void
  506. {
  507. const auto index = getIndex(indexName);
  508. if (index.IsValid())
  509. {
  510. // GetValue<T>() expects the actual type, not a reference type, so the reference needs to be removed.
  511. using TypeRefRemoved = AZStd::remove_cvref_t<decltype(ref)>;
  512. ref = material->GetPropertyValue(index).GetValue<TypeRefRemoved>();
  513. }
  514. };
  515. auto applyImage = [&](const char* const indexName, AZ::Data::Instance<AZ::RPI::Image>& ref, const char* const usingFlagName, DetailTextureFlags flagToSet, uint32_t& imageIndex, int deviceIndex) -> void
  516. {
  517. // Determine if an image exists and if its using flag allows it to be used.
  518. const auto index = getIndex(indexName);
  519. const auto useTextureIndex = getIndex(usingFlagName);
  520. bool useTextureValue = true;
  521. if (useTextureIndex.IsValid())
  522. {
  523. useTextureValue = material->GetPropertyValue(useTextureIndex).GetValue<bool>();
  524. }
  525. if (index.IsValid() && useTextureValue)
  526. {
  527. ref = material->GetPropertyValue(index).GetValue<AZ::Data::Instance<AZ::RPI::Image>>();
  528. }
  529. useTextureValue = useTextureValue && ref;
  530. flags = DetailTextureFlags(useTextureValue ? (flags | flagToSet) : (flags & ~flagToSet));
  531. if (ref)
  532. {
  533. imageIndex = ref->GetImageView()->GetDeviceImageView(deviceIndex)->GetBindlessReadIndex();
  534. }
  535. else if (imageIndex != InvalidImageIndex)
  536. {
  537. imageIndex = InvalidImageIndex;
  538. }
  539. };
  540. auto applyFlag = [&](const char* const indexName, DetailTextureFlags flagToSet) -> void
  541. {
  542. const auto index = getIndex(indexName);
  543. if (index.IsValid())
  544. {
  545. bool flagValue = material->GetPropertyValue(index).GetValue<bool>();
  546. flags = DetailTextureFlags(flagValue ? flags | flagToSet : flags);
  547. }
  548. };
  549. auto getEnumName = [&](const char* const indexName) -> const AZStd::string_view
  550. {
  551. const auto index = getIndex(indexName);
  552. if (index.IsValid())
  553. {
  554. uint32_t enumIndex = material->GetPropertyValue(index).GetValue<uint32_t>();
  555. const AZ::Name& enumName = material->GetMaterialPropertiesLayout()->GetPropertyDescriptor(index)->GetEnumName(enumIndex);
  556. return enumName.GetStringView();
  557. }
  558. return "";
  559. };
  560. using namespace DetailMaterialInputs;
  561. applyImage(BaseColorMap, materialData.m_colorImage, BaseColorUseTexture, DetailTextureFlags::UseTextureBaseColor, shaderData.m_colorImageIndex, deviceIndex);
  562. applyProperty(BaseColorFactor, shaderData.m_baseColorFactor);
  563. const auto baseColorIndex = getIndex(BaseColorColor);
  564. if (baseColorIndex.IsValid())
  565. {
  566. const AZ::Color baseColor = material->GetPropertyValue(baseColorIndex).GetValue<AZ::Color>();
  567. shaderData.m_baseColorRed = baseColor.GetR();
  568. shaderData.m_baseColorGreen = baseColor.GetG();
  569. shaderData.m_baseColorBlue = baseColor.GetB();
  570. }
  571. const AZStd::string_view& blendModeString = getEnumName(BaseColorBlendMode);
  572. if (blendModeString == "Multiply")
  573. {
  574. flags = DetailTextureFlags(flags | DetailTextureFlags::BlendModeMultiply);
  575. }
  576. else if (blendModeString == "LinearLight")
  577. {
  578. flags = DetailTextureFlags(flags | DetailTextureFlags::BlendModeLinearLight);
  579. }
  580. else if (blendModeString == "Lerp")
  581. {
  582. flags = DetailTextureFlags(flags | DetailTextureFlags::BlendModeLerp);
  583. }
  584. else if (blendModeString == "Overlay")
  585. {
  586. flags = DetailTextureFlags(flags | DetailTextureFlags::BlendModeOverlay);
  587. }
  588. applyImage(MetallicMap, materialData.m_metalnessImage, MetallicUseTexture, DetailTextureFlags::UseTextureMetallic, shaderData.m_metalnessImageIndex, deviceIndex);
  589. applyProperty(MetallicFactor, shaderData.m_metalFactor);
  590. applyImage(RoughnessMap, materialData.m_roughnessImage, RoughnessUseTexture, DetailTextureFlags::UseTextureRoughness, shaderData.m_roughnessImageIndex, deviceIndex);
  591. if ((flags & DetailTextureFlags::UseTextureRoughness) > 0)
  592. {
  593. float lowerBound = 0.0;
  594. float upperBound = 1.0;
  595. applyProperty(RoughnessLowerBound, lowerBound);
  596. applyProperty(RoughnessUpperBound, upperBound);
  597. shaderData.m_roughnessBias = lowerBound;
  598. shaderData.m_roughnessScale = upperBound - lowerBound;
  599. }
  600. else
  601. {
  602. shaderData.m_roughnessBias = 0.0;
  603. applyProperty(RoughnessFactor, shaderData.m_roughnessScale);
  604. }
  605. applyImage(SpecularF0Map, materialData.m_specularF0Image, SpecularF0UseTexture, DetailTextureFlags::UseTextureSpecularF0, shaderData.m_specularF0ImageIndex, deviceIndex);
  606. applyProperty(SpecularF0Factor, shaderData.m_specularF0Factor);
  607. applyImage(NormalMap, materialData.m_normalImage, NormalUseTexture, DetailTextureFlags::UseTextureNormal, shaderData.m_normalImageIndex, deviceIndex);
  608. applyProperty(NormalFactor, shaderData.m_normalFactor);
  609. applyFlag(NormalFlipX, DetailTextureFlags::FlipNormalX);
  610. applyFlag(NormalFlipY, DetailTextureFlags::FlipNormalY);
  611. applyImage(DiffuseOcclusionMap, materialData.m_occlusionImage, DiffuseOcclusionUseTexture, DetailTextureFlags::UseTextureOcclusion, shaderData.m_occlusionImageIndex, deviceIndex);
  612. applyProperty(DiffuseOcclusionFactor, shaderData.m_occlusionFactor);
  613. applyImage(HeightMap, materialData.m_heightImage, HeightUseTexture, DetailTextureFlags::UseTextureHeight, shaderData.m_heightImageIndex, deviceIndex);
  614. bool terrainSettingsOverrideParallax = false;
  615. applyProperty(TerrainSettingsOverrideParallax, terrainSettingsOverrideParallax);
  616. if (terrainSettingsOverrideParallax)
  617. {
  618. applyProperty(TerrainHeightFactor, shaderData.m_heightFactor);
  619. applyProperty(TerrainHeightOffset, shaderData.m_heightOffset);
  620. }
  621. else
  622. {
  623. // Parallax ranges from 0 to 0.1, so multiply by 10 to be in the 0-1 range.
  624. applyProperty(ParallaxHeightFactor, shaderData.m_heightFactor);
  625. shaderData.m_heightFactor *= 10.0f;
  626. applyProperty(ParallaxHeightOffset, shaderData.m_heightOffset);
  627. shaderData.m_heightOffset *= 10.0f;
  628. }
  629. applyProperty(HeightBlendFactor, shaderData.m_heightBlendFactor);
  630. applyProperty(HeightWeightClampFactor, shaderData.m_heightWeightClampFactor);
  631. shaderData.m_heightWeightClampFactor = 1.0f / AZStd::GetMax(0.0001f, shaderData.m_heightWeightClampFactor);
  632. AZ::Render::UvTransformDescriptor transformDescriptor;
  633. applyProperty(UvCenter, transformDescriptor.m_center);
  634. applyProperty(UvScale, transformDescriptor.m_scale);
  635. applyProperty(UvTileU, transformDescriptor.m_scaleX);
  636. applyProperty(UvTileV, transformDescriptor.m_scaleY);
  637. applyProperty(UvOffsetU, transformDescriptor.m_translateX);
  638. applyProperty(UvOffsetV, transformDescriptor.m_translateY);
  639. applyProperty(UvRotateDegrees, transformDescriptor.m_rotateDegrees);
  640. AZStd::array<AZ::Render::TransformType, 3> order =
  641. {
  642. AZ::Render::TransformType::Rotate,
  643. AZ::Render::TransformType::Translate,
  644. AZ::Render::TransformType::Scale,
  645. };
  646. AZ::Matrix3x3 uvTransformMatrix = AZ::Render::CreateUvTransformMatrix(transformDescriptor, order);
  647. uvTransformMatrix.GetRow(0).StoreToFloat3(&shaderData.m_uvTransform[0]);
  648. uvTransformMatrix.GetRow(1).StoreToFloat3(&shaderData.m_uvTransform[4]);
  649. uvTransformMatrix.GetRow(2).StoreToFloat3(&shaderData.m_uvTransform[8]);
  650. // Store a hash of the matrix in element in an unused portion for quick comparisons in the shader
  651. size_t hash64 = 0;
  652. for (float value : shaderData.m_uvTransform)
  653. {
  654. AZStd::hash_combine(hash64, value);
  655. }
  656. uint32_t hash32 = uint32_t((hash64 ^ (hash64 >> 32)) & 0xFFFFFFFF);
  657. shaderData.m_uvTransform[3] = *reinterpret_cast<float*>(&hash32);
  658. }
  659. m_detailMaterialBufferNeedsUpdate = true;
  660. }
  661. void TerrainDetailMaterialManager::CheckUpdateDetailTexture(const AZ::Vector3& cameraPosition)
  662. {
  663. AZ::Aabb untouchedRegion = AZ::Aabb::CreateNull();
  664. ClipmapBoundsRegionList edgeUpdatedRegions =
  665. m_detailMaterialIdBounds.UpdateCenter(AZ::Vector2(cameraPosition.GetX(), cameraPosition.GetY()), &untouchedRegion);
  666. if (!m_detailTextureImage)
  667. {
  668. // If the m_detailTextureImage doesn't exist, create it and populate the entire texture
  669. const AZ::Data::Instance<AZ::RPI::AttachmentImagePool> imagePool = AZ::RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool();
  670. AZ::RHI::ImageDescriptor imageDescriptor = AZ::RHI::ImageDescriptor::Create2D(
  671. AZ::RHI::ImageBindFlags::ShaderRead, m_detailTextureSize, m_detailTextureSize, AZ::RHI::Format::R8G8B8A8_UINT
  672. );
  673. const AZ::Name TerrainDetailName = AZ::Name(TerrainDetailChars);
  674. m_detailTextureImage = AZ::RPI::AttachmentImage::Create(*imagePool.get(), imageDescriptor, TerrainDetailName, nullptr, nullptr);
  675. AZ_Error(TerrainDetailMaterialManagerName, m_detailTextureImage, "Failed to initialize the detail texture image.");
  676. ClipmapBoundsRegionList updateRegions = m_detailMaterialIdBounds.TransformRegion(m_detailMaterialIdBounds.GetWorldBounds());
  677. for (const auto& region : updateRegions)
  678. {
  679. UpdateDetailTexture(region.m_worldAabb, region.m_localAabb);
  680. }
  681. }
  682. else
  683. {
  684. // Update the edge regions
  685. for (const auto& region : edgeUpdatedRegions)
  686. {
  687. UpdateDetailTexture(region.m_worldAabb, region.m_localAabb);
  688. }
  689. if (m_dirtyDetailRegion.IsValid())
  690. {
  691. m_dirtyDetailRegion = m_dirtyDetailRegion.GetClamped(untouchedRegion);
  692. if (m_dirtyDetailRegion.IsValid())
  693. {
  694. ClipmapBoundsRegionList updateRegions = m_detailMaterialIdBounds.TransformRegion(m_dirtyDetailRegion);
  695. for (const auto& region : updateRegions)
  696. {
  697. UpdateDetailTexture(region.m_worldAabb, region.m_localAabb);
  698. }
  699. }
  700. m_dirtyDetailRegion = AZ::Aabb::CreateNull();
  701. }
  702. }
  703. }
  704. void TerrainDetailMaterialManager::UpdateDetailTexture(const AZ::Aabb& worldUpdateAabb, const Aabb2i& textureUpdateAabb)
  705. {
  706. if (!m_detailTextureImage)
  707. {
  708. return;
  709. }
  710. struct DetailMaterialPixel
  711. {
  712. uint8_t m_material1{ 255 };
  713. uint8_t m_material2{ 255 };
  714. uint8_t m_blend{ 0 }; // 0 = full weight on material1, 255 = full weight on material2
  715. uint8_t m_padding{ 0 };
  716. };
  717. const int32_t width = textureUpdateAabb.m_max.m_x - textureUpdateAabb.m_min.m_x;
  718. const int32_t height = textureUpdateAabb.m_max.m_y - textureUpdateAabb.m_min.m_y;
  719. AZStd::vector<DetailMaterialPixel> pixels(width * height);
  720. auto perPositionCallback = [this, &pixels, &width](
  721. size_t xIndex, size_t yIndex,
  722. const AzFramework::SurfaceData::SurfacePoint& surfacePoint,
  723. [[maybe_unused]] bool terrainExists)
  724. {
  725. // Store the top two surface weights in the texture with m_blend storing the relative weight.
  726. DetailMaterialPixel& pixel = pixels.at(yIndex * width + xIndex);
  727. uint32_t foundMaterials = 0;
  728. float firstWeight = 0.0f;
  729. float secondWeight = 0.0f;
  730. AZ::Vector2 position(surfacePoint.m_position.GetX(), surfacePoint.m_position.GetY());
  731. const DetailMaterialListRegion* region = FindRegionForPosition(position);
  732. if (region == nullptr)
  733. {
  734. pixel.m_material1 = m_passthroughMaterialId;
  735. return;
  736. }
  737. for (const auto& surfaceTagWeight : surfacePoint.m_surfaceTags)
  738. {
  739. if (surfaceTagWeight.m_weight > 0.0f)
  740. {
  741. AZ::Crc32 surfaceType = surfaceTagWeight.m_surfaceType;
  742. uint16_t materialId = GetDetailMaterialForSurfaceType(*region, surfaceType);
  743. if (materialId < 255)
  744. {
  745. if (foundMaterials == 0)
  746. {
  747. // Found first material. Save its weight to calculate blend later.
  748. ++foundMaterials;
  749. pixel.m_material1 = aznumeric_cast<uint8_t>(materialId);
  750. firstWeight = surfaceTagWeight.m_weight;
  751. }
  752. else if (materialId == pixel.m_material1)
  753. {
  754. // Same material as the first material, just add the weights.
  755. firstWeight += surfaceTagWeight.m_weight;
  756. }
  757. else if (foundMaterials == 1)
  758. {
  759. // Found second material. Save its weight to calculate blend later.
  760. ++foundMaterials;
  761. secondWeight += surfaceTagWeight.m_weight;
  762. pixel.m_material2 = aznumeric_cast<uint8_t>(materialId);
  763. }
  764. else if (materialId == pixel.m_material2)
  765. {
  766. // Same material as the second material, just add the weights.
  767. secondWeight += surfaceTagWeight.m_weight;
  768. }
  769. else
  770. {
  771. break;
  772. }
  773. }
  774. }
  775. }
  776. if (foundMaterials == 0)
  777. {
  778. // No materials found, so use the default material.
  779. uint8_t defaultMaterial = region->m_defaultDetailMaterialId == InvalidDetailMaterialId ? m_passthroughMaterialId :
  780. aznumeric_cast<uint8_t>(m_detailMaterials.GetData(region->m_defaultDetailMaterialId).m_detailMaterialBufferIndex);
  781. pixel.m_material1 = defaultMaterial;
  782. }
  783. else if (foundMaterials == 2)
  784. {
  785. float totalWeight = firstWeight + secondWeight;
  786. float blendWeight = 1.0f - (firstWeight / totalWeight);
  787. pixel.m_blend = aznumeric_cast<uint8_t>(blendWeight * 255.0f + 0.5f);
  788. }
  789. };
  790. AZ::Vector2 stepSize(m_detailTextureScale);
  791. AZStd::binary_semaphore wait;
  792. AZStd::shared_ptr<AzFramework::Terrain::QueryAsyncParams> asyncParams
  793. = AZStd::make_shared<AzFramework::Terrain::QueryAsyncParams>();
  794. asyncParams->m_desiredNumberOfJobs = AzFramework::Terrain::QueryAsyncParams::UseMaxJobs;
  795. asyncParams->m_minPositionsPerJob = 4 * m_detailTextureSize; // do at least 4 rows per job.
  796. asyncParams->m_completionCallback = [&wait](AZStd::shared_ptr<AzFramework::Terrain::TerrainJobContext>)
  797. {
  798. wait.release();
  799. };
  800. AzFramework::Terrain::TerrainQueryRegion queryRegion(worldUpdateAabb.GetMin(), width, height, stepSize);
  801. AzFramework::Terrain::TerrainDataRequestBus::Broadcast(
  802. &AzFramework::Terrain::TerrainDataRequests::QueryRegionAsync,
  803. queryRegion,
  804. AzFramework::Terrain::TerrainDataRequests::TerrainDataMask::SurfaceData,
  805. perPositionCallback,
  806. AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT,
  807. asyncParams);
  808. wait.acquire();
  809. const int32_t left = textureUpdateAabb.m_min.m_x;
  810. const int32_t top = textureUpdateAabb.m_min.m_y;
  811. AZ::RHI::ImageUpdateRequest imageUpdateRequest;
  812. imageUpdateRequest.m_imageSubresourcePixelOffset.m_left = aznumeric_cast<uint32_t>(left);
  813. imageUpdateRequest.m_imageSubresourcePixelOffset.m_top = aznumeric_cast<uint32_t>(top);
  814. AZ::RHI::DeviceImageSubresourceLayout layout{{static_cast<uint32_t>(width), static_cast<uint32_t>(height), 1}, static_cast<uint32_t>(height), static_cast<uint32_t>(width * sizeof(DetailMaterialPixel)), static_cast<uint32_t>(width * height * sizeof(DetailMaterialPixel)), 1, 1};
  815. imageUpdateRequest.m_sourceSubresourceLayout.Init(m_detailTextureImage->GetRHIImage()->GetDeviceMask(), layout);
  816. imageUpdateRequest.m_sourceData = pixels.data();
  817. imageUpdateRequest.m_image = m_detailTextureImage->GetRHIImage();
  818. m_detailTextureImage->UpdateImageContents(imageUpdateRequest);
  819. }
  820. uint16_t TerrainDetailMaterialManager::GetDetailMaterialForSurfaceType(const DetailMaterialListRegion& materialRegion, AZ::Crc32 surfaceType) const
  821. {
  822. for (const auto& materialSurface : materialRegion.m_materialsForSurfaces)
  823. {
  824. if (materialSurface.m_surfaceTag == surfaceType)
  825. {
  826. return m_detailMaterials.GetData(materialSurface.m_detailMaterialId).m_detailMaterialBufferIndex;
  827. }
  828. }
  829. return InvalidDetailMaterialId;
  830. }
  831. auto TerrainDetailMaterialManager::FindRegionForPosition(const AZ::Vector2& position) const -> const DetailMaterialListRegion*
  832. {
  833. for (const auto& materialRegion : m_detailMaterialRegions.GetDataVector())
  834. {
  835. if (SurfaceData::AabbContains2D(materialRegion.m_region, position))
  836. {
  837. return &materialRegion;
  838. }
  839. }
  840. return nullptr;
  841. }
  842. void TerrainDetailMaterialManager::InitializePassthroughDetailMaterial()
  843. {
  844. m_passthroughMaterialId = aznumeric_cast<uint8_t>(m_detailMaterialShaderIndex.Reserve());
  845. for (auto& [deviceIndex, data] : m_detailMaterialShaderData)
  846. {
  847. if (m_detailMaterialShaderIndex.GetSize() > data.size())
  848. {
  849. data.resize(m_detailMaterialShaderIndex.GetSize());
  850. }
  851. auto& materialShaderData = data.at(m_passthroughMaterialId);
  852. // Material defaults to white (1.0, 1.0, 1.0), set the blend mode to multiply so it passes through to the macro material.
  853. materialShaderData.m_flags = DetailTextureFlags::BlendModeMultiply;
  854. }
  855. }
  856. auto TerrainDetailMaterialManager::FindByEntityId(AZ::EntityId entityId, AZ::Render::IndexedDataVector<DetailMaterialListRegion>& container)
  857. -> DetailMaterialListRegion*
  858. {
  859. for (DetailMaterialListRegion& data : container.GetDataVector())
  860. {
  861. if (data.m_entityId == entityId)
  862. {
  863. return &data;
  864. }
  865. }
  866. return nullptr;
  867. }
  868. auto TerrainDetailMaterialManager::FindOrCreateByEntityId(AZ::EntityId entityId, AZ::Render::IndexedDataVector<DetailMaterialListRegion>& container)
  869. -> DetailMaterialListRegion&
  870. {
  871. DetailMaterialListRegion* dataPtr = FindByEntityId(entityId, container);
  872. if (dataPtr != nullptr)
  873. {
  874. return *dataPtr;
  875. }
  876. const uint16_t slotId = container.GetFreeSlotIndex();
  877. AZ_Assert(slotId != AZ::Render::IndexedDataVector<TerrainDetailMaterialManager>::NoFreeSlot, "Ran out of indices");
  878. DetailMaterialListRegion& data = container.GetData(slotId);
  879. data.m_entityId = entityId;
  880. return data;
  881. }
  882. void TerrainDetailMaterialManager::RemoveByEntityId(AZ::EntityId entityId, AZ::Render::IndexedDataVector<DetailMaterialListRegion>& container)
  883. {
  884. for (DetailMaterialListRegion& data : container.GetDataVector())
  885. {
  886. if (data.m_entityId == entityId)
  887. {
  888. container.RemoveData(&data);
  889. return;
  890. }
  891. }
  892. AZ_Assert(false, "Entity Id not found in container.")
  893. }
  894. }