LightComponent.cpp 13 KB

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