LightComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Scene/Components/LightComponent.h>
  6. #include <AnKi/Scene/SceneNode.h>
  7. #include <AnKi/Scene/Frustum.h>
  8. #include <AnKi/Scene/SceneNode.h>
  9. #include <AnKi/Scene/SceneGraph.h>
  10. #include <AnKi/Scene/Octree.h>
  11. #include <AnKi/Collision.h>
  12. #include <AnKi/Resource/ResourceManager.h>
  13. #include <AnKi/Resource/ImageResource.h>
  14. #include <AnKi/Shaders/Include/ClusteredShadingTypes.h>
  15. namespace anki {
  16. LightComponent::LightComponent(SceneNode* node)
  17. : SceneComponent(node, kClassType)
  18. , m_spatial(this)
  19. , m_type(LightComponentType::kPoint)
  20. {
  21. m_point.m_radius = 1.0f;
  22. setLightComponentType(LightComponentType::kPoint);
  23. m_worldTransform = node->getWorldTransform();
  24. }
  25. LightComponent::~LightComponent()
  26. {
  27. deleteArray(SceneMemoryPool::getSingleton(), m_frustums, m_frustumCount);
  28. m_spatial.removeFromOctree(SceneGraph::getSingleton().getOctree());
  29. if(m_type == LightComponentType::kDirectional)
  30. {
  31. SceneGraph::getSingleton().removeDirectionalLight(this);
  32. }
  33. }
  34. void LightComponent::setLightComponentType(LightComponentType type)
  35. {
  36. ANKI_ASSERT(type >= LightComponentType::kFirst && type < LightComponentType::kCount);
  37. m_shapeUpdated = true;
  38. m_typeChanged = type != m_type;
  39. if(type == LightComponentType::kDirectional)
  40. {
  41. m_spatial.setAlwaysVisible(true);
  42. m_spatial.setUpdatesOctreeBounds(false);
  43. }
  44. else
  45. {
  46. m_spatial.setAlwaysVisible(false);
  47. m_spatial.setUpdatesOctreeBounds(true);
  48. }
  49. if(m_typeChanged)
  50. {
  51. if(type == LightComponentType::kDirectional)
  52. {
  53. // Now it's directional, inform the scene
  54. SceneGraph::getSingleton().addDirectionalLight(this);
  55. }
  56. else if(m_type == LightComponentType::kDirectional)
  57. {
  58. // It was directional, inform the scene
  59. SceneGraph::getSingleton().removeDirectionalLight(this);
  60. }
  61. }
  62. m_type = type;
  63. }
  64. Error LightComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  65. {
  66. const Bool typeChanged = m_typeChanged;
  67. const Bool moveUpdated = info.m_node->movedThisFrame() || typeChanged;
  68. const Bool shapeUpdated = m_shapeUpdated || typeChanged;
  69. updated = moveUpdated || shapeUpdated || typeChanged;
  70. m_shapeUpdated = false;
  71. m_typeChanged = false;
  72. if(moveUpdated)
  73. {
  74. m_worldTransform = info.m_node->getWorldTransform();
  75. }
  76. if(updated && m_type == LightComponentType::kPoint)
  77. {
  78. const Sphere sphere(m_worldTransform.getOrigin(), m_point.m_radius);
  79. m_spatial.setBoundingShape(sphere);
  80. if(m_shadow)
  81. {
  82. if(m_frustums == nullptr || m_frustumCount != 6) [[unlikely]]
  83. {
  84. // Allocate, initialize and update the frustums, just do everything to avoid bugs
  85. deleteArray(SceneMemoryPool::getSingleton(), m_frustums, m_frustumCount);
  86. m_frustums = newArray<Frustum>(SceneMemoryPool::getSingleton(), 6);
  87. m_frustumCount = 6;
  88. for(U32 i = 0; i < 6; i++)
  89. {
  90. m_frustums[i].init(FrustumType::kPerspective);
  91. m_frustums[i].setPerspective(kClusterObjectFrustumNearPlane, m_point.m_radius, kPi / 2.0f, kPi / 2.0f);
  92. m_frustums[i].setWorldTransform(Transform(m_worldTransform.getOrigin(), Frustum::getOmnidirectionalFrustumRotations()[i], 1.0f));
  93. }
  94. }
  95. // Update the frustums
  96. for(U32 i = 0; i < 6; i++)
  97. {
  98. if(shapeUpdated)
  99. {
  100. m_frustums[i].setFar(m_point.m_radius);
  101. }
  102. if(moveUpdated || shapeUpdated)
  103. {
  104. m_frustums[i].setWorldTransform(Transform(m_worldTransform.getOrigin(), Frustum::getOmnidirectionalFrustumRotations()[i], 1.0f));
  105. }
  106. }
  107. }
  108. if(m_shadow && shapeUpdated)
  109. {
  110. m_uuid = SceneGraph::getSingleton().getNewUuid();
  111. }
  112. else if(!m_shadow)
  113. {
  114. m_uuid = 0;
  115. }
  116. // Upload to the GPU scene
  117. GpuSceneLight gpuLight = {};
  118. gpuLight.m_position = m_worldTransform.getOrigin().xyz();
  119. gpuLight.m_radius = m_point.m_radius;
  120. gpuLight.m_diffuseColor = m_diffColor.xyz();
  121. gpuLight.m_squareRadiusOverOne = 1.0f / (m_point.m_radius * m_point.m_radius);
  122. gpuLight.m_shadow = m_shadow;
  123. gpuLight.m_uuid = (m_shadow) ? m_uuid : 0;
  124. if(!m_gpuSceneLight.isValid())
  125. {
  126. m_gpuSceneLight.allocate();
  127. }
  128. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  129. }
  130. else if(updated && m_type == LightComponentType::kSpot)
  131. {
  132. // Update texture matrix
  133. const Mat4 biasMat4(0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
  134. const Mat4 proj =
  135. Mat4::calculatePerspectiveProjectionMatrix(m_spot.m_outerAngle, m_spot.m_outerAngle, kClusterObjectFrustumNearPlane, m_spot.m_distance);
  136. m_spot.m_textureMat = biasMat4 * proj * Mat4(m_worldTransform.getInverse());
  137. // Update the spatial
  138. Array<Vec4, 4> points;
  139. computeEdgesOfFrustum(m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle, &points[0]);
  140. Array<Vec3, 5> worldPoints;
  141. for(U32 i = 0; i < 4; ++i)
  142. {
  143. m_spot.m_edgePointsWspace[i] = m_worldTransform.transform(points[i].xyz());
  144. worldPoints[i] = m_spot.m_edgePointsWspace[i].xyz();
  145. }
  146. worldPoints[4] = m_worldTransform.getOrigin().xyz();
  147. m_spatial.setBoundingShape(ConstWeakArray<Vec3>(worldPoints));
  148. if(m_shadow)
  149. {
  150. if(m_frustums == nullptr || m_frustumCount != 1) [[unlikely]]
  151. {
  152. // Allocate, initialize and update the frustums, just do everything to avoid bugs
  153. deleteArray(SceneMemoryPool::getSingleton(), m_frustums, m_frustumCount);
  154. m_frustums = newArray<Frustum>(SceneMemoryPool::getSingleton(), 1);
  155. m_frustumCount = 1;
  156. m_frustums[0].init(FrustumType::kPerspective);
  157. m_frustums[0].setPerspective(kClusterObjectFrustumNearPlane, m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle);
  158. m_frustums[0].setWorldTransform(m_worldTransform);
  159. }
  160. // Update the frustum
  161. if(shapeUpdated)
  162. {
  163. m_frustums[0].setFar(m_spot.m_distance);
  164. m_frustums[0].setFovX(m_spot.m_outerAngle);
  165. m_frustums[0].setFovY(m_spot.m_outerAngle);
  166. }
  167. if(moveUpdated)
  168. {
  169. m_frustums[0].setWorldTransform(m_worldTransform);
  170. }
  171. }
  172. if(m_shadow && shapeUpdated)
  173. {
  174. m_uuid = SceneGraph::getSingleton().getNewUuid();
  175. }
  176. else if(!m_shadow)
  177. {
  178. m_uuid = 0;
  179. }
  180. // Upload to the GPU scene
  181. GpuSceneLight gpuLight = {};
  182. gpuLight.m_position = m_worldTransform.getOrigin().xyz();
  183. for(U32 i = 0; i < 4; ++i)
  184. {
  185. gpuLight.m_edgePoints[i] = m_spot.m_edgePointsWspace[i].xyz0();
  186. }
  187. gpuLight.m_diffuseColor = m_diffColor.xyz();
  188. gpuLight.m_radius = m_spot.m_distance;
  189. gpuLight.m_direction = -m_worldTransform.getRotation().getZAxis();
  190. gpuLight.m_squareRadiusOverOne = 1.0f / (m_spot.m_distance * m_spot.m_distance);
  191. gpuLight.m_shadow = m_shadow;
  192. gpuLight.m_outerCos = cos(m_spot.m_outerAngle / 2.0f);
  193. gpuLight.m_innerCos = cos(m_spot.m_innerAngle / 2.0f);
  194. gpuLight.m_uuid = (m_shadow) ? m_uuid : 0;
  195. if(!m_gpuSceneLight.isValid())
  196. {
  197. m_gpuSceneLight.allocate();
  198. }
  199. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  200. }
  201. else if(m_type == LightComponentType::kDirectional)
  202. {
  203. // Update the scene bounds always
  204. SceneGraph::getSingleton().getOctree().getActualSceneBounds(m_dir.m_sceneMin, m_dir.m_sceneMax);
  205. m_gpuSceneLight.free();
  206. }
  207. const Bool spatialUpdated = m_spatial.update(SceneGraph::getSingleton().getOctree());
  208. updated = updated || spatialUpdated;
  209. if(m_shadow)
  210. {
  211. for(U32 i = 0; i < m_frustumCount; ++i)
  212. {
  213. const Bool frustumUpdated = m_frustums[i].update();
  214. updated = updated || frustumUpdated;
  215. }
  216. }
  217. return Error::kNone;
  218. }
  219. void LightComponent::setupDirectionalLightQueueElement(const Frustum& primaryFrustum, DirectionalLightQueueElement& el,
  220. WeakArray<Frustum> cascadeFrustums) const
  221. {
  222. ANKI_ASSERT(m_type == LightComponentType::kDirectional);
  223. ANKI_ASSERT(cascadeFrustums.getSize() <= kMaxShadowCascades);
  224. const U32 shadowCascadeCount = cascadeFrustums.getSize();
  225. el.m_uuid = m_uuid;
  226. el.m_diffuseColor = m_diffColor.xyz();
  227. el.m_direction = -m_worldTransform.getRotation().getZAxis().xyz();
  228. for(U32 i = 0; i < shadowCascadeCount; ++i)
  229. {
  230. el.m_shadowCascadesDistances[i] = primaryFrustum.getShadowCascadeDistance(i);
  231. }
  232. el.m_shadowCascadeCount = U8(shadowCascadeCount);
  233. el.m_shadowLayer = kMaxU8;
  234. if(shadowCascadeCount == 0)
  235. {
  236. return;
  237. }
  238. // Compute the texture matrices
  239. const Mat4 lightTrf(m_worldTransform);
  240. if(primaryFrustum.getFrustumType() == FrustumType::kPerspective)
  241. {
  242. // Get some stuff
  243. const F32 fovX = primaryFrustum.getFovX();
  244. const F32 fovY = primaryFrustum.getFovY();
  245. // Compute a sphere per cascade
  246. Array<Sphere, kMaxShadowCascades> boundingSpheres;
  247. for(U32 i = 0; i < shadowCascadeCount; ++i)
  248. {
  249. // Compute the center of the sphere
  250. // ^ z
  251. // |
  252. // ----------|---------- A(a, -f)
  253. // \ | /
  254. // \ | /
  255. // \ C(0,z) /
  256. // \ | /
  257. // \ | /
  258. // \---|---/ B(b, -n)
  259. // \ | /
  260. // \ | /
  261. // v
  262. // --------------------------> x
  263. // |
  264. // The square distance of A-C is equal to B-C. Solve the equation to find the z.
  265. const F32 f = primaryFrustum.getShadowCascadeDistance(i); // Cascade far
  266. const F32 n = (i == 0) ? primaryFrustum.getNear() : primaryFrustum.getShadowCascadeDistance(i - 1); // Cascade near
  267. const F32 a = f * tan(fovY / 2.0f) * fovX / fovY;
  268. const F32 b = n * tan(fovY / 2.0f) * fovX / fovY;
  269. const F32 z = (b * b + n * n - a * a - f * f) / (2.0f * (f - n));
  270. ANKI_ASSERT(absolute((Vec2(a, -f) - Vec2(0, z)).getLength() - (Vec2(b, -n) - Vec2(0, z)).getLength()) <= kEpsilonf * 100.0f);
  271. Vec3 C(0.0f, 0.0f, z); // Sphere center
  272. // Compute the radius of the sphere
  273. const Vec3 A(a, tan(fovY / 2.0f) * f, -f);
  274. const F32 r = (A - C).getLength();
  275. // Set the sphere
  276. boundingSpheres[i].setRadius(r);
  277. boundingSpheres[i].setCenter(primaryFrustum.getWorldTransform().transform(C));
  278. }
  279. // Compute the matrices
  280. for(U32 i = 0; i < shadowCascadeCount; ++i)
  281. {
  282. const Sphere& sphere = boundingSpheres[i];
  283. const Vec3 sphereCenter = sphere.getCenter().xyz();
  284. const F32 sphereRadius = sphere.getRadius();
  285. const Vec3& lightDir = el.m_direction;
  286. const Vec3 sceneMin = m_dir.m_sceneMin - Vec3(sphereRadius); // Push the bounds a bit
  287. const Vec3 sceneMax = m_dir.m_sceneMax + Vec3(sphereRadius);
  288. // Compute the intersections with the scene bounds
  289. Vec3 eye;
  290. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  291. {
  292. // Inside the scene bounds
  293. const Aabb sceneBox(sceneMin, sceneMax);
  294. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  295. eye = sphereCenter + t * (-lightDir);
  296. }
  297. else
  298. {
  299. eye = sphereCenter + sphereRadius * (-lightDir);
  300. }
  301. // Projection
  302. const F32 far = (eye - sphereCenter).getLength() + sphereRadius;
  303. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(sphereRadius, -sphereRadius, sphereRadius, -sphereRadius,
  304. kClusterObjectFrustumNearPlane, far);
  305. // View
  306. Transform cascadeTransform = m_worldTransform;
  307. cascadeTransform.setOrigin(eye.xyz0());
  308. const Mat4 cascadeViewMat = Mat4(cascadeTransform.getInverse());
  309. // Now it's time to stabilize the shadows by aligning the projection matrix
  310. {
  311. // Project a random fixed point to the light matrix
  312. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1();
  313. // Chose a random low shadowmap size and align the random point
  314. const F32 shadowmapSize = 128.0f;
  315. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  316. const F32 alignedX = std::round(randomPointAlmostLightSpace.x() * shadowmapSize2) / shadowmapSize2;
  317. const F32 alignedY = std::round(randomPointAlmostLightSpace.y() * shadowmapSize2) / shadowmapSize2;
  318. const F32 dx = alignedX - randomPointAlmostLightSpace.x();
  319. const F32 dy = alignedY - randomPointAlmostLightSpace.y();
  320. // Fix the projection matrix by applying an offset
  321. Mat4 correctionTranslationMat = Mat4::getIdentity();
  322. correctionTranslationMat.setTranslationPart(Vec4(dx, dy, 0, 1.0f));
  323. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  324. }
  325. // Light matrix
  326. const Mat4 biasMat4(0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
  327. el.m_viewProjectionMatrices[i] = cascadeProjMat * cascadeViewMat;
  328. el.m_textureMatrices[i] = biasMat4 * el.m_viewProjectionMatrices[i];
  329. // Fill the frustum with the fixed projection parameters from the fixed projection matrix
  330. Plane plane;
  331. extractClipPlane(cascadeProjMat, FrustumPlaneType::kLeft, plane);
  332. const F32 left = plane.getOffset();
  333. extractClipPlane(cascadeProjMat, FrustumPlaneType::kRight, plane);
  334. const F32 right = -plane.getOffset();
  335. extractClipPlane(cascadeProjMat, FrustumPlaneType::kTop, plane);
  336. const F32 top = -plane.getOffset();
  337. extractClipPlane(cascadeProjMat, FrustumPlaneType::kBottom, plane);
  338. const F32 bottom = plane.getOffset();
  339. Frustum& cascadeFrustum = cascadeFrustums[i];
  340. cascadeFrustum.init(FrustumType::kOrthographic);
  341. cascadeFrustum.setOrthographic(kClusterObjectFrustumNearPlane, far, right, left, top, bottom);
  342. cascadeFrustum.setWorldTransform(cascadeTransform);
  343. [[maybe_unused]] const Bool updated = cascadeFrustum.update();
  344. ANKI_ASSERT(updated);
  345. }
  346. }
  347. else
  348. {
  349. ANKI_ASSERT(!"TODO");
  350. }
  351. }
  352. } // end namespace anki