3
0

TerrainMeshManager.cpp 69 KB

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