LightComponent.cpp 14 KB

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