LightComponent.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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/Collision.h>
  11. #include <AnKi/Resource/ResourceManager.h>
  12. #include <AnKi/Resource/ImageResource.h>
  13. #include <AnKi/Shaders/Include/ClusteredShadingTypes.h>
  14. namespace anki {
  15. LightComponent::LightComponent(SceneNode* node)
  16. : SceneComponent(node, kClassType)
  17. , m_type(LightComponentType::kPoint)
  18. {
  19. m_point.m_radius = 1.0f;
  20. setLightComponentType(LightComponentType::kPoint);
  21. m_worldTransform = node->getWorldTransform();
  22. }
  23. LightComponent::~LightComponent()
  24. {
  25. if(m_type == LightComponentType::kDirectional)
  26. {
  27. SceneGraph::getSingleton().removeDirectionalLight(this);
  28. }
  29. }
  30. void LightComponent::setLightComponentType(LightComponentType newType)
  31. {
  32. ANKI_ASSERT(newType >= LightComponentType::kFirst && newType < LightComponentType::kCount);
  33. const LightComponentType oldType = m_type;
  34. const Bool typeChanged = newType != oldType;
  35. if(typeChanged)
  36. {
  37. m_type = newType;
  38. m_shadowAtlasUvViewportCount = 0;
  39. m_shapeDirty = true;
  40. m_otherDirty = true;
  41. m_uuid = 0;
  42. if(newType == LightComponentType::kDirectional)
  43. {
  44. // Now it's directional, inform the scene
  45. SceneGraph::getSingleton().addDirectionalLight(this);
  46. }
  47. else if(oldType == LightComponentType::kDirectional)
  48. {
  49. // It was directional, inform the scene
  50. SceneGraph::getSingleton().removeDirectionalLight(this);
  51. }
  52. }
  53. }
  54. Error LightComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  55. {
  56. const Bool moveUpdated = info.m_node->movedThisFrame();
  57. updated = moveUpdated || m_shapeDirty || m_otherDirty;
  58. if(moveUpdated)
  59. {
  60. m_worldTransform = info.m_node->getWorldTransform();
  61. }
  62. if(updated && m_type == LightComponentType::kPoint)
  63. {
  64. if(!m_shadow)
  65. {
  66. m_uuid = 0;
  67. }
  68. else if(m_uuid == 0)
  69. {
  70. m_uuid = SceneGraph::getSingleton().getNewUuid();
  71. }
  72. const Bool reallyShadow = m_shadow && m_shadowAtlasUvViewportCount == 6;
  73. // Upload the hash
  74. if(reallyShadow)
  75. {
  76. if(!m_hash.isValid())
  77. {
  78. m_hash.allocate();
  79. }
  80. if(m_shapeDirty || moveUpdated)
  81. {
  82. GpuSceneLightVisibleRenderablesHash hash = {};
  83. m_hash.uploadToGpuScene(hash);
  84. }
  85. }
  86. // Upload to the GPU scene
  87. GpuSceneLight gpuLight = {};
  88. gpuLight.m_position = m_worldTransform.getOrigin().xyz();
  89. gpuLight.m_radius = m_point.m_radius;
  90. gpuLight.m_diffuseColor = m_diffColor.xyz();
  91. gpuLight.m_visibleRenderablesHashIndex = (reallyShadow) ? m_hash.getIndex() : 0;
  92. gpuLight.m_flags = GpuSceneLightFlag::kPointLight;
  93. gpuLight.m_flags |= (reallyShadow) ? GpuSceneLightFlag::kShadow : GpuSceneLightFlag::kNone;
  94. gpuLight.m_componentArrayIndex = getArrayIndex();
  95. gpuLight.m_uuid = m_uuid;
  96. for(U32 f = 0; f < m_shadowAtlasUvViewportCount; ++f)
  97. {
  98. gpuLight.m_spotLightMatrixOrPointLightUvViewports[f] = m_shadowAtlasUvViewports[f];
  99. }
  100. if(!m_gpuSceneLight.isValid())
  101. {
  102. m_gpuSceneLight.allocate();
  103. }
  104. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  105. }
  106. else if(updated && m_type == LightComponentType::kSpot)
  107. {
  108. if(!m_shadow)
  109. {
  110. m_uuid = 0;
  111. }
  112. else if(m_uuid == 0)
  113. {
  114. m_uuid = SceneGraph::getSingleton().getNewUuid();
  115. }
  116. const Bool reallyShadow = m_shadow && m_shadowAtlasUvViewportCount == 1;
  117. // Upload the hash
  118. if(reallyShadow)
  119. {
  120. if(!m_hash.isValid())
  121. {
  122. m_hash.allocate();
  123. }
  124. if(m_shapeDirty || moveUpdated)
  125. {
  126. GpuSceneLightVisibleRenderablesHash hash = {};
  127. m_hash.uploadToGpuScene(hash);
  128. }
  129. }
  130. // Upload to the GPU scene
  131. GpuSceneLight gpuLight = {};
  132. gpuLight.m_position = m_worldTransform.getOrigin().xyz();
  133. gpuLight.m_radius = m_spot.m_distance;
  134. gpuLight.m_diffuseColor = m_diffColor.xyz();
  135. gpuLight.m_visibleRenderablesHashIndex = (reallyShadow) ? m_hash.getIndex() : 0;
  136. gpuLight.m_flags = GpuSceneLightFlag::kSpotLight;
  137. gpuLight.m_flags |= (reallyShadow) ? GpuSceneLightFlag::kShadow : GpuSceneLightFlag::kNone;
  138. gpuLight.m_componentArrayIndex = getArrayIndex();
  139. gpuLight.m_uuid = m_uuid;
  140. gpuLight.m_innerCos = cos(m_spot.m_innerAngle / 2.0f);
  141. gpuLight.m_direction = -m_worldTransform.getRotation().getZAxis();
  142. gpuLight.m_outerCos = cos(m_spot.m_outerAngle / 2.0f);
  143. Array<Vec4, 4> points;
  144. computeEdgesOfFrustum(m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle, &points[0]);
  145. for(U32 i = 0; i < 4; ++i)
  146. {
  147. points[i] = m_worldTransform.transform(points[i]);
  148. gpuLight.m_edgePoints[i] = points[i].xyz0();
  149. }
  150. if(reallyShadow)
  151. {
  152. 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);
  153. const Mat4 proj = Mat4::calculatePerspectiveProjectionMatrix(m_spot.m_outerAngle, m_spot.m_outerAngle, kClusterObjectFrustumNearPlane,
  154. m_spot.m_distance);
  155. const Mat4 uvToAtlas(m_shadowAtlasUvViewports[0].z(), 0.0f, 0.0f, m_shadowAtlasUvViewports[0].x(), 0.0f, m_shadowAtlasUvViewports[0].w(),
  156. 0.0f, m_shadowAtlasUvViewports[0].y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
  157. m_spot.m_viewMat = Mat3x4(m_worldTransform.getInverse());
  158. m_spot.m_viewProjMat = proj * Mat4(m_spot.m_viewMat, Vec4(0.0f, 0.0f, 0.0f, 1.0f));
  159. const Mat4 texMat = uvToAtlas * biasMat4 * m_spot.m_viewProjMat;
  160. gpuLight.m_spotLightMatrixOrPointLightUvViewports[0] = texMat.getRow(0);
  161. gpuLight.m_spotLightMatrixOrPointLightUvViewports[1] = texMat.getRow(1);
  162. gpuLight.m_spotLightMatrixOrPointLightUvViewports[2] = texMat.getRow(2);
  163. gpuLight.m_spotLightMatrixOrPointLightUvViewports[3] = texMat.getRow(3);
  164. }
  165. if(!m_gpuSceneLight.isValid())
  166. {
  167. m_gpuSceneLight.allocate();
  168. }
  169. m_gpuSceneLight.uploadToGpuScene(gpuLight);
  170. }
  171. else if(m_type == LightComponentType::kDirectional)
  172. {
  173. m_gpuSceneLight.free();
  174. }
  175. m_shapeDirty = false;
  176. m_otherDirty = false;
  177. return Error::kNone;
  178. }
  179. void LightComponent::computeCascadeFrustums(const Frustum& primaryFrustum, ConstWeakArray<F32> cascadeDistances, WeakArray<Mat4> cascadeProjMats,
  180. WeakArray<Mat3x4> cascadeViewMats) const
  181. {
  182. ANKI_ASSERT(m_type == LightComponentType::kDirectional);
  183. ANKI_ASSERT(m_shadow);
  184. ANKI_ASSERT(cascadeProjMats.getSize() <= kMaxShadowCascades && cascadeProjMats.getSize() > 0);
  185. ANKI_ASSERT(cascadeDistances.getSize() == cascadeProjMats.getSize());
  186. const U32 shadowCascadeCount = cascadeProjMats.getSize();
  187. // Compute the texture matrices
  188. if(primaryFrustum.getFrustumType() == FrustumType::kPerspective)
  189. {
  190. // Get some stuff
  191. const F32 fovX = primaryFrustum.getFovX();
  192. const F32 fovY = primaryFrustum.getFovY();
  193. // Compute a sphere per cascade
  194. Array<Sphere, kMaxShadowCascades> boundingSpheres;
  195. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  196. {
  197. // Compute the center of the sphere
  198. // ^ z
  199. // |
  200. // ----------|---------- A(a, -f)
  201. // \ | /
  202. // \ | /
  203. // \ C(0,z) /
  204. // \ | /
  205. // \ | /
  206. // \---|---/ B(b, -n)
  207. // \ | /
  208. // \ | /
  209. // v
  210. // --------------------------> x
  211. // |
  212. // The square distance of A-C is equal to B-C. Solve the equation to find the z.
  213. const F32 f = cascadeDistances[cascade]; // Cascade far
  214. const F32 n = (cascade == 0) ? primaryFrustum.getNear() : cascadeDistances[cascade - 1]; // Cascade near
  215. const F32 a = f * tan(fovY / 2.0f) * fovX / fovY;
  216. const F32 b = n * tan(fovY / 2.0f) * fovX / fovY;
  217. const F32 z = (b * b + n * n - a * a - f * f) / (2.0f * (f - n));
  218. ANKI_ASSERT(absolute((Vec2(a, -f) - Vec2(0, z)).getLength() - (Vec2(b, -n) - Vec2(0, z)).getLength()) <= kEpsilonf * 100.0f);
  219. Vec3 C(0.0f, 0.0f, z); // Sphere center
  220. // Compute the radius of the sphere
  221. const Vec3 A(a, tan(fovY / 2.0f) * f, -f);
  222. const F32 r = (A - C).getLength();
  223. // Set the sphere
  224. boundingSpheres[cascade].setRadius(r);
  225. boundingSpheres[cascade].setCenter(primaryFrustum.getWorldTransform().transform(C));
  226. }
  227. // Compute the matrices
  228. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  229. {
  230. const Sphere& sphere = boundingSpheres[cascade];
  231. const Vec3 sphereCenter = sphere.getCenter().xyz();
  232. const F32 sphereRadius = sphere.getRadius();
  233. const Vec3& lightDir = getDirection();
  234. Array<Vec3, 2> sceneBounds = SceneGraph::getSingleton().getSceneBounds();
  235. const Vec3 sceneMin = sceneBounds[0] - Vec3(sphereRadius); // Push the bounds a bit
  236. const Vec3 sceneMax = sceneBounds[1] + Vec3(sphereRadius);
  237. // Compute the intersections with the scene bounds
  238. Vec3 eye;
  239. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  240. {
  241. // Inside the scene bounds
  242. const Aabb sceneBox(sceneMin, sceneMax);
  243. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  244. eye = sphereCenter + t * (-lightDir);
  245. }
  246. else
  247. {
  248. eye = sphereCenter + sphereRadius * (-lightDir);
  249. }
  250. // View
  251. const Vec3 zAxis = m_worldTransform.getRotation().getZAxis();
  252. const Vec3 xAxis = Vec3(0.0f, 1.0f, 0.0f).cross(zAxis);
  253. const Vec3 yAxis = zAxis.cross(xAxis);
  254. Mat3x4 rot;
  255. rot.setXAxis(xAxis);
  256. rot.setYAxis(yAxis);
  257. rot.setZAxis(zAxis);
  258. rot.setTranslationPart(Vec3(0.0f));
  259. const Transform cascadeTransform(eye.xyz0(), rot, 1.0f);
  260. const Mat4 cascadeViewMat = Mat4(cascadeTransform.getInverse());
  261. // Projection
  262. const F32 far = (eye - sphereCenter).getLength() + sphereRadius;
  263. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(sphereRadius, -sphereRadius, sphereRadius, -sphereRadius,
  264. kClusterObjectFrustumNearPlane, far);
  265. // Now it's time to stabilize the shadows by aligning the projection matrix
  266. {
  267. // Project a random fixed point to the light matrix
  268. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1();
  269. // Chose a random low shadowmap size and align the random point
  270. const F32 shadowmapSize = 128.0f;
  271. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  272. const F32 alignedX = std::round(randomPointAlmostLightSpace.x() * shadowmapSize2) / shadowmapSize2;
  273. const F32 alignedY = std::round(randomPointAlmostLightSpace.y() * shadowmapSize2) / shadowmapSize2;
  274. const F32 dx = alignedX - randomPointAlmostLightSpace.x();
  275. const F32 dy = alignedY - randomPointAlmostLightSpace.y();
  276. // Fix the projection matrix by applying an offset
  277. Mat4 correctionTranslationMat = Mat4::getIdentity();
  278. correctionTranslationMat.setTranslationPart(Vec4(dx, dy, 0, 1.0f));
  279. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  280. }
  281. // Write the results
  282. cascadeProjMats[cascade] = cascadeProjMat;
  283. cascadeViewMats[cascade] = Mat3x4(cascadeViewMat);
  284. }
  285. }
  286. else
  287. {
  288. ANKI_ASSERT(!"TODO");
  289. }
  290. }
  291. void LightComponent::setShadowAtlasUvViewports(ConstWeakArray<Vec4> viewports)
  292. {
  293. ANKI_ASSERT(viewports.getSize() <= 6);
  294. if(m_type == LightComponentType::kPoint)
  295. {
  296. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 6);
  297. }
  298. else if(m_type == LightComponentType::kSpot)
  299. {
  300. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 1);
  301. }
  302. else
  303. {
  304. ANKI_ASSERT(viewports.getSize() == 0);
  305. }
  306. const Bool dirty = m_shadowAtlasUvViewportCount != viewports.getSize()
  307. || memcmp(m_shadowAtlasUvViewports.getBegin(), viewports.getBegin(), viewports.getSizeInBytes()) != 0;
  308. if(dirty)
  309. {
  310. m_shadowAtlasUvViewportCount = U8(viewports.getSize());
  311. for(U32 i = 0; i < viewports.getSize(); ++i)
  312. {
  313. m_shadowAtlasUvViewports[i] = viewports[i];
  314. }
  315. m_shapeDirty = true;
  316. }
  317. }
  318. } // end namespace anki