AreaLightExampleComponent.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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 <AreaLightExampleComponent.h>
  9. #include <SampleComponentConfig.h>
  10. #include <Utils/Utils.h>
  11. #include <Automation/ScriptableImGui.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  14. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  15. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  16. #include <Atom/RPI.Public/RPISystemInterface.h>
  17. #include <Atom/RPI.Public/Scene.h>
  18. #include <Atom/RPI.Public/AuxGeom/AuxGeomDraw.h>
  19. #include <Atom/RPI.Public/Image/StreamingImage.h>
  20. #include <Atom/RPI.Public/Image/StreamingImagePool.h>
  21. #include <Atom/RPI.Public/Shader/ShaderSystem.h>
  22. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  23. #include <imgui/imgui.h>
  24. #include <Atom/Feature/Material/MaterialAssignment.h>
  25. #include <RHI/BasicRHIComponent.h>
  26. namespace AtomSampleViewer
  27. {
  28. void AreaLightExampleComponent::Reflect(AZ::ReflectContext* context)
  29. {
  30. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  31. {
  32. serializeContext->Class <AreaLightExampleComponent, AZ::Component>()
  33. ->Version(0)
  34. ;
  35. }
  36. }
  37. AZ::Quaternion AreaLightExampleComponent::Configuration::GetRotationQuaternion()
  38. {
  39. AZ::Quaternion rotation = AZ::Quaternion::CreateIdentity();
  40. rotation.SetFromEulerRadians(AZ::Vector3(m_rotations[0] + AZ::Constants::Pi, m_rotations[1], m_rotations[2]));
  41. return rotation;
  42. }
  43. AZ::Matrix3x3 AreaLightExampleComponent::Configuration::GetRotationMatrix()
  44. {
  45. return AZ::Matrix3x3::CreateFromQuaternion(GetRotationQuaternion());
  46. }
  47. AreaLightExampleComponent::AreaLightExampleComponent()
  48. : m_materialBrowser("@user@/AreaLightExampleComponent/material_browser.xml")
  49. , m_modelBrowser("@user@/AreaLightExampleComponent/model_browser.xml")
  50. {
  51. }
  52. void AreaLightExampleComponent::Activate()
  53. {
  54. // Get Feature processors
  55. m_meshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::MeshFeatureProcessorInterface>();
  56. m_pointLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::PointLightFeatureProcessorInterface>();
  57. m_diskLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::DiskLightFeatureProcessorInterface>();
  58. m_capsuleLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::CapsuleLightFeatureProcessorInterface>();
  59. m_polygonLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::PolygonLightFeatureProcessorInterface>();
  60. m_quadLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::QuadLightFeatureProcessorInterface>();
  61. m_skyBoxFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::SkyBoxFeatureProcessorInterface>();
  62. m_auxGeom = AZ::RPI::AuxGeomFeatureProcessorInterface::GetDrawQueueForScene(m_scene);
  63. // Create background
  64. m_skyBoxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  65. m_skyBoxFeatureProcessor->SetCubemap(Utils::GetSolidColorCubemap(0xFF202020));
  66. m_skyBoxFeatureProcessor->Enable(true);
  67. // Get material and set up material instances
  68. AZ::RPI::AssetUtils::TraceLevel traceLevel = AZ::RPI::AssetUtils::TraceLevel::Assert;
  69. static const char* defaultMaterialPath = "materials/presets/macbeth/00_illuminant.azmaterial";
  70. auto materialAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::MaterialAsset>(defaultMaterialPath, traceLevel);
  71. InitializeMaterials(materialAsset);
  72. // Prepare meshes and lights
  73. auto modelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(m_config.m_modelAssetPath.c_str(), traceLevel);
  74. m_meshHandles.resize(MaxVariants);
  75. UpdateModels(modelAsset);
  76. m_photometricValue.ConvertToPhotometricUnit(AZ::Render::PhotometricUnit::Lumen);
  77. m_lightHandles.resize(MaxVariants);
  78. UpdateLights();
  79. // Enable camera
  80. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  81. azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  82. // Sidebar
  83. m_materialBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  84. {
  85. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::MaterialAsset>() &&
  86. assetInfo.m_assetId.m_subId == 0; // no materials generated from models.
  87. });
  88. m_materialBrowser.Activate();
  89. m_materialBrowserSettings.m_labels.m_root = "Materials";
  90. m_modelBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  91. {
  92. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::ModelAsset>();
  93. });
  94. m_modelBrowser.Activate();
  95. m_modelBrowserSettings.m_labels.m_root = "Models";
  96. m_imguiSidebar.Activate();
  97. m_imguiSidebar.SetHideSidebar(true);
  98. // Connect to busses
  99. AZ::TickBus::Handler::BusConnect();
  100. }
  101. void AreaLightExampleComponent::Deactivate()
  102. {
  103. // Force validation off since it's a global flag.
  104. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(AZ::Name{ "o_area_light_validation" }, AZ::RPI::ShaderOptionValue{ false });
  105. AZ::TickBus::Handler::BusDisconnect();
  106. m_imguiSidebar.Deactivate();
  107. m_modelBrowser.Deactivate();
  108. m_materialBrowser.Deactivate();
  109. ReleaseModels();
  110. ReleaseLights();
  111. m_materialInstances.clear();
  112. m_skyBoxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::None);
  113. m_skyBoxFeatureProcessor->Enable(false);
  114. }
  115. void AreaLightExampleComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint timePoint)
  116. {
  117. DrawUI();
  118. DrawAuxGeom();
  119. }
  120. float AreaLightExampleComponent::GetPositionPercentage(uint32_t index)
  121. {
  122. return aznumeric_cast<float>(index) / aznumeric_cast<float>(m_config.m_count - 1);
  123. }
  124. AZ::Vector3 AreaLightExampleComponent::GetModelPosition(uint32_t index)
  125. {
  126. static float Spacing = 5.0f;
  127. // Total width of n models is Spacing * n, so the start x position is half of that.
  128. float startXPos = aznumeric_cast<float>(m_config.m_count - 1) * 0.5f * -Spacing;
  129. float xPos = startXPos + aznumeric_cast<float>(index) * Spacing;
  130. // y position pushes further away from the camera the more models there are to show.
  131. float yPos = -2.0f + Spacing * m_config.m_count * 0.4f;
  132. // z is slightly negative so the model's center is slightly below the camera's center
  133. float zPos = -1.0f;
  134. return AZ::Vector3(xPos, yPos, zPos);
  135. }
  136. template<typename T>
  137. T AreaLightExampleComponent::GetLerpValue(T values[2], uint32_t index, bool doLerp)
  138. {
  139. if (doLerp)
  140. {
  141. return AZ::Lerp(values[0], values[1], GetPositionPercentage(index));
  142. }
  143. return values[0];
  144. }
  145. AZ::Vector3 AreaLightExampleComponent::GetLightPosition(uint32_t index)
  146. {
  147. AZ::Vector3 position = GetModelPosition(index);
  148. position.SetZ(position.GetZ() + m_config.m_lightDistance);
  149. position += AZ::Vector3::CreateFromFloat3(m_config.m_positionOffset);
  150. return position;
  151. }
  152. void AreaLightExampleComponent::InitializeMaterials(AZ::Data::Asset<AZ::RPI::MaterialAsset> materialAsset)
  153. {
  154. m_roughnessPropertyIndex = materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(AZ::Name("roughness.factor"));
  155. m_metallicPropertyIndex = materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(AZ::Name("metallic.factor"));
  156. m_multiScatteringEnabledIndex = materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(AZ::Name("specularF0.enableMultiScatterCompensation"));
  157. m_materialInstances.resize(MaxVariants);
  158. for (AZ::Data::Instance<AZ::RPI::Material>& material : m_materialInstances)
  159. {
  160. material = AZ::RPI::Material::Create(materialAsset);
  161. }
  162. }
  163. void AreaLightExampleComponent::UpdateModels(AZ::Data::Asset<AZ::RPI::ModelAsset> modelAsset)
  164. {
  165. for (uint32_t i = 0; i < MaxVariants; ++i)
  166. {
  167. MeshHandle& meshHandle = m_meshHandles.at(i);
  168. if (i < m_config.m_count)
  169. {
  170. if (!meshHandle.IsValid())
  171. {
  172. meshHandle = m_meshFeatureProcessor->AcquireMesh(MeshHandleDescriptor{ modelAsset }, m_materialInstances.at(i));
  173. }
  174. else if (m_modelAsset.GetId() != modelAsset.GetId())
  175. {
  176. // Valid mesh handle, but wrong asset. Release and reacquire.
  177. m_meshFeatureProcessor->ReleaseMesh(meshHandle);
  178. meshHandle = m_meshFeatureProcessor->AcquireMesh(MeshHandleDescriptor{ modelAsset }, m_materialInstances.at(i));
  179. }
  180. AZ::Transform transform = AZ::Transform::CreateIdentity();
  181. transform.SetTranslation(GetModelPosition(i));
  182. m_meshFeatureProcessor->SetTransform(meshHandle, transform);
  183. }
  184. else if(meshHandle.IsValid())
  185. {
  186. m_meshFeatureProcessor->ReleaseMesh(meshHandle);
  187. }
  188. }
  189. m_modelAsset = modelAsset;
  190. }
  191. void AreaLightExampleComponent::UpdateMaterials()
  192. {
  193. bool allMaterialsCompiled = true;
  194. for (uint32_t i = 0; i < m_config.m_count; ++i)
  195. {
  196. MaterialInstance& materialInstance = m_materialInstances.at(i);
  197. if (m_roughnessPropertyIndex.IsValid())
  198. {
  199. float roughness = GetLerpValue(m_config.m_roughness, i, m_config.GetVaryRoughness());
  200. materialInstance->SetPropertyValue(m_roughnessPropertyIndex, roughness);
  201. }
  202. if (m_metallicPropertyIndex.IsValid())
  203. {
  204. float metallic = GetLerpValue(m_config.m_metallic, i, m_config.GetVaryMetallic());
  205. materialInstance->SetPropertyValue(m_metallicPropertyIndex, metallic);
  206. }
  207. if (m_multiScatteringEnabledIndex.IsValid())
  208. {
  209. materialInstance->SetPropertyValue(m_multiScatteringEnabledIndex, m_config.m_multiScattering);
  210. }
  211. allMaterialsCompiled = allMaterialsCompiled && materialInstance->Compile();
  212. }
  213. if (allMaterialsCompiled)
  214. {
  215. m_materialsNeedUpdate = false;
  216. }
  217. }
  218. template <typename FeatureProcessorType, typename HandleType>
  219. void AreaLightExampleComponent::UpdateLightForType(FeatureProcessorType featureProcessor, HandleType& handle, uint32_t index)
  220. {
  221. if (index < m_config.m_count)
  222. {
  223. if (!handle.IsValid())
  224. {
  225. handle = featureProcessor->AcquireLight();
  226. featureProcessor->SetAttenuationRadius(handle, 100.0f);
  227. }
  228. }
  229. else
  230. {
  231. featureProcessor->ReleaseLight(handle);
  232. }
  233. }
  234. void AreaLightExampleComponent::UpdatePointLight(PointLightHandle& handle, uint32_t index, AZ::Vector3 position)
  235. {
  236. UpdateLightForType(m_pointLightFeatureProcessor, handle, index);
  237. if (index < m_config.m_count)
  238. {
  239. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::OmnidirectionalSteradians);
  240. m_pointLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Candela>());
  241. float radius = GetLerpValue(m_config.m_radius, index, m_config.GetVaryRadius());
  242. m_pointLightFeatureProcessor->SetPosition(handle, position);
  243. m_pointLightFeatureProcessor->SetBulbRadius(handle, radius);
  244. }
  245. }
  246. void AreaLightExampleComponent::UpdateDiskLight(DiskLightHandle& handle, uint32_t index, AZ::Vector3 position)
  247. {
  248. UpdateLightForType(m_diskLightFeatureProcessor, handle, index);
  249. if (index < m_config.m_count)
  250. {
  251. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::DirectionalEffectiveSteradians);
  252. m_diskLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Candela>());
  253. m_diskLightFeatureProcessor->SetPosition(handle, position);
  254. AZ::Matrix3x3 rotationMatrix = m_config.GetRotationMatrix();
  255. m_diskLightFeatureProcessor->SetDirection(handle, rotationMatrix.GetBasisZ());
  256. float radius = GetLerpValue(m_config.m_radius, index, m_config.GetVaryRadius());
  257. m_diskLightFeatureProcessor->SetDiskRadius(handle, radius);
  258. }
  259. }
  260. void AreaLightExampleComponent::UpdateCapsuleLight(CapsuleLightHandle& handle, uint32_t index, AZ::Vector3 position)
  261. {
  262. UpdateLightForType(m_capsuleLightFeatureProcessor, handle, index);
  263. if (index < m_config.m_count)
  264. {
  265. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::OmnidirectionalSteradians);
  266. m_capsuleLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Candela>());
  267. AZ::Matrix3x3 rotationMatrix = m_config.GetRotationMatrix();
  268. AZ::Vector3 startPos = position - rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  269. AZ::Vector3 endPos = position + rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  270. m_capsuleLightFeatureProcessor->SetCapsuleLineSegment(handle, startPos, endPos);
  271. float radius = GetLerpValue(m_config.m_radius, index, m_config.GetVaryRadius());
  272. m_capsuleLightFeatureProcessor->SetCapsuleRadius(handle, radius);
  273. }
  274. }
  275. void AreaLightExampleComponent::UpdateQuadLight(QuadLightHandle& handle, uint32_t index, AZ::Vector3 position)
  276. {
  277. UpdateLightForType(m_quadLightFeatureProcessor, handle, index);
  278. if (index < m_config.m_count)
  279. {
  280. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::DirectionalEffectiveSteradians);
  281. m_photometricValue.SetArea(m_config.m_quadSize[0] * m_config.m_quadSize[1]);
  282. m_quadLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Nit>());
  283. m_quadLightFeatureProcessor->SetPosition(handle, position);
  284. m_quadLightFeatureProcessor->SetOrientation(handle, m_config.GetRotationQuaternion());
  285. m_quadLightFeatureProcessor->SetQuadDimensions(handle, m_config.m_quadSize[0], m_config.m_quadSize[1]);
  286. m_quadLightFeatureProcessor->SetLightEmitsBothDirections(handle, m_config.m_emitsBothDirections);
  287. m_quadLightFeatureProcessor->SetUseFastApproximation(handle, m_config.m_fastApproximation);
  288. }
  289. }
  290. void AreaLightExampleComponent::UpdatePolygonLight(PolygonLightHandle& handle, uint32_t index, AZ::Vector3 position)
  291. {
  292. UpdateLightForType(m_polygonLightFeatureProcessor, handle, index);
  293. if (index < m_config.m_count)
  294. {
  295. AZStd::vector<AZ::Vector3> points = GetPolygonVertices(m_config.m_polyStarCount, m_config.m_polyMinMaxRadius);
  296. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::DirectionalEffectiveSteradians);
  297. m_photometricValue.SetArea(CalculatePolygonArea(points));
  298. m_polygonLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Nit>());
  299. m_polygonLightFeatureProcessor->SetPosition(handle, position);
  300. m_polygonLightFeatureProcessor->SetLightEmitsBothDirections(handle, m_config.m_emitsBothDirections);
  301. TransformVertices(points, m_config.GetRotationQuaternion(), position);
  302. AZ::Vector3 direction = m_config.GetRotationQuaternion().TransformVector(AZ::Vector3::CreateAxisZ());
  303. m_polygonLightFeatureProcessor->SetPolygonPoints(handle, points.data(), static_cast<uint32_t>(points.size()), direction);
  304. }
  305. }
  306. void AreaLightExampleComponent::UpdateLights()
  307. {
  308. m_photometricValue.SetIntensity(m_config.m_intensity);
  309. m_photometricValue.SetChroma(AZ::Color::CreateFromVector3(AZ::Vector3::CreateFromFloat3(m_config.m_color)));
  310. for (uint32_t i = 0; i < MaxVariants; ++i)
  311. {
  312. LightHandle& lightHandle = m_lightHandles.at(i);
  313. AZ::Vector3 lightPos = GetLightPosition(i);
  314. switch (m_config.m_lightType)
  315. {
  316. case Point:
  317. UpdatePointLight(lightHandle.m_point, i, lightPos);
  318. break;
  319. case Disk:
  320. UpdateDiskLight(lightHandle.m_disk, i, lightPos);
  321. break;
  322. case Capsule:
  323. UpdateCapsuleLight(lightHandle.m_capsule, i, lightPos);
  324. break;
  325. case Quad:
  326. UpdateQuadLight(lightHandle.m_quad, i, lightPos);
  327. break;
  328. case Polygon:
  329. UpdatePolygonLight(lightHandle.m_polygon, i, lightPos);
  330. break;
  331. }
  332. }
  333. }
  334. void AreaLightExampleComponent::TransformVertices(AZStd::vector<AZ::Vector3>& vertices, const AZ::Quaternion& orientation, const AZ::Vector3& translation)
  335. {
  336. for (AZ::Vector3& vertex : vertices)
  337. {
  338. vertex = orientation.TransformVector(vertex);
  339. vertex += translation;
  340. }
  341. }
  342. AZ::Vector3 AreaLightExampleComponent::GetCirclePoint(float n, float count)
  343. {
  344. // Calculate angle for this point in the star
  345. float ratio = 1.0f - (n / count);
  346. float angle = ratio * AZ::Constants::TwoPi;
  347. // Get normalized x, y coordinates for point
  348. float sin = 0.0f;
  349. float cos = 0.0f;
  350. AZ::SinCos(angle, sin, cos);
  351. return AZ::Vector3(sin, cos, 0.0f);
  352. }
  353. AZStd::vector<AZ::Vector3> AreaLightExampleComponent::GetPolygonVertices(uint32_t pointCount, float minMaxRadius[2])
  354. {
  355. uint32_t vertexCount = pointCount * 2; // For each of the stars points, there's a vertex bewteen the points.
  356. AZStd::vector<AZ::Vector3> points;
  357. points.reserve(vertexCount);
  358. for (uint32_t i = 0; i < vertexCount; ++i)
  359. {
  360. // Get a point on the circle and scale it by the min or max radius for every other point.
  361. AZ::Vector3 point = GetCirclePoint(static_cast<float>(i), static_cast<float>(vertexCount)) * minMaxRadius[i % 2];
  362. points.push_back(point);
  363. }
  364. return points;
  365. }
  366. AZStd::vector<AZ::Vector3> AreaLightExampleComponent::GetPolygonTriangles(uint32_t pointCount, float minMaxRadius[2])
  367. {
  368. AZStd::vector<AZ::Vector3> tris;
  369. tris.reserve(pointCount * 6); // 2 triangles with 3 vertices for each star point.
  370. uint32_t vertexCount = pointCount * 2; // For each of the stars points, there's a vertex bewteen the points.
  371. for (uint32_t i = 0; i < vertexCount; ++i)
  372. {
  373. uint32_t nextI = (i + 1) % vertexCount;
  374. AZ::Vector3 p0 = GetCirclePoint(static_cast<float>(i), static_cast<float>(vertexCount)) * minMaxRadius[i % 2];
  375. AZ::Vector3 p1 = GetCirclePoint(static_cast<float>(nextI), static_cast<float>(vertexCount)) * minMaxRadius[nextI % 2];
  376. tris.push_back(p0);
  377. tris.push_back(p1);
  378. tris.push_back(AZ::Vector3::CreateZero());
  379. }
  380. return tris;
  381. }
  382. void AreaLightExampleComponent::ReleaseModels()
  383. {
  384. for (MeshHandle& meshHandle : m_meshHandles)
  385. {
  386. m_meshFeatureProcessor->ReleaseMesh(meshHandle);
  387. }
  388. }
  389. void AreaLightExampleComponent::ReleaseLights()
  390. {
  391. for (LightHandle& lightHandle : m_lightHandles)
  392. {
  393. switch (m_config.m_lightType)
  394. {
  395. case Point:
  396. m_pointLightFeatureProcessor->ReleaseLight(lightHandle.m_point);
  397. break;
  398. case Disk:
  399. m_diskLightFeatureProcessor->ReleaseLight(lightHandle.m_disk);
  400. break;
  401. case Capsule:
  402. m_capsuleLightFeatureProcessor->ReleaseLight(lightHandle.m_capsule);
  403. break;
  404. case Quad:
  405. m_quadLightFeatureProcessor->ReleaseLight(lightHandle.m_quad);
  406. break;
  407. case Polygon:
  408. m_polygonLightFeatureProcessor->ReleaseLight(lightHandle.m_polygon);
  409. break;
  410. }
  411. }
  412. }
  413. void AreaLightExampleComponent::DrawUI()
  414. {
  415. ScriptableImGui::Begin("AreaLightSample", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar);
  416. bool modelsNeedUpdate = false;
  417. bool lightsNeedUpdate = false;
  418. ImGui::Text("Area Light Example");
  419. ImGui::Separator();
  420. ImGui::Text("Mesh Settings");
  421. int count = m_config.m_count;
  422. if (ScriptableImGui::SliderInt("Count", &count, 1, MaxVariants))
  423. {
  424. m_config.m_count = aznumeric_cast<uint32_t>(count);
  425. modelsNeedUpdate = true;
  426. lightsNeedUpdate = true;
  427. }
  428. if (m_roughnessPropertyIndex.IsValid())
  429. {
  430. if (m_config.m_count > 1)
  431. {
  432. if (ScriptableImGui::Checkbox("Vary Roughness Across Models", &m_config.m_varyRoughness))
  433. {
  434. m_materialsNeedUpdate = true;
  435. }
  436. }
  437. if (m_config.GetVaryRoughness())
  438. {
  439. if (ScriptableImGui::SliderFloat2("Min Max Roughness", m_config.m_roughness, 0.0f, 1.0f))
  440. {
  441. m_materialsNeedUpdate = true;
  442. }
  443. }
  444. else if (ScriptableImGui::SliderFloat("Roughness", &m_config.m_roughness[0], 0.0f, 1.0f))
  445. {
  446. m_materialsNeedUpdate = true;
  447. }
  448. }
  449. if (m_metallicPropertyIndex.IsValid())
  450. {
  451. if (m_config.m_count > 1)
  452. {
  453. if (ScriptableImGui::Checkbox("Vary Metallic Across Models", &m_config.m_varyMetallic))
  454. {
  455. m_materialsNeedUpdate = true;
  456. }
  457. }
  458. if (m_config.GetVaryMetallic())
  459. {
  460. if (ScriptableImGui::SliderFloat2("Min Max Metallic", m_config.m_metallic, 0.0f, 1.0f))
  461. {
  462. m_materialsNeedUpdate = true;
  463. }
  464. }
  465. else if (ScriptableImGui::SliderFloat("Metallic", &m_config.m_metallic[0], 0.0f, 1.0f))
  466. {
  467. m_materialsNeedUpdate = true;
  468. }
  469. }
  470. ImGui::Separator();
  471. ImGui::Text("Light Settings");
  472. if (ScriptableImGui::Checkbox("Validate", &m_config.m_validation))
  473. {
  474. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(AZ::Name{ "o_area_light_validation" }, AZ::RPI::ShaderOptionValue{ m_config.m_validation });
  475. }
  476. AZStd::vector<AZStd::string> lightTypeNames
  477. {
  478. "Point",
  479. "Disk",
  480. "Capsule",
  481. "Quad",
  482. "Polygon",
  483. };
  484. if (ScriptableImGui::BeginCombo("LightType", lightTypeNames.at(m_config.m_lightType).c_str()))
  485. {
  486. for (uint32_t i = 0; i < lightTypeNames.size(); ++i)
  487. {
  488. AZStd::string& name = lightTypeNames.at(i);
  489. if (ScriptableImGui::Selectable(name.c_str(), m_config.m_lightType == LightType(i)))
  490. {
  491. ReleaseLights();
  492. m_config.m_lightType = LightType(i);
  493. lightsNeedUpdate = true;
  494. }
  495. }
  496. ScriptableImGui::EndCombo();
  497. }
  498. if (ScriptableImGui::SliderFloat("Lumens", &m_config.m_intensity, 0.0f, 1000.0f, "%.3f", ImGuiSliderFlags_Logarithmic))
  499. {
  500. lightsNeedUpdate = true;
  501. }
  502. if (ScriptableImGui::ColorEdit3("Color", m_config.m_color, ImGuiColorEditFlags_Float))
  503. {
  504. lightsNeedUpdate = true;
  505. }
  506. if (ScriptableImGui::SliderFloat3("Position Offset", m_config.m_positionOffset, -3.0f, 3.0f))
  507. {
  508. lightsNeedUpdate = true;
  509. }
  510. if (m_config.m_lightType == Disk || m_config.m_lightType == Capsule || m_config.m_lightType == Quad || m_config.m_lightType == Polygon)
  511. {
  512. if (ScriptableImGui::SliderAngle("X rotation", &m_config.m_rotations[0]))
  513. {
  514. lightsNeedUpdate = true;
  515. }
  516. if (ScriptableImGui::SliderAngle("Y rotation", &m_config.m_rotations[1]))
  517. {
  518. lightsNeedUpdate = true;
  519. }
  520. if (m_config.m_lightType == Quad || m_config.m_lightType == Polygon) // Disk and Capsule are circular around z axis, so this only affects Quad and Polygon.
  521. {
  522. if (ScriptableImGui::SliderAngle("Z rotation", &m_config.m_rotations[2]))
  523. {
  524. lightsNeedUpdate = true;
  525. }
  526. }
  527. }
  528. // Radius
  529. if (m_config.m_lightType == Point || m_config.m_lightType == Disk || m_config.m_lightType == Capsule)
  530. {
  531. if (m_config.m_count > 1)
  532. {
  533. if (ScriptableImGui::Checkbox("Vary Radius Across Lights", &m_config.m_varyRadius))
  534. {
  535. lightsNeedUpdate = true;
  536. }
  537. }
  538. if (m_config.GetVaryRadius())
  539. {
  540. if (ScriptableImGui::SliderFloat2("Min/Max Radius", m_config.m_radius, 0.0f, 1.0f))
  541. {
  542. lightsNeedUpdate = true;
  543. }
  544. }
  545. else if (ScriptableImGui::SliderFloat("Radius", &m_config.m_radius[0], 0.0f, 2.0f))
  546. {
  547. lightsNeedUpdate = true;
  548. }
  549. }
  550. // Capsule Height
  551. if (m_config.m_lightType == Capsule)
  552. {
  553. if (ScriptableImGui::SliderFloat("Capsule Height", &m_config.m_capsuleHeight, 0.0f, 10.0f))
  554. {
  555. lightsNeedUpdate = true;
  556. }
  557. }
  558. if (m_config.m_lightType == Quad)
  559. {
  560. if (ScriptableImGui::SliderFloat2("Quad Dimensions", m_config.m_quadSize, 0.0f, 10.0f))
  561. {
  562. lightsNeedUpdate = true;
  563. }
  564. if (ScriptableImGui::Checkbox("Use Fast Approximation", &m_config.m_fastApproximation))
  565. {
  566. lightsNeedUpdate = true;
  567. }
  568. }
  569. if (m_config.m_lightType == Polygon)
  570. {
  571. if (ScriptableImGui::SliderInt("Star Points", &m_config.m_polyStarCount, 2, 32))
  572. {
  573. lightsNeedUpdate = true;
  574. }
  575. if (ScriptableImGui::SliderFloat2("Star Min-Max Radius", m_config.m_polyMinMaxRadius, 0.0f, 4.0))
  576. {
  577. lightsNeedUpdate = true;
  578. }
  579. }
  580. if (m_config.m_lightType == Quad || m_config.m_lightType == Polygon)
  581. {
  582. if (ScriptableImGui::Checkbox("Emit Both Directions", &m_config.m_emitsBothDirections))
  583. {
  584. lightsNeedUpdate = true;
  585. }
  586. }
  587. if (ScriptableImGui::Checkbox("Multiscattering", &m_config.m_multiScattering))
  588. {
  589. m_materialsNeedUpdate = true;
  590. }
  591. ScriptableImGui::End();
  592. if (m_imguiSidebar.Begin())
  593. {
  594. if (m_modelBrowser.Tick(m_modelBrowserSettings))
  595. {
  596. AZ::Data::AssetId selectedModelAssetId = m_modelBrowser.GetSelectedAssetId();
  597. if (selectedModelAssetId.IsValid())
  598. {
  599. AZ::Data::Asset<AZ::RPI::ModelAsset> modelAsset;
  600. modelAsset.Create(selectedModelAssetId);
  601. UpdateModels(modelAsset);
  602. modelsNeedUpdate = false;
  603. }
  604. }
  605. ImGui::Spacing();
  606. if (m_materialBrowser.Tick(m_materialBrowserSettings))
  607. {
  608. AZ::Data::AssetId selectedMaterialAssetId = m_materialBrowser.GetSelectedAssetId();
  609. if (selectedMaterialAssetId.IsValid())
  610. {
  611. AZ::Data::Asset<AZ::RPI::MaterialAsset> materialAsset = AZ::Data::AssetManager::Instance().GetAsset<AZ::RPI::MaterialAsset>(
  612. selectedMaterialAssetId, AZ::Data::AssetLoadBehavior::PreLoad);
  613. materialAsset.BlockUntilLoadComplete();
  614. if (materialAsset.IsReady())
  615. {
  616. InitializeMaterials(materialAsset);
  617. ReleaseModels();
  618. modelsNeedUpdate = true;
  619. }
  620. }
  621. }
  622. m_imguiSidebar.End();
  623. }
  624. if (modelsNeedUpdate)
  625. {
  626. UpdateModels(m_modelAsset);
  627. }
  628. if (m_materialsNeedUpdate || modelsNeedUpdate)
  629. {
  630. UpdateMaterials();
  631. }
  632. if (lightsNeedUpdate)
  633. {
  634. UpdateLights();
  635. }
  636. }
  637. void AreaLightExampleComponent::DrawAuxGeom()
  638. {
  639. // Lights need to add support for rendering their emissive surfaces to the regular forward pass which will replace the below.
  640. // Draw AuxGeom for the lights themselves
  641. AZ::Matrix3x3 rotationMatrix = m_config.GetRotationMatrix();
  642. for (uint32_t i = 0; i < m_config.m_count; ++i)
  643. {
  644. float radius = GetLerpValue(m_config.m_radius, i, m_config.GetVaryRadius());
  645. AZ::Vector3 lightPos = GetLightPosition(i);
  646. float area = 0.0f;
  647. switch (m_config.m_lightType)
  648. {
  649. case Point:
  650. area = 4.0f * AZ::Constants::Pi * radius * radius;
  651. break;
  652. case Disk:
  653. area = AZ::Constants::Pi * radius * radius;
  654. break;
  655. case Capsule:
  656. {
  657. float cylinderArea = 2.0f * AZ::Constants::Pi * m_config.m_capsuleHeight * radius;
  658. float capArea = 4.0f * AZ::Constants::Pi * radius * radius;
  659. area = cylinderArea + capArea;
  660. break;
  661. }
  662. case Quad:
  663. area = m_config.m_quadSize[0] * m_config.m_quadSize[1];
  664. break;
  665. case Polygon:
  666. area = CalculatePolygonArea(GetPolygonVertices(m_config.m_polyStarCount, m_config.m_polyMinMaxRadius));
  667. break;
  668. }
  669. float luxIntensity = m_config.m_intensity / area;
  670. float nitsIntensity = luxIntensity / AZ::Constants::Pi;
  671. // The aux geom pass happens after display mapper pass, so do basic gamma correction so the surface of the light's brightness is closer to everything else.
  672. nitsIntensity = pow(nitsIntensity, 1.0f / 2.2f);
  673. AZ::Color nitsColor = AZ::Color(nitsIntensity * m_config.m_color[0], nitsIntensity * m_config.m_color[1], nitsIntensity * m_config.m_color[2], 1.0f);
  674. AZ::RPI::AuxGeomDraw::DrawStyle drawStyle = AZ::RPI::AuxGeomDraw::DrawStyle::Solid;
  675. switch (m_config.m_lightType)
  676. {
  677. case Point:
  678. m_auxGeom->DrawSphere(lightPos, radius, nitsColor, drawStyle);
  679. break;
  680. case Disk:
  681. m_auxGeom->DrawDisk(lightPos, rotationMatrix.GetBasisZ(), radius, nitsColor, drawStyle);
  682. break;
  683. case Capsule:
  684. {
  685. m_auxGeom->DrawCylinder(lightPos, rotationMatrix.GetBasisZ(), radius, m_config.m_capsuleHeight, nitsColor, drawStyle);
  686. // Draw cylinder caps as spheres
  687. AZ::Vector3 startPos = lightPos - rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  688. AZ::Vector3 endPos = lightPos + rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  689. m_auxGeom->DrawSphere(startPos, radius, nitsColor, drawStyle);
  690. m_auxGeom->DrawSphere(endPos, radius, nitsColor, drawStyle);
  691. break;
  692. }
  693. case Quad:
  694. {
  695. AZ::Transform transform = AZ::Transform::CreateIdentity();
  696. transform.SetRotation(AZ::ConvertEulerRadiansToQuaternion(AZ::Vector3(m_config.m_rotations[0], -m_config.m_rotations[1], -m_config.m_rotations[2])));
  697. transform.SetTranslation(lightPos);
  698. transform *= AZ::Transform::CreateFromQuaternion(AZ::ConvertEulerRadiansToQuaternion(AZ::Vector3(AZ::Constants::Pi * 0.5f, 0.0f, 0.0f)));
  699. m_auxGeom->DrawQuad(m_config.m_quadSize[0], m_config.m_quadSize[1], AZ::Matrix3x4::CreateFromTransform(transform), nitsColor, drawStyle);
  700. break;
  701. }
  702. case Polygon:
  703. {
  704. // Sadly DrawTriangles() only supports 8 bit color, so nitsColor must be capped at 1.0f.
  705. nitsIntensity = AZ::GetMin(1.0f, nitsIntensity);
  706. nitsColor = AZ::Color(nitsIntensity * m_config.m_color[0], nitsIntensity * m_config.m_color[1], nitsIntensity * m_config.m_color[2], 1.0f);
  707. AZStd::vector<AZ::Vector3> tris = GetPolygonTriangles(m_config.m_polyStarCount, m_config.m_polyMinMaxRadius);
  708. TransformVertices(tris, m_config.GetRotationQuaternion(), lightPos);
  709. AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments args;
  710. args.m_colorCount = 1;
  711. args.m_colors = &nitsColor;
  712. args.m_vertCount = static_cast<uint32_t>(tris.size());
  713. args.m_verts = tris.data();
  714. m_auxGeom->DrawTriangles(args);
  715. break;
  716. }
  717. }
  718. }
  719. }
  720. float AreaLightExampleComponent::CalculatePolygonArea(const AZStd::vector<AZ::Vector3>& vertices)
  721. {
  722. // See https://en.wikipedia.org/wiki/Shoelace_formula
  723. float twiceArea = 0.0f;
  724. for (size_t i = 0; i < vertices.size(); ++i)
  725. {
  726. size_t j = (i + 1) % vertices.size();
  727. twiceArea += vertices.at(i).GetX() * vertices.at(j).GetY();
  728. twiceArea -= vertices.at(i).GetY() * vertices.at(j).GetX();
  729. }
  730. return AZ::GetAbs(twiceArea * 0.5f);
  731. }
  732. }