LightComponent.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // Copyright (C) 2009-present, 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<Vec3, 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.invert());
  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,
  181. WeakArray<Array<F32, U32(FrustumPlaneType::kCount)>> cascadePlanes) const
  182. {
  183. ANKI_ASSERT(m_type == LightComponentType::kDirectional);
  184. ANKI_ASSERT(m_shadow);
  185. ANKI_ASSERT(cascadeProjMats.getSize() <= kMaxShadowCascades && cascadeProjMats.getSize() > 0);
  186. ANKI_ASSERT(cascadeDistances.getSize() == cascadeProjMats.getSize());
  187. const U32 shadowCascadeCount = cascadeProjMats.getSize();
  188. // Compute the texture matrices
  189. if(primaryFrustum.getFrustumType() == FrustumType::kPerspective)
  190. {
  191. // Get some stuff
  192. const F32 fovX = primaryFrustum.getFovX();
  193. const F32 fovY = primaryFrustum.getFovY();
  194. // Compute a sphere per cascade
  195. Array<Sphere, kMaxShadowCascades> boundingSpheres;
  196. Array<Vec3, 4> prevFarPlaneEdges;
  197. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  198. {
  199. if(cascade == 0)
  200. {
  201. Array<Vec3, 5> edgePoints;
  202. edgePoints[0] = Vec3(0.0f);
  203. computeEdgesOfFrustum(cascadeDistances[cascade], fovX, fovY, &edgePoints[1]);
  204. boundingSpheres[cascade] = computeBoundingSphere(edgePoints.getBegin(), edgePoints.getSize(), sizeof(edgePoints[0]));
  205. memcpy(&prevFarPlaneEdges[0], &edgePoints[1], sizeof(prevFarPlaneEdges));
  206. }
  207. else
  208. {
  209. Array<Vec3, 8> edgePoints;
  210. computeEdgesOfFrustum(cascadeDistances[cascade], fovX, fovY, &edgePoints[0]);
  211. memcpy(&edgePoints[4], &prevFarPlaneEdges[0], sizeof(prevFarPlaneEdges));
  212. boundingSpheres[cascade] = computeBoundingSphere(edgePoints.getBegin(), edgePoints.getSize(), sizeof(edgePoints[0]));
  213. memcpy(&prevFarPlaneEdges[0], &edgePoints[0], sizeof(prevFarPlaneEdges));
  214. }
  215. boundingSpheres[cascade].setCenter(primaryFrustum.getWorldTransform().transform(boundingSpheres[cascade].getCenter()));
  216. }
  217. // Compute the matrices
  218. for(U32 cascade = 0; cascade < shadowCascadeCount; ++cascade)
  219. {
  220. const Sphere& sphere = boundingSpheres[cascade];
  221. const Vec3 sphereCenter = sphere.getCenter().xyz();
  222. const F32 sphereRadius = sphere.getRadius();
  223. const Vec3& lightDir = getDirection();
  224. Array<Vec3, 2> sceneBounds = SceneGraph::getSingleton().getSceneBounds();
  225. const Vec3 sceneMin = sceneBounds[0] - Vec3(sphereRadius); // Push the bounds a bit
  226. const Vec3 sceneMax = sceneBounds[1] + Vec3(sphereRadius);
  227. // Compute the intersections with the scene bounds
  228. Vec3 eye;
  229. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  230. {
  231. // Inside the scene bounds
  232. const Aabb sceneBox(sceneMin, sceneMax);
  233. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  234. eye = sphereCenter + t * (-lightDir);
  235. }
  236. else
  237. {
  238. eye = sphereCenter + sphereRadius * (-lightDir);
  239. }
  240. // View
  241. const Vec3 zAxis = m_worldTransform.getRotation().getZAxis();
  242. const Vec3 xAxis = Vec3(0.0f, 1.0f, 0.0f).cross(zAxis).normalize();
  243. const Vec3 yAxis = zAxis.cross(xAxis).normalize();
  244. Mat3x4 rot;
  245. rot.setXAxis(xAxis);
  246. rot.setYAxis(yAxis);
  247. rot.setZAxis(zAxis);
  248. rot.setTranslationPart(Vec3(0.0f));
  249. const Transform cascadeTransform(eye.xyz0(), rot, Vec4(1.0f, 1.0f, 1.0f, 0.0f));
  250. const Mat4 cascadeViewMat = Mat4(cascadeTransform.invert());
  251. // Projection
  252. const F32 far = (eye - sphereCenter).length() + sphereRadius;
  253. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(sphereRadius, -sphereRadius, sphereRadius, -sphereRadius,
  254. kClusterObjectFrustumNearPlane, far);
  255. if(cascadePlanes.getSize() > 0)
  256. {
  257. cascadePlanes[cascade][FrustumPlaneType::kLeft] = -sphereRadius;
  258. cascadePlanes[cascade][FrustumPlaneType::kRight] = sphereRadius;
  259. cascadePlanes[cascade][FrustumPlaneType::kBottom] = -sphereRadius;
  260. cascadePlanes[cascade][FrustumPlaneType::kTop] = sphereRadius;
  261. cascadePlanes[cascade][FrustumPlaneType::kNear] = kClusterObjectFrustumNearPlane;
  262. cascadePlanes[cascade][FrustumPlaneType::kFar] = far;
  263. }
  264. // Now it's time to stabilize the shadows by aligning the projection matrix
  265. {
  266. // Project a random fixed point to the light matrix
  267. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1();
  268. // Chose a random low shadowmap size and align the random point
  269. const F32 shadowmapSize = 128.0f;
  270. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  271. const F32 alignedX = std::round(randomPointAlmostLightSpace.x() * shadowmapSize2) / shadowmapSize2;
  272. const F32 alignedY = std::round(randomPointAlmostLightSpace.y() * shadowmapSize2) / shadowmapSize2;
  273. const F32 dx = alignedX - randomPointAlmostLightSpace.x();
  274. const F32 dy = alignedY - randomPointAlmostLightSpace.y();
  275. // Fix the projection matrix by applying an offset
  276. Mat4 correctionTranslationMat = Mat4::getIdentity();
  277. correctionTranslationMat.setTranslationPart(Vec3(dx, dy, 0.0f));
  278. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  279. }
  280. // Write the results
  281. cascadeProjMats[cascade] = cascadeProjMat;
  282. cascadeViewMats[cascade] = Mat3x4(cascadeViewMat);
  283. }
  284. }
  285. else
  286. {
  287. ANKI_ASSERT(!"TODO");
  288. }
  289. }
  290. void LightComponent::setShadowAtlasUvViewports(ConstWeakArray<Vec4> viewports)
  291. {
  292. ANKI_ASSERT(viewports.getSize() <= 6);
  293. if(m_type == LightComponentType::kPoint)
  294. {
  295. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 6);
  296. }
  297. else if(m_type == LightComponentType::kSpot)
  298. {
  299. ANKI_ASSERT(viewports.getSize() == 0 || viewports.getSize() == 1);
  300. }
  301. else
  302. {
  303. ANKI_ASSERT(viewports.getSize() == 0);
  304. }
  305. const Bool dirty = m_shadowAtlasUvViewportCount != viewports.getSize()
  306. || memcmp(m_shadowAtlasUvViewports.getBegin(), viewports.getBegin(), viewports.getSizeInBytes()) != 0;
  307. if(dirty)
  308. {
  309. m_shadowAtlasUvViewportCount = U8(viewports.getSize());
  310. for(U32 i = 0; i < viewports.getSize(); ++i)
  311. {
  312. m_shadowAtlasUvViewports[i] = viewports[i];
  313. }
  314. m_shapeDirty = true;
  315. }
  316. }
  317. } // end namespace anki