LightComponent.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Copyright (C) 2009-2021, 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/Components/FrustumComponent.h>
  7. #include <AnKi/Scene/SceneNode.h>
  8. #include <AnKi/Scene/SceneGraph.h>
  9. #include <AnKi/Scene/Octree.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. ANKI_SCENE_COMPONENT_STATICS(LightComponent)
  16. LightComponent::LightComponent(SceneNode* node)
  17. : SceneComponent(node, getStaticClassId())
  18. , m_node(node)
  19. , m_uuid(node->getSceneGraph().getNewUuid())
  20. , m_type(LightComponentType::POINT)
  21. , m_shadow(false)
  22. , m_markedForUpdate(true)
  23. {
  24. ANKI_ASSERT(m_uuid > 0);
  25. m_point.m_radius = 1.0f;
  26. if(node->getSceneGraph().getResourceManager().loadResource("EngineAssets/LightBulb.ankitex", m_pointDebugImage)
  27. || node->getSceneGraph().getResourceManager().loadResource("EngineAssets/SpotLight.ankitex", m_spotDebugImage))
  28. {
  29. ANKI_SCENE_LOGF("Failed to load resources");
  30. }
  31. }
  32. Error LightComponent::update(SceneNode& node, Second prevTime, Second crntTime, Bool& updated)
  33. {
  34. updated = m_markedForUpdate;
  35. m_markedForUpdate = false;
  36. if(updated && m_type == LightComponentType::SPOT)
  37. {
  38. const Mat4 biasMat4(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  39. const Mat4 proj = Mat4::calculatePerspectiveProjectionMatrix(
  40. m_spot.m_outerAngle, m_spot.m_outerAngle, CLUSTER_OBJECT_FRUSTUM_NEAR_PLANE, m_spot.m_distance);
  41. m_spot.m_textureMat = biasMat4 * proj * Mat4(m_worldtransform.getInverse());
  42. Array<Vec4, 4> points;
  43. computeEdgesOfFrustum(m_spot.m_distance, m_spot.m_outerAngle, m_spot.m_outerAngle, &points[0]);
  44. for(U32 i = 0; i < 4; ++i)
  45. {
  46. m_spot.m_edgePointsWspace[i] = m_worldtransform.transform(points[i].xyz());
  47. }
  48. }
  49. // Update the scene bounds always
  50. if(m_type == LightComponentType::DIRECTIONAL)
  51. {
  52. node.getSceneGraph().getOctree().getActualSceneBounds(m_dir.m_sceneMin, m_dir.m_sceneMax);
  53. }
  54. return Error::NONE;
  55. }
  56. void LightComponent::setupDirectionalLightQueueElement(const FrustumComponent& frustumComp,
  57. DirectionalLightQueueElement& el,
  58. WeakArray<FrustumComponent> cascadeFrustumComponents) const
  59. {
  60. ANKI_ASSERT(m_type == LightComponentType::DIRECTIONAL);
  61. ANKI_ASSERT(cascadeFrustumComponents.getSize() <= MAX_SHADOW_CASCADES2);
  62. const U32 shadowCascadeCount = cascadeFrustumComponents.getSize();
  63. el.m_drawCallback = [](RenderQueueDrawContext& ctx, ConstWeakArray<void*> userData) {
  64. ANKI_ASSERT(userData.getSize() == 1);
  65. static_cast<const LightComponent*>(userData[0])->draw(ctx);
  66. };
  67. el.m_drawCallbackUserData = this;
  68. el.m_uuid = m_uuid;
  69. el.m_diffuseColor = m_diffColor.xyz();
  70. el.m_direction = -m_worldtransform.getRotation().getZAxis().xyz();
  71. el.m_effectiveShadowDistance = frustumComp.getEffectiveShadowDistance();
  72. el.m_shadowCascadesDistancePower = frustumComp.getShadowCascadesDistancePower();
  73. el.m_shadowCascadeCount = U8(shadowCascadeCount);
  74. el.m_shadowLayer = MAX_U8;
  75. if(shadowCascadeCount == 0)
  76. {
  77. return;
  78. }
  79. // Compute the texture matrices
  80. const Mat4 lightTrf(m_worldtransform);
  81. if(frustumComp.getFrustumType() == FrustumType::PERSPECTIVE)
  82. {
  83. // Get some stuff
  84. const F32 fovX = frustumComp.getFovX();
  85. const F32 fovY = frustumComp.getFovY();
  86. // Compute a sphere per cascade
  87. Array<Sphere, MAX_SHADOW_CASCADES2> boundingSpheres;
  88. for(U32 i = 0; i < shadowCascadeCount; ++i)
  89. {
  90. // Compute the center of the sphere
  91. // ^ z
  92. // |
  93. // ----------|---------- A(a, -f)
  94. // \ | /
  95. // \ | /
  96. // \ C(0,z) /
  97. // \ | /
  98. // \ | /
  99. // \---|---/ B(b, -n)
  100. // \ | /
  101. // \ | /
  102. // v
  103. // --------------------------> x
  104. // |
  105. // The square distance of A-C is equal to B-C. Solve the equation to find the z.
  106. const F32 f = frustumComp.computeShadowCascadeDistance(i); // Cascade far
  107. const F32 n =
  108. (i == 0) ? frustumComp.getNear() : frustumComp.computeShadowCascadeDistance(i - 1); // Cascade near
  109. const F32 a = f * tan(fovY / 2.0f) * fovX / fovY;
  110. const F32 b = n * tan(fovY / 2.0f) * fovX / fovY;
  111. const F32 z = (b * b + n * n - a * a - f * f) / (2.0f * (f - n));
  112. ANKI_ASSERT(absolute((Vec2(a, -f) - Vec2(0, z)).getLength() - (Vec2(b, -n) - Vec2(0, z)).getLength())
  113. <= EPSILON * 100.0f);
  114. Vec3 C(0.0f, 0.0f, z); // Sphere center
  115. // Compute the radius of the sphere
  116. const Vec3 A(a, tan(fovY / 2.0f) * f, -f);
  117. const F32 r = (A - C).getLength();
  118. // Set the sphere
  119. boundingSpheres[i].setRadius(r);
  120. boundingSpheres[i].setCenter(frustumComp.getWorldTransform().transform(C));
  121. }
  122. // Compute the matrices
  123. for(U32 i = 0; i < shadowCascadeCount; ++i)
  124. {
  125. const Sphere& sphere = boundingSpheres[i];
  126. const Vec3 sphereCenter = sphere.getCenter().xyz();
  127. const F32 sphereRadius = sphere.getRadius();
  128. const Vec3& lightDir = el.m_direction;
  129. const Vec3 sceneMin = m_dir.m_sceneMin - Vec3(sphereRadius); // Push the bounds a bit
  130. const Vec3 sceneMax = m_dir.m_sceneMax + Vec3(sphereRadius);
  131. // Compute the intersections with the scene bounds
  132. Vec3 eye;
  133. if(sphereCenter > sceneMin && sphereCenter < sceneMax)
  134. {
  135. // Inside the scene bounds
  136. const Aabb sceneBox(sceneMin, sceneMax);
  137. const F32 t = testCollisionInside(sceneBox, Ray(sphereCenter, -lightDir));
  138. eye = sphereCenter + t * (-lightDir);
  139. }
  140. else
  141. {
  142. eye = sphereCenter + sphereRadius * (-lightDir);
  143. }
  144. // Projection
  145. const F32 far = (eye - sphereCenter).getLength() + sphereRadius;
  146. Mat4 cascadeProjMat = Mat4::calculateOrthographicProjectionMatrix(
  147. sphereRadius, -sphereRadius, sphereRadius, -sphereRadius, CLUSTER_OBJECT_FRUSTUM_NEAR_PLANE, far);
  148. // View
  149. Transform cascadeTransform = m_worldtransform;
  150. cascadeTransform.setOrigin(eye.xyz0());
  151. const Mat4 cascadeViewMat = Mat4(cascadeTransform.getInverse());
  152. // Now it's time to stabilize the shadows by aligning the projection matrix
  153. {
  154. // Project a random fixed point to the light matrix
  155. const Vec4 randomPointAlmostLightSpace = (cascadeProjMat * cascadeViewMat) * Vec3(0.0f).xyz1();
  156. // Chose a random low shadowmap size and align the random point
  157. const F32 shadowmapSize = 128.0f;
  158. const F32 shadowmapSize2 = shadowmapSize / 2.0f; // Div with 2 because the projected point is in NDC
  159. const F32 alignedX = std::round(randomPointAlmostLightSpace.x() * shadowmapSize2) / shadowmapSize2;
  160. const F32 alignedY = std::round(randomPointAlmostLightSpace.y() * shadowmapSize2) / shadowmapSize2;
  161. const F32 dx = alignedX - randomPointAlmostLightSpace.x();
  162. const F32 dy = alignedY - randomPointAlmostLightSpace.y();
  163. // Fix the projection matrix by applying an offset
  164. Mat4 correctionTranslationMat = Mat4::getIdentity();
  165. correctionTranslationMat.setTranslationPart(Vec4(dx, dy, 0, 1.0f));
  166. cascadeProjMat = correctionTranslationMat * cascadeProjMat;
  167. }
  168. // Light matrix
  169. static 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,
  170. 0.0f, 0.0f, 1.0f);
  171. el.m_textureMatrices[i] = biasMat4 * cascadeProjMat * cascadeViewMat;
  172. // Fill the frustum with the fixed projection parameters from the fixed projection matrix
  173. Plane plane;
  174. extractClipPlane(cascadeProjMat, FrustumPlaneType::LEFT, plane);
  175. const F32 left = plane.getOffset();
  176. extractClipPlane(cascadeProjMat, FrustumPlaneType::RIGHT, plane);
  177. const F32 right = -plane.getOffset();
  178. extractClipPlane(cascadeProjMat, FrustumPlaneType::TOP, plane);
  179. const F32 top = -plane.getOffset();
  180. extractClipPlane(cascadeProjMat, FrustumPlaneType::BOTTOM, plane);
  181. const F32 bottom = plane.getOffset();
  182. FrustumComponent& cascadeFrustumComp = cascadeFrustumComponents[i];
  183. cascadeFrustumComp.setOrthographic(CLUSTER_OBJECT_FRUSTUM_NEAR_PLANE, far, right, left, top, bottom);
  184. cascadeFrustumComp.setWorldTransform(cascadeTransform);
  185. }
  186. }
  187. else
  188. {
  189. ANKI_ASSERT(!"TODO");
  190. }
  191. }
  192. void LightComponent::draw(RenderQueueDrawContext& ctx) const
  193. {
  194. const Bool enableDepthTest = ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DEPTH_TEST_ON);
  195. if(enableDepthTest)
  196. {
  197. ctx.m_commandBuffer->setDepthCompareOperation(CompareOperation::LESS);
  198. }
  199. else
  200. {
  201. ctx.m_commandBuffer->setDepthCompareOperation(CompareOperation::ALWAYS);
  202. }
  203. Vec3 color = m_diffColor.xyz();
  204. color /= max(max(color.x(), color.y()), color.z());
  205. ImageResourcePtr imageResource = (m_type == LightComponentType::POINT) ? m_pointDebugImage : m_spotDebugImage;
  206. m_node->getSceneGraph().getDebugDrawer().drawBillboardTexture(
  207. ctx.m_projectionMatrix, ctx.m_viewMatrix, m_worldtransform.getOrigin().xyz(), color.xyz1(),
  208. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), imageResource->getTextureView(),
  209. ctx.m_sampler, Vec2(0.75f), *ctx.m_stagingGpuAllocator, ctx.m_commandBuffer);
  210. // Restore state
  211. if(!enableDepthTest)
  212. {
  213. ctx.m_commandBuffer->setDepthCompareOperation(CompareOperation::LESS);
  214. }
  215. }
  216. } // end namespace anki