TerrainMeshManager.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  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/TerrainMeshManager.h>
  9. #include <AzCore/Console/Console.h>
  10. #include <AzCore/Math/Frustum.h>
  11. #include <AzCore/Math/ShapeIntersection.h>
  12. #include <AzCore/Jobs/Algorithms.h>
  13. #include <AzCore/Jobs/JobCompletion.h>
  14. #include <AzCore/Jobs/JobFunction.h>
  15. #include <Atom/RHI.Reflect/BufferViewDescriptor.h>
  16. #include <Atom/RHI.Reflect/InputStreamLayoutBuilder.h>
  17. #include <Atom/RHI/RHISystemInterface.h>
  18. #include <Atom/RPI.Public/Scene.h>
  19. #include <Atom/RPI.Public/View.h>
  20. #include <Atom/RPI.Public/AuxGeom/AuxGeomDraw.h>
  21. #include <Atom/RPI.Public/AuxGeom/AuxGeomFeatureProcessorInterface.h>
  22. #include <Atom/RPI.Public/Buffer/Buffer.h>
  23. #include <Atom/RPI.Public/Model/Model.h>
  24. #include <Atom/RPI.Public/Shader/ShaderResourceGroup.h>
  25. #include <Atom/Feature/RenderCommon.h>
  26. #include <Atom/Feature/Mesh/MeshCommon.h>
  27. namespace Terrain
  28. {
  29. namespace
  30. {
  31. [[maybe_unused]] static const char* TerrainMeshManagerName = "TerrainMeshManager";
  32. }
  33. AZ_CVAR(bool,
  34. r_debugTerrainLodLevels,
  35. false,
  36. [](const bool& value)
  37. {
  38. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(AZ::Name{ "o_debugTerrainLodLevels" }, AZ::RPI::ShaderOptionValue{ value });
  39. },
  40. AZ::ConsoleFunctorFlags::Null,
  41. "Turns on debug coloring for terrain mesh lods."
  42. );
  43. AZ_CVAR(bool,
  44. r_debugTerrainAabbs,
  45. false,
  46. nullptr,
  47. AZ::ConsoleFunctorFlags::Null,
  48. "Turns on debug aabbs for terrain sectors."
  49. );
  50. TerrainMeshManager::TerrainMeshManager()
  51. {
  52. }
  53. TerrainMeshManager::~TerrainMeshManager()
  54. {
  55. AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusDisconnect();
  56. }
  57. void TerrainMeshManager::Initialize(AZ::RPI::Scene& parentScene)
  58. {
  59. m_parentScene = &parentScene;
  60. AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusConnect();
  61. m_handleGlobalShaderOptionUpdate = AZ::RPI::ShaderSystemInterface::GlobalShaderOptionUpdatedEvent::Handler
  62. {
  63. [this](const AZ::Name&, AZ::RPI::ShaderOptionValue) { m_rebuildDrawPackets = true; }
  64. };
  65. AZ::RPI::ShaderSystemInterface::Get()->Connect(m_handleGlobalShaderOptionUpdate);
  66. m_meshMovedFlag = m_parentScene->GetViewTagBitRegistry().AcquireTag(AZ::Render::MeshCommon::MeshMovedName);
  67. m_rayTracingFeatureProcessor = m_parentScene->GetFeatureProcessor<AZ::Render::RayTracingFeatureProcessorInterface>();
  68. m_rayTracingEnabled = (AZ::RHI::RHISystemInterface::Get()->GetRayTracingSupport() != AZ::RHI::MultiDevice::NoDevices) && m_rayTracingFeatureProcessor;
  69. m_isInitialized = true;
  70. }
  71. void TerrainMeshManager::SetConfiguration(const MeshConfiguration& config)
  72. {
  73. bool requireRebuild = m_config.CheckWouldRequireRebuild(config);
  74. m_config = config;
  75. if (requireRebuild)
  76. {
  77. m_rebuildSectors = true;
  78. OnTerrainDataChanged(AZ::Aabb::CreateNull(), TerrainDataChangedMask::HeightData);
  79. }
  80. // This will trigger a draw packet rebuild later.
  81. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(AZ::Name{ "o_useTerrainClod" }, AZ::RPI::ShaderOptionValue{ m_config.m_clodEnabled });
  82. }
  83. bool TerrainMeshManager::UpdateGridSize(float distanceToFirstLod)
  84. {
  85. float queryResolution = 1.0f;
  86. AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(
  87. queryResolution, &AzFramework::Terrain::TerrainDataRequests::GetTerrainHeightQueryResolution);
  88. float quadsToFirstLod = distanceToFirstLod / queryResolution;
  89. uint32_t quadsPerSector = aznumeric_cast<uint32_t>(quadsToFirstLod / 4.0f);
  90. uint32_t gridSize = AZ::RHI::IsPowerOfTwo(quadsPerSector) ? quadsPerSector : (AZ::RHI::NextPowerOfTwo(quadsPerSector) >> 1);
  91. gridSize = AZStd::GetMin(gridSize, 128u); // x/y positions must be able to fix in 8 bits (256 is too large by 1)
  92. gridSize = AZStd::GetMax(gridSize, 8u); // make sure there's enough vertices to be worth drawing.
  93. if (gridSize != m_gridSize)
  94. {
  95. m_gridSize = aznumeric_cast<uint8_t>(gridSize);
  96. m_gridVerts1D = m_gridSize + 1;
  97. m_gridVerts2D = m_gridVerts1D * m_gridVerts1D;
  98. return true;
  99. }
  100. return false;
  101. }
  102. void TerrainMeshManager::SetMaterial(MaterialInstance materialInstance)
  103. {
  104. if (m_materialInstance != materialInstance || m_materialInstance->GetCurrentChangeId() != m_lastMaterialChangeId)
  105. {
  106. m_lastMaterialChangeId = materialInstance->GetCurrentChangeId();
  107. m_materialInstance = materialInstance;
  108. // Queue the load of the material's shaders now since they'll be needed later.
  109. m_materialInstance->ForAllShaderItems(
  110. [&](const AZ::Name&, const AZ::RPI::ShaderCollection::Item& shaderItem)
  111. {
  112. AZ::Data::Asset<AZ::RPI::ShaderAsset> shaderAsset = shaderItem.GetShaderAsset();
  113. if (!shaderAsset.IsReady())
  114. {
  115. shaderAsset.QueueLoad();
  116. }
  117. return true;
  118. });
  119. m_rebuildDrawPackets = true;
  120. }
  121. }
  122. bool TerrainMeshManager::IsInitialized() const
  123. {
  124. return m_isInitialized;
  125. }
  126. void TerrainMeshManager::ClearSectorBuffers()
  127. {
  128. // RemoveRayTracedMeshes() needs to be called first since it uses pointers into the sector data stored in m_sectorLods.
  129. RemoveRayTracedMeshes();
  130. m_candidateSectors.clear();
  131. m_sectorsThatNeedSrgCompiled.clear();
  132. m_sectorLods.clear();
  133. }
  134. void TerrainMeshManager::Reset()
  135. {
  136. if (m_meshMovedFlag.IsValid())
  137. {
  138. m_parentScene->GetViewTagBitRegistry().ReleaseTag(m_meshMovedFlag);
  139. }
  140. ClearSectorBuffers();
  141. m_xyPositions.clear();
  142. m_cachedDrawData.clear();
  143. m_rebuildSectors = true;
  144. }
  145. void TerrainMeshManager::RemoveRayTracedMeshes()
  146. {
  147. AZ_Assert(m_rayTracedItems.empty() || !m_sectorLods.empty(),
  148. "RemoveRayTracedMeshes() is being called after the underlying sector data has been deleted. "
  149. "The pointers stored in it are no longer valid.");
  150. for (RayTracedItem& item : m_rayTracedItems)
  151. {
  152. if (auto& rtData = item.m_sector->m_rtData; rtData)
  153. {
  154. RtSector::MeshGroup& meshGroup = rtData->m_meshGroups.at(item.m_meshGroupIndex);
  155. meshGroup.m_isVisible = false;
  156. m_rayTracingFeatureProcessor->RemoveMesh(meshGroup.m_id);
  157. }
  158. }
  159. m_rayTracedItems.clear();
  160. }
  161. void TerrainMeshManager::Update(const AZ::RPI::ViewPtr mainView, AZ::Data::Instance<AZ::RPI::ShaderResourceGroup>& terrainSrg)
  162. {
  163. if (m_rebuildDrawPackets)
  164. {
  165. // Rebuild the draw packets when the material or shaders change.
  166. RebuildDrawPackets();
  167. m_rebuildDrawPackets = false;
  168. }
  169. if (m_rebuildSectors)
  170. {
  171. // Rebuild the sectors when the configuration or terrain world changes
  172. CreateCommonBuffers();
  173. RebuildSectors();
  174. m_rebuildSectors = false;
  175. }
  176. ShaderMeshData meshData;
  177. mainView->GetCameraTransform().GetTranslation().StoreToFloat3(meshData.m_mainCameraPosition.data());
  178. meshData.m_firstLodDistance = m_config.m_firstLodDistance;
  179. meshData.m_rcpClodDistance = 1.0f / m_config.m_clodDistance;
  180. meshData.m_rcpGridSize = 1.0f / m_gridSize;
  181. meshData.m_gridToQuadScale = m_gridSize / 255.0f;
  182. terrainSrg->SetConstant(m_srgMeshDataIndex, meshData);
  183. }
  184. void TerrainMeshManager::CheckLodGridsForUpdate(AZ::Vector3 newPosition)
  185. {
  186. // lods of sectors that need updating, separated by LOD level.
  187. AZStd::vector<AZStd::vector<Sector*>> sectorsToUpdate(m_sectorLods.size());
  188. bool anySectorsUpdated = false;
  189. for (uint32_t lodLevel = 0; lodLevel < m_sectorLods.size(); ++lodLevel)
  190. {
  191. SectorLodGrid& lodGrid = m_sectorLods.at(lodLevel);
  192. // Figure out what the start coordinate should be for this lod level.
  193. const Vector2i newStartCoord = [&]()
  194. {
  195. const float maxDistance = m_config.m_firstLodDistance * aznumeric_cast<float>(1 << lodLevel);
  196. const float gridMeters = (m_gridSize * m_sampleSpacing) * (1 << lodLevel);
  197. const int32_t startCoordX = aznumeric_cast<int32_t>(AZStd::floorf((newPosition.GetX() - maxDistance) / gridMeters));
  198. const int32_t startCoordY = aznumeric_cast<int32_t>(AZStd::floorf((newPosition.GetY() - maxDistance) / gridMeters));
  199. // If the start coord for the lod level is different, then some of the sectors will need to be updated.
  200. // There's 1 sector of wiggle room, so make sure we've moving the lod's start coord by as little as possible.
  201. auto coordCheck = [&](int32_t newStartCoord, int32_t lodStartCoord) -> int32_t
  202. {
  203. return
  204. newStartCoord > lodStartCoord + 1 ? newStartCoord - 1 :
  205. newStartCoord < lodStartCoord ? newStartCoord :
  206. lodStartCoord;
  207. };
  208. return Vector2i(coordCheck(startCoordX, lodGrid.m_startCoord.m_x), coordCheck(startCoordY, lodGrid.m_startCoord.m_y));
  209. }();
  210. if (lodGrid.m_startCoord != newStartCoord)
  211. {
  212. lodGrid.m_startCoord = newStartCoord;
  213. const uint32_t firstSectorIndexX = (m_1dSectorCount + (newStartCoord.m_x % m_1dSectorCount)) % m_1dSectorCount;
  214. const uint32_t firstSectorIndexY = (m_1dSectorCount + (newStartCoord.m_y % m_1dSectorCount)) % m_1dSectorCount;
  215. for (uint32_t xOffset = 0; xOffset < m_1dSectorCount; ++xOffset)
  216. {
  217. for (uint32_t yOffset = 0; yOffset < m_1dSectorCount; ++yOffset)
  218. {
  219. // Sectors use toroidal addressing to avoid needing to update any more than necessary.
  220. const uint32_t sectorIndexX = (firstSectorIndexX + xOffset) % m_1dSectorCount;
  221. const uint32_t sectorIndexY = (firstSectorIndexY + yOffset) % m_1dSectorCount;
  222. const uint32_t sectorIndex = sectorIndexY * m_1dSectorCount + sectorIndexX;
  223. const Vector2i worldCoord = newStartCoord + Vector2i(xOffset, yOffset);
  224. Sector& sector = lodGrid.m_sectors.at(sectorIndex);
  225. if (sector.m_worldCoord != worldCoord)
  226. {
  227. sector.m_worldCoord = worldCoord;
  228. sectorsToUpdate.at(lodLevel).push_back(&sector);
  229. anySectorsUpdated = true;
  230. }
  231. }
  232. }
  233. }
  234. }
  235. if (anySectorsUpdated)
  236. {
  237. ProcessSectorUpdates(sectorsToUpdate);
  238. return;
  239. }
  240. }
  241. AZ::RHI::StreamBufferView TerrainMeshManager::CreateStreamBufferView(AZ::Data::Instance<AZ::RPI::Buffer>& buffer, uint32_t offset)
  242. {
  243. return
  244. {
  245. *buffer->GetRHIBuffer(),
  246. offset,
  247. aznumeric_cast<uint32_t>(buffer->GetBufferSize()),
  248. buffer->GetBufferViewDescriptor().m_elementSize
  249. };
  250. }
  251. void TerrainMeshManager::BuildDrawPacket(Sector& sector)
  252. {
  253. AZ::RHI::DrawPacketBuilder drawPacketBuilder{AZ::RHI::MultiDevice::AllDevices};
  254. uint32_t indexCount = m_indexBuffer->GetBufferViewDescriptor().m_elementCount;
  255. sector.m_geometryView.SetDrawArguments(AZ::RHI::DrawIndexed(0, indexCount, 0));
  256. sector.m_geometryView.SetIndexBufferView(m_indexBufferView);
  257. drawPacketBuilder.Begin(nullptr);
  258. drawPacketBuilder.SetGeometryView(&sector.m_geometryView);
  259. drawPacketBuilder.AddShaderResourceGroup(sector.m_srg->GetRHIShaderResourceGroup());
  260. drawPacketBuilder.AddShaderResourceGroup(m_materialInstance->GetRHIShaderResourceGroup());
  261. sector.m_perDrawSrgs.clear();
  262. for (CachedDrawData& drawData : m_cachedDrawData)
  263. {
  264. AZ::Data::Instance<AZ::RPI::Shader>& shader = drawData.m_shader;
  265. AZ::RHI::DrawPacketBuilder::DrawRequest drawRequest;
  266. drawRequest.m_listTag = drawData.m_drawListTag;
  267. drawRequest.m_pipelineState = drawData.m_pipelineState;
  268. drawRequest.m_streamIndices = sector.m_geometryView.GetFullStreamBufferIndices();
  269. drawRequest.m_stencilRef = AZ::Render::StencilRefs::UseDiffuseGIPass | AZ::Render::StencilRefs::UseIBLSpecularPass;
  270. if (drawData.m_materialPipelineName != AZ::RPI::MaterialPipelineNone)
  271. {
  272. AZ::RHI::DrawFilterTag pipelineTag = m_parentScene->GetDrawFilterTagRegistry()->AcquireTag(drawData.m_materialPipelineName);
  273. AZ_Assert(pipelineTag.IsValid(), "Could not acquire pipeline filter tag '%s'.", drawData.m_materialPipelineName.GetCStr());
  274. drawRequest.m_drawFilterMask = 1 << pipelineTag.GetIndex();
  275. }
  276. AZ::Data::Instance<AZ::RPI::ShaderResourceGroup> drawSrg;
  277. if (drawData.m_drawSrgLayout)
  278. {
  279. // If the DrawSrg exists we must create and bind it, otherwise the CommandList will fail validation for SRG being null
  280. drawSrg = AZ::RPI::ShaderResourceGroup::Create(shader->GetAsset(), shader->GetSupervariantIndex(), drawData.m_drawSrgLayout->GetName());
  281. if (drawData.m_shaderVariant.UseKeyFallback() && drawData.m_drawSrgLayout->HasShaderVariantKeyFallbackEntry())
  282. {
  283. drawSrg->SetShaderVariantKeyFallbackValue(drawData.m_shaderOptions.GetShaderVariantKeyFallbackValue());
  284. }
  285. drawSrg->Compile();
  286. }
  287. if (drawSrg)
  288. {
  289. drawRequest.m_uniqueShaderResourceGroup = drawSrg->GetRHIShaderResourceGroup();
  290. sector.m_perDrawSrgs.push_back(drawSrg);
  291. }
  292. drawPacketBuilder.AddDrawItem(drawRequest);
  293. }
  294. AZ::RHI::DrawPacketBuilder commonQuadrantDrawPacketBuilder = drawPacketBuilder; // Copy of the draw packet builder to use later.
  295. sector.m_rhiDrawPacket = drawPacketBuilder.End();
  296. // Generate draw packets for each of the quadrants so they can be used to fill in places where the previous LOD didn't draw.
  297. // Due to z-ordered index buffer, no additional data is needed, just a different index offset and index count. Each quarter of
  298. // the index buffer perfectly corresponds to a quadrant of the sector in Z order (TL, TR, BL, BR).
  299. uint32_t lowerLodIndexCount = indexCount / 4;
  300. for (uint32_t i = 0; i < 4; ++i)
  301. {
  302. sector.m_quadrantGeometryViews[i] = sector.m_geometryView;
  303. sector.m_quadrantGeometryViews[i].SetDrawArguments( AZ::RHI::DrawIndexed(0, lowerLodIndexCount, lowerLodIndexCount * i) );
  304. AZ::RHI::DrawPacketBuilder quadrantDrawPacketBuilder = commonQuadrantDrawPacketBuilder;
  305. quadrantDrawPacketBuilder.SetGeometryView(&sector.m_quadrantGeometryViews[i]);
  306. sector.m_rhiDrawPacketQuadrant[i] = quadrantDrawPacketBuilder.End();
  307. }
  308. }
  309. void TerrainMeshManager::BuildRtSector(Sector& sector, uint32_t lodLevel)
  310. {
  311. RtSector& rtSector = *sector.m_rtData;
  312. AZStd::string positionName = AZStd::string::format("Terrain Positions- Lod %u, Sector (%u, %u)", lodLevel, sector.m_worldCoord.m_x, sector.m_worldCoord.m_x);
  313. AZStd::string normalName = AZStd::string::format("Terrain Normals - Lod %u, Sector (%u, %u)", lodLevel, sector.m_worldCoord.m_x, sector.m_worldCoord.m_x);
  314. rtSector.m_positionsBuffer = CreateRayTracingMeshBufferInstance(AZ::RHI::Format::R32G32B32_FLOAT, m_gridVerts2D, nullptr, positionName.c_str());
  315. rtSector.m_normalsBuffer = CreateRayTracingMeshBufferInstance(AZ::RHI::Format::R32G32B32_FLOAT, m_gridVerts2D, nullptr, positionName.c_str());
  316. // setup the stream and shader buffer views
  317. AZ::RHI::Buffer& rhiPositionsBuffer = *rtSector.m_positionsBuffer->GetRHIBuffer();
  318. uint32_t positionsBufferByteCount = aznumeric_cast<uint32_t>(rhiPositionsBuffer.GetDescriptor().m_byteCount);
  319. AZ::RHI::Format positionsBufferFormat = rtSector.m_positionsBuffer->GetBufferViewDescriptor().m_elementFormat;
  320. uint32_t positionsBufferElementSize = AZ::RHI::GetFormatSize(positionsBufferFormat);
  321. AZ::RHI::StreamBufferView positionsVertexBufferView(rhiPositionsBuffer, 0, positionsBufferByteCount, positionsBufferElementSize);
  322. AZ::RHI::BufferViewDescriptor positionsBufferDescriptor = AZ::RHI::BufferViewDescriptor::CreateRaw(0, positionsBufferByteCount);
  323. AZ::RHI::Buffer& rhiNormalsBuffer = *rtSector.m_normalsBuffer->GetRHIBuffer();
  324. uint32_t normalsBufferByteCount = aznumeric_cast<uint32_t>(rhiNormalsBuffer.GetDescriptor().m_byteCount);
  325. AZ::RHI::Format normalsBufferFormat = rtSector.m_normalsBuffer->GetBufferViewDescriptor().m_elementFormat;
  326. uint32_t normalsBufferElementSize = AZ::RHI::GetFormatSize(normalsBufferFormat);
  327. AZ::RHI::StreamBufferView normalsVertexBufferView(rhiNormalsBuffer, 0, normalsBufferByteCount, normalsBufferElementSize);
  328. AZ::RHI::BufferViewDescriptor normalsBufferDescriptor = AZ::RHI::BufferViewDescriptor::CreateRaw(0, normalsBufferByteCount);
  329. AZ::RHI::Buffer& rhiIndexBuffer = *m_rtIndexBuffer->GetRHIBuffer();
  330. AZ::RHI::IndexFormat indexBufferFormat = AZ::RHI::IndexFormat::Uint32;
  331. uint32_t totalIndexBufferByteCount = aznumeric_cast<uint32_t>(rhiIndexBuffer.GetDescriptor().m_byteCount);
  332. uint32_t indexElementSize = AZ::RHI::GetIndexFormatSize(indexBufferFormat);
  333. // Create the ray tracing meshes. Each sector has 5 meshes which all share the same data - one mesh that covers the whole
  334. // sector, and 4 meshes that cover each quadrant of the sector.
  335. auto createMesh = [&](RtSector::MeshGroup& meshGroup, uint32_t indexBufferByteOffset, uint32_t indexBufferByteCount)
  336. {
  337. meshGroup.m_submeshVector.clear();
  338. AZ::Render::RayTracingFeatureProcessorInterface::SubMesh& subMesh = meshGroup.m_submeshVector.emplace_back();
  339. subMesh.m_positionFormat = positionsBufferFormat;
  340. subMesh.m_positionVertexBufferView = positionsVertexBufferView;
  341. subMesh.m_positionShaderBufferView = rhiPositionsBuffer.GetBufferView(positionsBufferDescriptor);
  342. subMesh.m_normalFormat = normalsBufferFormat;
  343. subMesh.m_normalVertexBufferView = normalsVertexBufferView;
  344. subMesh.m_normalShaderBufferView = rhiNormalsBuffer.GetBufferView(normalsBufferDescriptor);
  345. subMesh.m_indexBufferView = AZ::RHI::IndexBufferView(rhiIndexBuffer, indexBufferByteOffset, indexBufferByteCount, indexBufferFormat);
  346. subMesh.m_material.m_baseColor = AZ::Color::CreateFromVector3(AZ::Vector3(0.18f));
  347. AZ::RHI::BufferViewDescriptor indexBufferDescriptor;
  348. indexBufferDescriptor.m_elementOffset = indexBufferByteOffset / indexElementSize;
  349. indexBufferDescriptor.m_elementCount = indexBufferByteCount / indexElementSize;
  350. indexBufferDescriptor.m_elementSize = indexElementSize;
  351. indexBufferDescriptor.m_elementFormat = AZ::RHI::Format::R32_UINT;
  352. subMesh.m_indexShaderBufferView = rhiIndexBuffer.GetBufferView(indexBufferDescriptor);
  353. meshGroup.m_mesh.m_assetId = AZ::Data::AssetId(meshGroup.m_id);
  354. float xyScale = (m_gridSize * m_sampleSpacing) * (1 << lodLevel);
  355. meshGroup.m_mesh.m_transform = AZ::Transform::CreateIdentity();
  356. meshGroup.m_mesh.m_nonUniformScale = AZ::Vector3(xyScale, xyScale, m_worldHeightBounds.m_max - m_worldHeightBounds.m_min);
  357. meshGroup.m_mesh.m_instanceMask |=
  358. static_cast<uint32_t>(AZ::RHI::RayTracingAccelerationStructureInstanceInclusionMask::STATIC_MESH);
  359. };
  360. createMesh(rtSector.m_meshGroups[0], 0, totalIndexBufferByteCount);
  361. uint32_t quarterCount = totalIndexBufferByteCount / 4;
  362. createMesh(rtSector.m_meshGroups[1], quarterCount * 0, quarterCount);
  363. createMesh(rtSector.m_meshGroups[2], quarterCount * 1, quarterCount);
  364. createMesh(rtSector.m_meshGroups[3], quarterCount * 2, quarterCount);
  365. createMesh(rtSector.m_meshGroups[4], quarterCount * 3, quarterCount);
  366. }
  367. void TerrainMeshManager::RebuildSectors()
  368. {
  369. const float gridMeters = m_gridSize * m_sampleSpacing;
  370. const auto& materialAsset = m_materialInstance->GetAsset();
  371. const auto& shaderAsset = materialAsset->GetMaterialTypeAsset()->GetShaderAssetForObjectSrg();
  372. // Calculate the largest potential number of sectors needed per dimension at any lod level.
  373. const float firstLodDiameter = m_config.m_firstLodDistance * 2.0f;
  374. m_1dSectorCount = aznumeric_cast<uint32_t>(AZStd::ceilf(firstLodDiameter / gridMeters));
  375. // If the sector grid doesn't line up perfectly with the camera, it will cover part of a sector
  376. // along each boundary, so we need an extra sector to cover in those cases.
  377. m_1dSectorCount += 1;
  378. // Add one sector of wiggle room so to avoid thrashing updates when going back and forth over a boundary.
  379. m_1dSectorCount += 1;
  380. ClearSectorBuffers();
  381. const uint8_t lodCount = aznumeric_cast<uint8_t>(AZStd::ceilf(log2f(AZStd::GetMax(1.0f, m_config.m_renderDistance / m_config.m_firstLodDistance)) + 1.0f));
  382. m_sectorLods.reserve(lodCount);
  383. // Create all the sectors with uninitialized SRGs. The SRGs will be updated later by CheckLodGridsForUpdate().
  384. m_indexBufferView =
  385. {
  386. *m_indexBuffer->GetRHIBuffer(),
  387. 0,
  388. aznumeric_cast<uint32_t>(m_indexBuffer->GetBufferSize()),
  389. AZ::RHI::IndexFormat::Uint16
  390. };
  391. for (uint8_t lodLevel = 0; lodLevel < lodCount; ++lodLevel)
  392. {
  393. m_sectorLods.push_back({});
  394. SectorLodGrid& lodGrid = m_sectorLods.back();
  395. lodGrid.m_sectors.resize(m_1dSectorCount * m_1dSectorCount);
  396. for (Sector& sector : lodGrid.m_sectors)
  397. {
  398. sector.m_srg = AZ::RPI::ShaderResourceGroup::Create(shaderAsset, materialAsset->GetObjectSrgLayout()->GetName());
  399. sector.m_heightsNormalsBuffer = CreateMeshBufferInstance(sizeof(HeightNormalVertex), m_gridVerts2D);
  400. sector.m_geometryView.ClearStreamBufferViews();
  401. AZStd::vector<AZ::RHI::StreamBufferView>& streamBufferViews = sector.m_geometryView.GetStreamBufferViews();
  402. streamBufferViews.resize(StreamIndex::Count);
  403. streamBufferViews[StreamIndex::XYPositions] = CreateStreamBufferView(m_xyPositionsBuffer);
  404. streamBufferViews[StreamIndex::Heights] = CreateStreamBufferView(sector.m_heightsNormalsBuffer);
  405. streamBufferViews[StreamIndex::Normals] = CreateStreamBufferView(sector.m_heightsNormalsBuffer, AZ::RHI::GetFormatSize(HeightFormat));
  406. if (m_config.m_clodEnabled)
  407. {
  408. sector.m_lodHeightsNormalsBuffer = CreateMeshBufferInstance(sizeof(HeightNormalVertex), m_gridVerts2D);
  409. streamBufferViews[StreamIndex::LodHeights] = CreateStreamBufferView(sector.m_lodHeightsNormalsBuffer);
  410. streamBufferViews[StreamIndex::LodNormals] = CreateStreamBufferView(sector.m_lodHeightsNormalsBuffer, AZ::RHI::GetFormatSize(HeightFormat));
  411. }
  412. else
  413. {
  414. streamBufferViews[StreamIndex::LodHeights] = CreateStreamBufferView(m_dummyLodHeightsNormalsBuffer);
  415. streamBufferViews[StreamIndex::LodNormals] = CreateStreamBufferView(m_dummyLodHeightsNormalsBuffer, AZ::RHI::GetFormatSize(HeightFormat));
  416. }
  417. BuildDrawPacket(sector);
  418. if (m_rayTracingEnabled)
  419. {
  420. sector.m_rtData = AZStd::make_unique<RtSector>();
  421. BuildRtSector(sector, lodLevel);
  422. }
  423. }
  424. }
  425. }
  426. void TerrainMeshManager::DrawMeshes(const AZ::RPI::FeatureProcessor::RenderPacket& process, const AZ::RPI::ViewPtr mainView)
  427. {
  428. AZ::Vector3 mainCameraPosition = mainView->GetCameraTransform().GetTranslation();
  429. CheckLodGridsForUpdate(mainCameraPosition);
  430. for (Sector* sector : m_sectorsThatNeedSrgCompiled)
  431. {
  432. sector->m_srg->Compile();
  433. sector->m_isQueuedForSrgCompile = false;
  434. }
  435. m_sectorsThatNeedSrgCompiled.clear();
  436. // Only update candidate sectors if the camera has moved. This could probably be relaxed further, but is a good starting point.
  437. const float minMovedDistanceSq = m_sampleSpacing * m_sampleSpacing;
  438. bool terrainChanged = m_candidateSectors.empty(); // candidate sectors need to be recalculated any time the terrain changes
  439. if (terrainChanged || m_cameraPosition.GetDistanceSq(mainCameraPosition) > minMovedDistanceSq)
  440. {
  441. m_cameraPosition = mainCameraPosition;
  442. UpdateCandidateSectors();
  443. }
  444. const AZ::RPI::AuxGeomDrawPtr auxGeomPtr = r_debugTerrainAabbs ?
  445. AZ::RPI::AuxGeomFeatureProcessorInterface::GetDrawQueueForScene(m_parentScene) :
  446. nullptr;
  447. // Compare view frustums against the list of candidate sectors and submit those sectors to draw.
  448. for (auto& view : process.m_views)
  449. {
  450. if (terrainChanged)
  451. {
  452. view->ApplyFlags(m_meshMovedFlag.GetIndex());
  453. }
  454. const AZ::Frustum viewFrustum = AZ::Frustum::CreateFromMatrixColumnMajor(view->GetWorldToClipMatrix());
  455. for (CandidateSector& candidateSector : m_candidateSectors)
  456. {
  457. if (candidateSector.m_rhiDrawPacket && AZ::ShapeIntersection::Overlaps(viewFrustum, candidateSector.m_aabb))
  458. {
  459. view->AddDrawPacket(candidateSector.m_rhiDrawPacket);
  460. if (auxGeomPtr && view == mainView)
  461. {
  462. auxGeomPtr->DrawAabb(candidateSector.m_aabb, AZ::Colors::Red, AZ::RPI::AuxGeomDraw::DrawStyle::Line);
  463. }
  464. }
  465. }
  466. }
  467. }
  468. void TerrainMeshManager::SetRebuildDrawPackets()
  469. {
  470. m_rebuildDrawPackets = true;
  471. }
  472. void TerrainMeshManager::RebuildDrawPackets()
  473. {
  474. m_materialInstance->ApplyGlobalShaderOptions();
  475. m_cachedDrawData.clear();
  476. m_candidateSectors.clear();
  477. // Rebuild common draw packet data
  478. m_materialInstance->ForAllShaderItems(
  479. [&](const AZ::Name& materialPipelineName, const AZ::RPI::ShaderCollection::Item& shaderItem)
  480. {
  481. if (!shaderItem.IsEnabled())
  482. {
  483. return true;
  484. }
  485. // Force load and cache shader instances.
  486. AZ::Data::Instance<AZ::RPI::Shader> shader = AZ::RPI::Shader::FindOrCreate(shaderItem.GetShaderAsset());
  487. if (!shader)
  488. {
  489. AZ_Error(
  490. TerrainMeshManagerName,
  491. false,
  492. "Shader '%s'. Failed to find or create instance",
  493. shaderItem.GetShaderAsset()->GetName().GetCStr());
  494. return true;
  495. }
  496. // Skip the shader item without creating the shader instance
  497. // if the mesh is not going to be rendered based on the draw tag
  498. AZ::RHI::RHISystemInterface* rhiSystem = AZ::RHI::RHISystemInterface::Get();
  499. AZ::RHI::DrawListTagRegistry* drawListTagRegistry = rhiSystem->GetDrawListTagRegistry();
  500. // Use the explicit draw list override if exists.
  501. AZ::RHI::DrawListTag drawListTag = shaderItem.GetDrawListTagOverride();
  502. if (drawListTag.IsNull())
  503. {
  504. drawListTag = drawListTagRegistry->FindTag(shaderItem.GetShaderAsset()->GetDrawListName());
  505. }
  506. if (!m_parentScene->HasOutputForPipelineState(drawListTag))
  507. {
  508. // drawListTag not found in this scene, so skip this item
  509. return true;
  510. }
  511. // Set all unspecified shader options to default values, so that we get the most specialized variant possible.
  512. // (because FindVariantStableId treats unspecified options as a request specifically for a variant that doesn't specify those
  513. // options) [GFX TODO][ATOM-3883] We should consider updating the FindVariantStableId algorithm to handle default values for us,
  514. // and remove this step here.
  515. AZ::RPI::ShaderOptionGroup shaderOptions = *shaderItem.GetShaderOptions();
  516. shaderOptions.SetUnspecifiedToDefaultValues();
  517. const AZ::RPI::ShaderVariantId finalVariantId = shaderOptions.GetShaderVariantId();
  518. const AZ::RPI::ShaderVariant& variant = shader->GetVariant(finalVariantId);
  519. AZ::RHI::PipelineStateDescriptorForDraw pipelineStateDescriptor;
  520. variant.ConfigurePipelineState(pipelineStateDescriptor, shaderOptions);
  521. AZ::RHI::InputStreamLayoutBuilder layoutBuilder;
  522. layoutBuilder.AddBuffer()->Channel(AZ::RHI::ShaderSemantic{ "POSITION", 0 }, XYPositionFormat);
  523. layoutBuilder.AddBuffer()->Channel(AZ::RHI::ShaderSemantic{ "POSITION", 1 }, HeightFormat)->Padding(2);
  524. layoutBuilder.AddBuffer()->Channel(AZ::RHI::ShaderSemantic{ "NORMAL", 0 }, NormalFormat)->Padding(2);
  525. layoutBuilder.AddBuffer()->Channel(AZ::RHI::ShaderSemantic{ "POSITION", 2 }, HeightFormat)->Padding(2);
  526. layoutBuilder.AddBuffer()->Channel(AZ::RHI::ShaderSemantic{ "NORMAL", 1 }, NormalFormat)->Padding(2);
  527. pipelineStateDescriptor.m_inputStreamLayout = layoutBuilder.End();
  528. m_parentScene->ConfigurePipelineState(drawListTag, pipelineStateDescriptor);
  529. const AZ::RHI::PipelineState* pipelineState = shader->AcquirePipelineState(pipelineStateDescriptor);
  530. if (!pipelineState)
  531. {
  532. AZ_Error(
  533. TerrainMeshManagerName,
  534. false,
  535. "Shader '%s'. Failed to acquire default pipeline state",
  536. shaderItem.GetShaderAsset()->GetName().GetCStr());
  537. return true;
  538. }
  539. auto drawSrgLayout = shader->GetAsset()->GetDrawSrgLayout(shader->GetSupervariantIndex());
  540. m_cachedDrawData.push_back({ shader, shaderOptions, pipelineState, drawListTag, drawSrgLayout, variant, materialPipelineName });
  541. return true;
  542. });
  543. // Rebuild the draw packets themselves
  544. for (auto& lodGrid : m_sectorLods)
  545. {
  546. for (auto& sector : lodGrid.m_sectors)
  547. {
  548. BuildDrawPacket(sector);
  549. }
  550. }
  551. }
  552. void TerrainMeshManager::OnTerrainDataCreateEnd()
  553. {
  554. OnTerrainDataChanged(AZ::Aabb::CreateNull(), TerrainDataChangedMask::HeightData);
  555. }
  556. void TerrainMeshManager::OnTerrainDataDestroyBegin()
  557. {
  558. ClearSectorBuffers();
  559. m_rebuildSectors = true;
  560. }
  561. void TerrainMeshManager::OnTerrainDataChanged([[maybe_unused]] const AZ::Aabb& dirtyRegion, TerrainDataChangedMask dataChangedMask)
  562. {
  563. if ((dataChangedMask & (TerrainDataChangedMask::HeightData | TerrainDataChangedMask::Settings)) != TerrainDataChangedMask::None)
  564. {
  565. AzFramework::Terrain::FloatRange heightBounds = AzFramework::Terrain::FloatRange::CreateNull();
  566. AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(
  567. heightBounds, &AzFramework::Terrain::TerrainDataRequests::GetTerrainHeightBounds);
  568. float queryResolution = 1.0f;
  569. AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(
  570. queryResolution, &AzFramework::Terrain::TerrainDataRequests::GetTerrainHeightQueryResolution);
  571. bool gridSizeChanged = UpdateGridSize(m_config.m_firstLodDistance);
  572. // Sectors need to be rebuilt when certain settings change.
  573. m_rebuildSectors = m_rebuildSectors || (m_sampleSpacing != queryResolution) || (heightBounds != m_worldHeightBounds) || gridSizeChanged;
  574. m_worldHeightBounds = heightBounds;
  575. m_sampleSpacing = queryResolution;
  576. if (dirtyRegion.IsValid())
  577. {
  578. if (!m_rebuildSectors)
  579. {
  580. // Rebuild any sectors in the dirty region if they aren't all being rebuilt
  581. AZStd::vector<AZStd::vector<Sector*>> sectorsToUpdate(m_sectorLods.size());
  582. ForOverlappingSectors(dirtyRegion,
  583. [&sectorsToUpdate](Sector& sectorData, uint32_t lodLevel)
  584. {
  585. sectorsToUpdate.at(lodLevel).push_back(&sectorData);
  586. }
  587. );
  588. if (!sectorsToUpdate.empty())
  589. {
  590. ProcessSectorUpdates(sectorsToUpdate);
  591. }
  592. }
  593. }
  594. }
  595. }
  596. void TerrainMeshManager::CreateCommonBuffers()
  597. {
  598. // This function initializes positions and indices that are common to all terrain sectors. The indices are laid out
  599. // using a z-order curve (Morton code) which helps triangles which are close in space to also be close in the index
  600. // buffer. This in turn increases the probability that previously processed vertices will be in the vertex cache.
  601. // Generate x and y coordinates using Moser-de Bruijn sequences, so the final z-order position can be found quickly by interleaving.
  602. AZ_Assert(m_gridSize < AZStd::numeric_limits<uint8_t>::max(),
  603. "The following equation to generate z-order indices requires the number to be 8 or fewer bits.");
  604. AZStd::vector<uint16_t> zOrderX(m_gridSize);
  605. AZStd::vector<uint16_t> zOrderY(m_gridSize);
  606. for (uint16_t i = 0; i < m_gridSize; ++i)
  607. {
  608. // This will take any 8 bit number and put 0's in between each bit. For instance 0b1011 becomes 0b1000101.
  609. uint16_t value = ((i * 0x0101010101010101ULL & 0x8040201008040201ULL) * 0x0102040810204081ULL >> 49) & 0x5555;
  610. zOrderX.at(i) = value;
  611. zOrderY.at(i) = value << 1;
  612. }
  613. AZStd::vector<uint16_t> indices;
  614. indices.resize_no_construct(m_gridSize * m_gridSize * 6); // total number of quads, 2 triangles with 6 indices per quad.
  615. // Create the indices for a mesh patch in z-order for vertex cache optimization.
  616. for (uint16_t y = 0; y < m_gridSize; ++y)
  617. {
  618. for (uint16_t x = 0; x < m_gridSize; ++x)
  619. {
  620. uint32_t quadOrder = (zOrderX[x] | zOrderY[y]); // Interleave the x and y arrays from above for a final z-order index.
  621. quadOrder *= 6; // 6 indices per quad (2 triangles, 3 vertices each)
  622. const uint16_t topLeft = y * m_gridVerts1D + x;
  623. const uint16_t topRight = topLeft + 1;
  624. const uint16_t bottomLeft = topLeft + m_gridVerts1D;
  625. const uint16_t bottomRight = bottomLeft + 1;
  626. indices.at(quadOrder + 0) = topLeft;
  627. indices.at(quadOrder + 1) = topRight;
  628. indices.at(quadOrder + 2) = bottomLeft;
  629. indices.at(quadOrder + 3) = bottomLeft;
  630. indices.at(quadOrder + 4) = topRight;
  631. indices.at(quadOrder + 5) = bottomRight;
  632. }
  633. }
  634. // Infer the vertex order from the indices for cache efficient vertex buffer reads. Create a table that
  635. // can quickly map from a linear order (y * m_gridVerts1D + x) to the order dictated by the indices. Update
  636. // the index buffer to point directly to these new indices.
  637. constexpr uint16_t VertexNotSet = 0xFFFF;
  638. m_vertexOrder = AZStd::vector<uint16_t>(m_gridVerts2D, VertexNotSet);
  639. uint16_t vertex = 0;
  640. for (uint16_t& index : indices)
  641. {
  642. if (m_vertexOrder.at(index) == VertexNotSet)
  643. {
  644. // This is the first time this vertex has been seen in the index buffer, add it to the vertex order mapper.
  645. m_vertexOrder.at(index) = vertex;
  646. index = vertex;
  647. ++vertex;
  648. }
  649. else
  650. {
  651. // This vertex has already been added, so just update the index buffer to point to it.
  652. index = m_vertexOrder.at(index);
  653. }
  654. }
  655. m_indexBuffer = CreateMeshBufferInstance(
  656. AZ::RHI::GetFormatSize(AZ::RHI::Format::R16_UINT),
  657. aznumeric_cast<uint32_t>(indices.size()),
  658. indices.data());
  659. if (m_rayTracingEnabled)
  660. {
  661. // Generate a 32 bit index buffer for ray tracing by copying and transforming the 16 bit index buffer.
  662. AZStd::vector<uint32_t> rtIndices;
  663. rtIndices.resize_no_construct(indices.size());
  664. AZStd::transform(indices.begin(), indices.end(), rtIndices.begin(),
  665. [](uint16_t value)
  666. {
  667. return static_cast<uint32_t>(value);
  668. }
  669. );
  670. m_rtIndexBuffer = CreateMeshBufferInstance(
  671. AZ::RHI::GetFormatSize(AZ::RHI::Format::R32_UINT),
  672. aznumeric_cast<uint32_t>(rtIndices.size()),
  673. rtIndices.data());
  674. }
  675. // Create x/y positions. These are the same for all sectors since they're in local space.
  676. m_xyPositions.resize_no_construct(m_gridVerts2D);
  677. for (uint8_t y = 0; y < m_gridVerts1D; ++y)
  678. {
  679. for (uint8_t x = 0; x < m_gridVerts1D; ++x)
  680. {
  681. uint16_t zOrderCoord = m_vertexOrder.at(y * m_gridVerts1D + x);
  682. m_xyPositions.at(zOrderCoord) = { x, y };
  683. }
  684. }
  685. m_xyPositionsBuffer = CreateMeshBufferInstance(
  686. AZ::RHI::GetFormatSize(XYPositionFormat),
  687. aznumeric_cast<uint32_t>(m_xyPositions.size()),
  688. m_xyPositions.data());
  689. m_dummyLodHeightsNormalsBuffer = CreateMeshBufferInstance(sizeof(HeightNormalVertex), m_gridVerts2D, nullptr);
  690. }
  691. void TerrainMeshManager::UpdateSectorBuffers(Sector& sector, const AZStd::span<const HeightNormalVertex> heightsNormals)
  692. {
  693. sector.m_heightsNormalsBuffer->UpdateData(heightsNormals.data(), heightsNormals.size_bytes());
  694. if (sector.m_rtData)
  695. {
  696. // While heightsNormals is in the exact format the terrain shader expects for optimum efficiency, for
  697. // ray tracing it needs to be a more conventional layout. So here we generate more traditional R32G32B32
  698. // data from the highly compressed HeightNormalVertex.
  699. struct RtVert
  700. {
  701. float x;
  702. float y;
  703. float z;
  704. };
  705. AZStd::vector<RtVert> rtPositions(heightsNormals.size());
  706. AZStd::vector<RtVert> rtNormals(heightsNormals.size());
  707. AZ_Assert(heightsNormals.size() == m_gridVerts2D, "Unexpected number of vertices.");
  708. constexpr float maxHeight = static_cast<float>(AZStd::numeric_limits<HeightDataType>::max());
  709. constexpr float maxNormal = static_cast<float>(AZStd::numeric_limits<NormalDataType>::max());
  710. for (uint32_t i = 0; i < heightsNormals.size(); ++i)
  711. {
  712. const HeightNormalVertex& heightNormal = heightsNormals[i];
  713. XYPosition xyPosition = m_xyPositions.at(i);
  714. float xyPositionMax = static_cast<float>(m_gridSize);
  715. rtPositions.at(i) =
  716. {
  717. xyPosition.m_posx / xyPositionMax,
  718. xyPosition.m_posy / xyPositionMax,
  719. heightNormal.m_height == NoTerrainVertexHeight ?
  720. 0.0f :
  721. heightNormal.m_height / maxHeight,
  722. };
  723. float normalX = heightNormal.m_normal.first / maxNormal;
  724. float normalY = heightNormal.m_normal.second / maxNormal;
  725. // It's a little unfortunate to use a sqrt to decode a normal which used a sqrt to encode in the
  726. // first place, but this avoids branching around ray tracing in GatherMeshData(). It also helps ensure
  727. // the ray traced normal lines up with the compressed one used in forward pass.
  728. float normalZ = sqrt(AZStd::GetMax(0.0f, 1.0f - normalX * normalX - normalY * normalY));
  729. rtNormals.at(i) = { normalX, normalY, normalZ };
  730. }
  731. sector.m_rtData->m_positionsBuffer->UpdateData(rtPositions.data(), rtPositions.size() * sizeof(RtVert));
  732. sector.m_rtData->m_normalsBuffer->UpdateData(rtNormals.data(), rtNormals.size() * sizeof(RtVert));
  733. // If the mesh is currently visible, it must be removed and re-added to update its data.
  734. for (RtSector::MeshGroup& meshGroup : sector.m_rtData->m_meshGroups)
  735. {
  736. if (meshGroup.m_isVisible)
  737. {
  738. AZ::Vector3 translation = sector.m_aabb.GetMin();
  739. translation.SetZ(m_worldHeightBounds.m_min);
  740. meshGroup.m_mesh.m_transform = AZ::Transform::CreateTranslation(translation);
  741. m_rayTracingFeatureProcessor->RemoveMesh(meshGroup.m_id);
  742. m_rayTracingFeatureProcessor->AddMesh(meshGroup.m_id, meshGroup.m_mesh, meshGroup.m_submeshVector);
  743. }
  744. }
  745. }
  746. }
  747. void TerrainMeshManager::UpdateSectorLodBuffers(Sector& sector,
  748. const AZStd::span<const HeightNormalVertex> originalHeightsNormals,
  749. const AZStd::span<const HeightNormalVertex> lodHeightsNormals)
  750. {
  751. // Store the height and normal information for the next lod level in each vertex for continuous LOD.
  752. AZStd::vector<HeightNormalVertex> clodHeightNormals;
  753. clodHeightNormals.resize_no_construct(m_gridVerts2D);
  754. const uint16_t lodGridVerts1D = (m_gridVerts1D >> 1) + 1;
  755. for (uint16_t yPos = 0; yPos < m_gridVerts1D; ++yPos)
  756. {
  757. for (uint16_t xPos = 0; xPos < m_gridVerts1D; ++xPos)
  758. {
  759. uint16_t index = yPos * m_gridVerts1D + xPos;
  760. uint16_t lodIndex1 = (yPos / 2) * lodGridVerts1D + (xPos / 2);
  761. uint16_t lodIndex2 = lodIndex1;
  762. if (xPos % 2 == 1)
  763. {
  764. // x position is between two vertices in the row
  765. ++lodIndex1;
  766. }
  767. if (yPos % 2 == 1)
  768. {
  769. // y position is between two vertices in the column
  770. lodIndex2 += lodGridVerts1D;
  771. }
  772. const uint16_t zOrderIndex = m_vertexOrder.at(index);
  773. if (lodHeightsNormals[lodIndex1].m_height == NoTerrainVertexHeight || lodHeightsNormals[lodIndex2].m_height == NoTerrainVertexHeight)
  774. {
  775. // One of the neighboring vertices has no data, so use the original height and normal
  776. clodHeightNormals[zOrderIndex] = originalHeightsNormals[zOrderIndex];
  777. }
  778. else
  779. {
  780. clodHeightNormals[zOrderIndex] =
  781. {
  782. HeightDataType((lodHeightsNormals[lodIndex1].m_height + lodHeightsNormals[lodIndex2].m_height) / 2),
  783. NormalXYDataType(
  784. {
  785. int8_t((lodHeightsNormals[lodIndex1].m_normal.first + lodHeightsNormals[lodIndex2].m_normal.first) / 2),
  786. int8_t((lodHeightsNormals[lodIndex1].m_normal.second + lodHeightsNormals[lodIndex2].m_normal.second) / 2)
  787. })
  788. };
  789. }
  790. }
  791. }
  792. sector.m_lodHeightsNormalsBuffer->UpdateData(clodHeightNormals.data(), clodHeightNormals.size() * sizeof(HeightNormalVertex), 0);
  793. }
  794. void TerrainMeshManager::GatherMeshData(SectorDataRequest request, AZStd::vector<HeightNormalVertex>& meshHeightsNormals, AZ::Aabb& meshAabb, bool& terrainExistsAnywhere)
  795. {
  796. const AZ::Vector2 stepSize(request.m_vertexSpacing);
  797. const uint16_t querySamplesX = request.m_samplesX + 2; // extra row / column on each side for normals.
  798. const uint16_t querySamplesY = request.m_samplesY + 2; // extra row / column on each side for normals.
  799. const uint16_t querySamplesCount = querySamplesX * querySamplesY;
  800. const uint16_t outputSamplesCount = request.m_samplesX * request.m_samplesY;
  801. AZStd::vector<float> heights;
  802. heights.resize_no_construct(querySamplesCount);
  803. meshHeightsNormals.resize_no_construct(outputSamplesCount);
  804. auto perPositionCallback = [this, &heights, querySamplesX, &terrainExistsAnywhere]
  805. (size_t xIndex, size_t yIndex, const AzFramework::SurfaceData::SurfacePoint& surfacePoint, bool terrainExists)
  806. {
  807. static constexpr float HeightDoesNotExistValue = -1.0f;
  808. const float height = surfacePoint.m_position.GetZ() - m_worldHeightBounds.m_min;
  809. heights.at(yIndex * querySamplesX + xIndex) = terrainExists ? height : HeightDoesNotExistValue;
  810. terrainExistsAnywhere = terrainExistsAnywhere || terrainExists;
  811. };
  812. AzFramework::Terrain::TerrainQueryRegion queryRegion(
  813. request.m_worldStartPosition - stepSize, querySamplesX, querySamplesY, stepSize);
  814. AzFramework::Terrain::TerrainDataRequestBus::Broadcast(
  815. &AzFramework::Terrain::TerrainDataRequests::QueryRegion,
  816. queryRegion,
  817. AzFramework::Terrain::TerrainDataRequests::TerrainDataMask::Heights,
  818. perPositionCallback,
  819. request.m_samplerType);
  820. if (!terrainExistsAnywhere)
  821. {
  822. // No height data, so just return
  823. return;
  824. }
  825. float zExtents = (m_worldHeightBounds.m_max - m_worldHeightBounds.m_min);
  826. const float rcpWorldZ = 1.0f / zExtents;
  827. const float vertexSpacing2 = request.m_vertexSpacing * 2.0f;
  828. // initialize min/max heights to the max/min possible values so they're immediately updated when a valid point is found.
  829. float minHeight = zExtents;
  830. float maxHeight = 0.0f;
  831. // float versions of int max to make sure a int->float conversion doesn't happen at each loop iteration.
  832. constexpr float MaxHeightHalf = float(AZStd::numeric_limits<HeightDataType>::max() / 2);
  833. constexpr float MaxNormal = AZStd::numeric_limits<NormalDataType>::max();
  834. for (uint16_t y = 0; y < request.m_samplesY; ++y)
  835. {
  836. const uint16_t queryY = y + 1;
  837. for (uint16_t x = 0; x < request.m_samplesX; ++x)
  838. {
  839. const uint16_t queryX = x + 1;
  840. const uint16_t queryCoord = queryY * querySamplesX + queryX;
  841. uint16_t coord = y * request.m_samplesX + x;
  842. coord = request.m_useVertexOrderRemap ? m_vertexOrder.at(coord) : coord;
  843. const float height = heights.at(queryCoord);
  844. if (height < 0.0f)
  845. {
  846. // Primary terrain height is limited to every-other bit, and clod heights can be in-between or the same
  847. // as any of the primary heights. This leaves the max value as the single value that is never used by a
  848. // legitimate height.
  849. meshHeightsNormals.at(coord).m_height = NoTerrainVertexHeight;
  850. continue;
  851. }
  852. const float clampedHeight = AZ::GetClamp(height * rcpWorldZ, 0.0f, 1.0f);
  853. // For continuous LOD, it needs to be possible to create a height that's exactly in between any other height, so scale
  854. // and quantize to half the height, then multiply by 2, ensuring there's always an in-between value available.
  855. const HeightDataType quantizedHeight = aznumeric_cast<HeightDataType>(clampedHeight * MaxHeightHalf + 0.5f); // always positive, so just add 0.5 to round.
  856. meshHeightsNormals.at(coord).m_height = quantizedHeight * 2;
  857. if (minHeight > height)
  858. {
  859. minHeight = height;
  860. }
  861. else if (maxHeight < height)
  862. {
  863. maxHeight = height;
  864. }
  865. auto getSlope = [&](float height1, float height2)
  866. {
  867. if (height1 < 0.0f)
  868. {
  869. if (height2 < 0.0f)
  870. {
  871. // Assume no slope if the left and right vertices both don't exist.
  872. return 0.0f;
  873. }
  874. else
  875. {
  876. return (height - height2) / request.m_vertexSpacing;
  877. }
  878. }
  879. else
  880. {
  881. if (height2 < 0.0f)
  882. {
  883. return (height1 - height) / request.m_vertexSpacing;
  884. }
  885. else
  886. {
  887. return (height1 - height2) / vertexSpacing2;
  888. }
  889. }
  890. };
  891. const float leftHeight = heights.at(queryCoord - 1);
  892. const float rightHeight = heights.at(queryCoord + 1);
  893. const float xSlope = getSlope(leftHeight, rightHeight);
  894. const float normalX = xSlope / sqrt(xSlope * xSlope + 1); // sin(arctan(xSlope)
  895. const float upHeight = heights.at(queryCoord - querySamplesX);
  896. const float downHeight = heights.at(queryCoord + querySamplesX);
  897. const float ySlope = getSlope(upHeight, downHeight);
  898. const float normalY = ySlope / sqrt(ySlope * ySlope + 1); // sin(arctan(ySlope)
  899. meshHeightsNormals.at(coord).m_normal =
  900. {
  901. aznumeric_cast<NormalDataType>(AZStd::lround(normalX * MaxNormal)),
  902. aznumeric_cast<NormalDataType>(AZStd::lround(normalY * MaxNormal)),
  903. };
  904. }
  905. }
  906. if (maxHeight < minHeight)
  907. {
  908. // All height samples were invalid, so set the aabb to null.
  909. meshAabb.SetNull();
  910. }
  911. else
  912. {
  913. float width = (request.m_samplesX - 1) * request.m_vertexSpacing;
  914. float height = (request.m_samplesY - 1) * request.m_vertexSpacing;
  915. AZ::Vector3 aabbMin = AZ::Vector3(request.m_worldStartPosition.GetX(), request.m_worldStartPosition.GetY(), m_worldHeightBounds.m_min + minHeight);
  916. AZ::Vector3 aabbMax = AZ::Vector3(aabbMin.GetX() + width, aabbMin.GetY() + height, m_worldHeightBounds.m_min + maxHeight);
  917. meshAabb.Set(aabbMin, aabbMax);
  918. }
  919. }
  920. void TerrainMeshManager::ProcessSectorUpdates(AZStd::vector<AZStd::vector<Sector*>>& sectorUpdates)
  921. {
  922. AZ::JobCompletion jobCompletion;
  923. for (uint32_t lodLevel = 0; lodLevel < sectorUpdates.size(); ++lodLevel)
  924. {
  925. auto& sectors = sectorUpdates.at(lodLevel);
  926. if (sectors.empty())
  927. {
  928. continue;
  929. }
  930. for (Sector* sector : sectors)
  931. {
  932. const float gridMeters = (m_gridSize * m_sampleSpacing) * (1 << lodLevel);
  933. const auto jobLambda = [this, sector, gridMeters]() -> void
  934. {
  935. AZStd::vector<HeightNormalVertex> meshHeightsNormals;
  936. {
  937. SectorDataRequest request;
  938. request.m_samplesX = m_gridVerts1D;
  939. request.m_samplesY = m_gridVerts1D;
  940. request.m_worldStartPosition = sector->m_worldCoord.ToVector2() * gridMeters;
  941. request.m_vertexSpacing = gridMeters / m_gridSize;
  942. request.m_useVertexOrderRemap = true;
  943. GatherMeshData(request, meshHeightsNormals, sector->m_aabb, sector->m_hasData);
  944. if (sector->m_hasData)
  945. {
  946. UpdateSectorBuffers(*sector, meshHeightsNormals);
  947. }
  948. // Create AABBs for each quadrant for cases where this LOD needs to fill in a gap in a lower LOD.
  949. CreateAabbQuadrants(sector->m_aabb, sector->m_quadrantAabbs);
  950. }
  951. if (m_config.m_clodEnabled && sector->m_hasData)
  952. {
  953. SectorDataRequest request;
  954. uint16_t m_gridSizeNextLod = (m_gridSize >> 1);
  955. request.m_samplesX = m_gridSizeNextLod + 1;
  956. request.m_samplesY = m_gridSizeNextLod + 1;
  957. request.m_worldStartPosition = sector->m_worldCoord.ToVector2() * gridMeters;
  958. request.m_vertexSpacing = gridMeters / m_gridSizeNextLod;
  959. AZ::Aabb dummyAabb = AZ::Aabb::CreateNull(); // Don't update the sector aabb based on only the clod vertices.
  960. bool terrainExists = false;
  961. AZStd::vector<HeightNormalVertex> meshLodHeightsNormals;
  962. GatherMeshData(request, meshLodHeightsNormals, dummyAabb, terrainExists);
  963. if (!terrainExists)
  964. {
  965. // It's unlikely but possible for the higher lod to have data and the lower lod to not. In that case
  966. // meshLodHeights will be empty, so fill it with values that represent "no data".
  967. HeightNormalVertex defaultValue = { NoTerrainVertexHeight, NormalXYDataType(NormalDataType(0), NormalDataType(0)) };
  968. AZStd::fill(meshLodHeightsNormals.begin(), meshLodHeightsNormals.end(), defaultValue);
  969. }
  970. UpdateSectorLodBuffers(*sector, meshHeightsNormals, meshLodHeightsNormals);
  971. }
  972. };
  973. ShaderObjectData objectSrgData;
  974. objectSrgData.m_xyTranslation = { sector->m_worldCoord.m_x * gridMeters, sector->m_worldCoord.m_y * gridMeters };
  975. objectSrgData.m_xyScale = gridMeters * (aznumeric_cast<float>(AZStd::numeric_limits<uint8_t>::max()) / m_gridSize);
  976. objectSrgData.m_lodLevel = lodLevel;
  977. objectSrgData.m_rcpLodLevel = 1.0f / (lodLevel + 1);
  978. sector->m_srg->SetConstant(m_patchDataIndex, objectSrgData);
  979. if (!sector->m_isQueuedForSrgCompile)
  980. {
  981. m_sectorsThatNeedSrgCompiled.push_back(sector);
  982. }
  983. sector->m_hasData = false; // mark the terrain as not having data for now. Once a job runs if it actually has data it'll flip to true.
  984. // Check against the area of terrain that could appear in this sector for any terrain areas. If none exist then skip updating the mesh.
  985. bool hasTerrain = false;
  986. AZ::Vector3 minAabb = AZ::Vector3(sector->m_worldCoord.m_x * gridMeters, sector->m_worldCoord.m_y * gridMeters, m_worldHeightBounds.m_min);
  987. AZ::Aabb sectorBounds = AZ::Aabb::CreateFromMinMax(minAabb,
  988. minAabb + AZ::Vector3(gridMeters, gridMeters, m_worldHeightBounds.m_max - m_worldHeightBounds.m_min));
  989. AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(
  990. hasTerrain, &AzFramework::Terrain::TerrainDataRequests::TerrainAreaExistsInBounds, sectorBounds);
  991. if (hasTerrain)
  992. {
  993. AZ::Job* executeGroupJob = aznew AZ::JobFunction<decltype(jobLambda)>(jobLambda, true, nullptr); // Auto-deletes
  994. executeGroupJob->SetDependent(&jobCompletion);
  995. executeGroupJob->Start();
  996. }
  997. }
  998. }
  999. jobCompletion.StartAndWaitForCompletion();
  1000. m_candidateSectors.clear(); // Force recalculation of candidate sectors since AABBs could have changed.
  1001. }
  1002. void TerrainMeshManager::UpdateCandidateSectors()
  1003. {
  1004. // Gather a list of all sectors that could render based on their status, lod, and camera position.
  1005. float maxDistanceSq = m_config.m_firstLodDistance * m_config.m_firstLodDistance;
  1006. uint32_t nextLodSectorCount = m_1dSectorCount * 2; // The number of this lod's sectors that would fit into the next lod's space.
  1007. AZStd::vector<bool> previousSelectedSectors;
  1008. m_candidateSectors.clear();
  1009. AZStd::vector<RayTracedItem> newRayTraceItems;
  1010. if (m_rayTracingEnabled)
  1011. {
  1012. newRayTraceItems.reserve(m_sectorLods.size() * m_1dSectorCount * m_1dSectorCount);
  1013. }
  1014. for (uint32_t lodLevel = 0; lodLevel < m_sectorLods.size(); ++lodLevel)
  1015. {
  1016. auto& lodGrid = m_sectorLods.at(lodLevel);
  1017. // Each sector in an LOD is half the size of a sector in the next LOD in each direction, so 4 sectors
  1018. // in this LOD equal one sector in the next LOD. Construct a grid of bools for each sector in this
  1019. // LOD that covers the entire space of the next LOD, and mark everything to false. As sectors in
  1020. // this LOD are drawn, mark appropriate locations in the grid as true. When processing the next
  1021. // LOD, each of the next LOD's sectors will look up the 4 entries in this that represent quadrants
  1022. // of that sector to determine whether to draw nothing, specific quadrants, or the entire sector.
  1023. AZStd::vector<bool> selectedSectors(nextLodSectorCount * nextLodSectorCount, false);
  1024. Vector2i selectedSectorStartCoord{ 0, 0 };
  1025. if (lodLevel == m_sectorLods.size() - 1)
  1026. {
  1027. // There is no next lod, so just use this one's start coord to avoid lots of checks in the for loop.
  1028. selectedSectorStartCoord = m_sectorLods.at(lodLevel).m_startCoord;
  1029. }
  1030. else
  1031. {
  1032. // This is the start coord of the next LOD in the current LOD's scale.
  1033. selectedSectorStartCoord = m_sectorLods.at(lodLevel + 1).m_startCoord * 2;
  1034. }
  1035. for (uint32_t sectorIndex = 0; sectorIndex < lodGrid.m_sectors.size(); ++sectorIndex)
  1036. {
  1037. Sector& sector = lodGrid.m_sectors.at(sectorIndex);
  1038. Vector2i selectedCoord = sector.m_worldCoord - selectedSectorStartCoord;
  1039. uint32_t selectedIndex = selectedCoord.m_y * nextLodSectorCount + selectedCoord.m_x;
  1040. if (!sector.m_hasData)
  1041. {
  1042. selectedSectors.at(selectedIndex) = true; // Terrain just doesn't exist here, so mark as "selected" so another LOD doesn't try to draw here.
  1043. continue;
  1044. }
  1045. const float aabbMinDistanceSq = sector.m_aabb.GetDistanceSq(m_cameraPosition);
  1046. if (aabbMinDistanceSq < maxDistanceSq)
  1047. {
  1048. selectedSectors.at(selectedIndex) = true;
  1049. if (lodLevel == 0)
  1050. {
  1051. // Since this is the first lod, no previous lod to check, so just draw.
  1052. m_candidateSectors.push_back({ sector.m_aabb, sector.m_rhiDrawPacket.get() });
  1053. if (sector.m_rtData)
  1054. {
  1055. newRayTraceItems.push_back({ &sector, 0, lodLevel });
  1056. }
  1057. continue;
  1058. }
  1059. Vector2i previousCoord = (sector.m_worldCoord - lodGrid.m_startCoord) * 2;
  1060. uint32_t previousDrawnIndex = previousCoord.m_y * nextLodSectorCount + previousCoord.m_x;
  1061. // Check the 4 sectors in the previous LOD that are covered by this sector.
  1062. uint8_t coveredByHigherLod =
  1063. (uint8_t(previousSelectedSectors.at(previousDrawnIndex)) << 0) | // Top left
  1064. (uint8_t(previousSelectedSectors.at(previousDrawnIndex + 1)) << 1) | // Top right
  1065. (uint8_t(previousSelectedSectors.at(previousDrawnIndex + nextLodSectorCount)) << 2) | // Bottom left
  1066. (uint8_t(previousSelectedSectors.at(previousDrawnIndex + nextLodSectorCount + 1)) << 3); // Bottom right
  1067. if (coveredByHigherLod == 0b1111)
  1068. {
  1069. continue; // Completely covered by previous LOD, so do nothing
  1070. }
  1071. if (coveredByHigherLod == 0b0000)
  1072. {
  1073. // Not covered at all by previous LOD, so the draw entire sector
  1074. m_candidateSectors.push_back({ sector.m_aabb, sector.m_rhiDrawPacket.get() });
  1075. if (sector.m_rtData)
  1076. {
  1077. newRayTraceItems.push_back({ &sector, 0, lodLevel });
  1078. }
  1079. }
  1080. else
  1081. {
  1082. // Partially covered by previous LOD. Draw only missing quadrants
  1083. for (uint8_t i = 0; i < 4; ++i)
  1084. {
  1085. if ((coveredByHigherLod & 0b0001) == 0b0000)
  1086. {
  1087. m_candidateSectors.push_back({ sector.m_quadrantAabbs.at(i), sector.m_rhiDrawPacketQuadrant.at(i).get() });
  1088. if (sector.m_rtData)
  1089. {
  1090. newRayTraceItems.push_back({ &sector, i + 1u, lodLevel });
  1091. }
  1092. }
  1093. coveredByHigherLod >>= 1;
  1094. }
  1095. }
  1096. }
  1097. }
  1098. maxDistanceSq = maxDistanceSq * 4.0f; // Double the distance with squared distances is * 2^2.
  1099. previousSelectedSectors = AZStd::move(selectedSectors);
  1100. }
  1101. if (m_rayTracingEnabled)
  1102. {
  1103. // Compare the sorted new list to the old list to figure out which ray traced sectors need to be
  1104. // added or removed.
  1105. auto getMeshGroup = [](auto& item) -> auto&
  1106. {
  1107. return item.m_sector->m_rtData->m_meshGroups[item.m_meshGroupIndex];
  1108. };
  1109. AZStd::sort(newRayTraceItems.begin(), newRayTraceItems.end(),
  1110. [&getMeshGroup](const RayTracedItem& value1, const RayTracedItem& value2) -> bool
  1111. {
  1112. return getMeshGroup(value1).m_id < getMeshGroup(value2).m_id;
  1113. }
  1114. );
  1115. auto prevIt = m_rayTracedItems.begin();
  1116. auto newIt = newRayTraceItems.begin();
  1117. auto addMesh = [&](RayTracedItem& item, RtSector::MeshGroup& meshGroup)
  1118. {
  1119. const float gridMeters = (m_gridSize * m_sampleSpacing) * (1 << item.m_lodLevel);
  1120. AZ::Vector3 translation = AZ::Vector3(item.m_sector->m_worldCoord.m_x * gridMeters, item.m_sector->m_worldCoord.m_y * gridMeters, m_worldHeightBounds.m_min);
  1121. meshGroup.m_mesh.m_transform = AZ::Transform::CreateTranslation(translation);
  1122. meshGroup.m_isVisible = true;
  1123. m_rayTracingFeatureProcessor->AddMesh(meshGroup.m_id, meshGroup.m_mesh, meshGroup.m_submeshVector);
  1124. };
  1125. auto removeMesh = [&](RtSector::MeshGroup& meshGroup)
  1126. {
  1127. meshGroup.m_isVisible = false;
  1128. m_rayTracingFeatureProcessor->RemoveMesh(meshGroup.m_id);
  1129. };
  1130. // Since the two lists are sorted, we can easily compare them and figure out which items need
  1131. // to be removed or added. If a uuid shows up in the old list first, then it must not be in the new
  1132. // list, so it needs to be removed, then only the old list iterator is incremented. Similarly if a
  1133. // uuid shows up in the new list first then it must not be in the old list, so it needs to be added.
  1134. // Finally if the uuids match, they're in both lists, and therefore both iterators can be incremented.
  1135. while (prevIt < m_rayTracedItems.end() && newIt < newRayTraceItems.end())
  1136. {
  1137. RtSector::MeshGroup& prevMeshGroup = getMeshGroup(*prevIt);
  1138. RtSector::MeshGroup& newMeshGroup = getMeshGroup(*newIt);
  1139. if (prevMeshGroup.m_id < newMeshGroup.m_id)
  1140. {
  1141. removeMesh(prevMeshGroup);
  1142. ++prevIt;
  1143. }
  1144. else if (prevMeshGroup.m_id > newMeshGroup.m_id)
  1145. {
  1146. addMesh(*newIt, newMeshGroup);
  1147. ++newIt;
  1148. }
  1149. else
  1150. {
  1151. ++prevIt;
  1152. ++newIt;
  1153. }
  1154. }
  1155. // Since the above loop stops when either iterator is done, remaining items in the other iterator need to be handled here.
  1156. while (prevIt < m_rayTracedItems.end())
  1157. {
  1158. removeMesh(getMeshGroup(*prevIt));
  1159. ++prevIt;
  1160. }
  1161. while (newIt < newRayTraceItems.end())
  1162. {
  1163. addMesh(*newIt, getMeshGroup(*newIt));
  1164. ++newIt;
  1165. }
  1166. m_rayTracedItems = AZStd::move(newRayTraceItems);
  1167. }
  1168. }
  1169. void TerrainMeshManager::CreateAabbQuadrants(const AZ::Aabb& aabb, AZStd::span<AZ::Aabb, 4> quadrantAabb)
  1170. {
  1171. // Create 4 AABBs for each quadrant on the xy plane.
  1172. if (aabb.IsValid())
  1173. {
  1174. float centerX = aabb.GetCenter().GetX();
  1175. float centerY = aabb.GetCenter().GetY();
  1176. quadrantAabb[0] = AZ::Aabb::CreateFromMinMax(
  1177. aabb.GetMin(),
  1178. AZ::Vector3(centerX, centerY, aabb.GetMax().GetZ())
  1179. );
  1180. float halfExtentX = aabb.GetXExtent() * 0.5f;
  1181. float halfExtentY = aabb.GetYExtent() * 0.5f;
  1182. quadrantAabb[1] = quadrantAabb[0].GetTranslated(AZ::Vector3(halfExtentX, 0.0f, 0.0f));
  1183. quadrantAabb[2] = quadrantAabb[0].GetTranslated(AZ::Vector3(0.0f, halfExtentY, 0.0f));
  1184. quadrantAabb[3] = quadrantAabb[0].GetTranslated(AZ::Vector3(halfExtentX, halfExtentY, 0.0f));
  1185. }
  1186. else
  1187. {
  1188. AZStd::fill(quadrantAabb.begin(), quadrantAabb.end(), AZ::Aabb::CreateNull());
  1189. }
  1190. }
  1191. template<typename Callback>
  1192. void TerrainMeshManager::ForOverlappingSectors(const AZ::Aabb& bounds, Callback callback)
  1193. {
  1194. const AZ::Vector2 boundsMin2d = AZ::Vector2(bounds.GetMin());
  1195. const AZ::Vector2 boundsMax2d = AZ::Vector2(bounds.GetMax());
  1196. for (uint32_t lodLevel = 0; lodLevel < m_sectorLods.size(); ++lodLevel)
  1197. {
  1198. // Expand the bounds by the spacing of the lod since vertex normals are affected by neighbors.
  1199. // The bounds needs to be 2x what's expected because clod also encodes information about the normals
  1200. // for the next lod level in the current lod level (which has vertices spaced 2x as far apart)
  1201. const AZ::Vector2 lodSpacing = AZ::Vector2(m_sampleSpacing * (1 << lodLevel) * 2.0f);
  1202. const AZ::Vector2 lodBoundsMin2d = boundsMin2d - lodSpacing;
  1203. const AZ::Vector2 lodBoundsMax2d = boundsMax2d + lodSpacing;
  1204. const float gridMeters = (m_gridSize * m_sampleSpacing) * (1 << lodLevel);
  1205. auto& lodGrid = m_sectorLods.at(lodLevel);
  1206. for (Sector& sector : lodGrid.m_sectors)
  1207. {
  1208. const AZ::Vector2 sectorAabbMin2D = sector.m_worldCoord.ToVector2() * gridMeters;
  1209. const AZ::Vector2 sectorAabbMax2D = sectorAabbMin2D + AZ::Vector2(gridMeters);
  1210. const bool overlaps = sectorAabbMin2D.IsLessEqualThan(lodBoundsMax2d) && sectorAabbMax2D.IsGreaterEqualThan(lodBoundsMin2d);
  1211. if (overlaps)
  1212. {
  1213. callback(sector, lodLevel);
  1214. }
  1215. }
  1216. }
  1217. }
  1218. AZ::Data::Instance<AZ::RPI::Buffer> TerrainMeshManager::CreateMeshBufferInstance(uint32_t elementSize, uint32_t elementCount, const void* initialData, const char* name)
  1219. {
  1220. AZ::RPI::CommonBufferDescriptor desc;
  1221. desc.m_poolType = AZ::RPI::CommonBufferPoolType::StaticInputAssembly;
  1222. desc.m_elementSize = elementSize;
  1223. desc.m_byteCount = desc.m_elementSize * elementCount;
  1224. desc.m_bufferData = initialData;
  1225. if (name != nullptr)
  1226. {
  1227. desc.m_bufferName = name;
  1228. }
  1229. return AZ::RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc);
  1230. }
  1231. AZ::Data::Instance<AZ::RPI::Buffer> TerrainMeshManager::CreateRayTracingMeshBufferInstance(AZ::RHI::Format elementFormat, uint32_t elementCount, const void* initialData, const char* name)
  1232. {
  1233. AZ::RPI::CommonBufferDescriptor desc;
  1234. desc.m_poolType = AZ::RPI::CommonBufferPoolType::DynamicInputAssembly;
  1235. desc.m_elementSize = AZ::RHI::GetFormatSize(elementFormat);
  1236. desc.m_byteCount = desc.m_elementSize * elementCount;
  1237. desc.m_bufferData = initialData;
  1238. desc.m_elementFormat = elementFormat;
  1239. if (name != nullptr)
  1240. {
  1241. desc.m_bufferName = name;
  1242. }
  1243. return AZ::RPI::BufferSystemInterface::Get()->CreateBufferFromCommonPool(desc);
  1244. }
  1245. }