LightComponent.cpp 11 KB

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