Light.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "Light.h"
  27. #include "Node.h"
  28. #include "OctreeQuery.h"
  29. #include "Profiler.h"
  30. #include "ResourceCache.h"
  31. #include "Texture2D.h"
  32. #include "TextureCube.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. extern const char* SCENE_CATEGORY;
  37. static const LightType DEFAULT_LIGHTTYPE = LIGHT_POINT;
  38. static const float DEFAULT_RANGE = 10.0f;
  39. static const float DEFAULT_FOV = 30.0f;
  40. static const float DEFAULT_SPECULARINTENSITY = 1.0f;
  41. static const float DEFAULT_BRIGHTNESS = 1.0f;
  42. static const float DEFAULT_CONSTANTBIAS = 0.0001f;
  43. static const float DEFAULT_SLOPESCALEDBIAS = 0.5f;
  44. static const float DEFAULT_BIASAUTOADJUST = 1.0f;
  45. static const float DEFAULT_SHADOWFADESTART = 0.8f;
  46. static const float DEFAULT_SHADOWQUANTIZE = 0.5f;
  47. static const float DEFAULT_SHADOWMINVIEW = 3.0f;
  48. static const float DEFAULT_SHADOWNEARFARRATIO = 0.002f;
  49. static const float DEFAULT_SHADOWSPLIT = 1000.0f;
  50. static const char* typeNames[] =
  51. {
  52. "Directional",
  53. "Spot",
  54. "Point",
  55. 0
  56. };
  57. void BiasParameters::Validate()
  58. {
  59. constantBias_ = Clamp(constantBias_, -1.0f, 1.0f);
  60. slopeScaledBias_ = Clamp(slopeScaledBias_, -16.0f, 16.0f);
  61. }
  62. void CascadeParameters::Validate()
  63. {
  64. for (unsigned i = 0; i < MAX_CASCADE_SPLITS; ++i)
  65. splits_[i] = Max(splits_[i], 0.0f);
  66. fadeStart_ = Clamp(fadeStart_, M_EPSILON, 1.0f);
  67. }
  68. void FocusParameters::Validate()
  69. {
  70. quantize_ = Max(quantize_, SHADOW_MIN_QUANTIZE);
  71. minView_ = Max(minView_, SHADOW_MIN_VIEW);
  72. }
  73. template<> LightType Variant::Get<LightType>() const
  74. {
  75. return (LightType)GetInt();
  76. }
  77. Light::Light(Context* context) :
  78. Drawable(context, DRAWABLE_LIGHT),
  79. lightType_(DEFAULT_LIGHTTYPE),
  80. shadowBias_(BiasParameters(DEFAULT_CONSTANTBIAS, DEFAULT_SLOPESCALEDBIAS)),
  81. shadowCascade_(CascadeParameters(DEFAULT_SHADOWSPLIT, 0.0f, 0.0f, 0.0f, DEFAULT_SHADOWFADESTART)),
  82. shadowFocus_(FocusParameters(true, true, true, DEFAULT_SHADOWQUANTIZE, DEFAULT_SHADOWMINVIEW)),
  83. lightQueue_(0),
  84. specularIntensity_(DEFAULT_SPECULARINTENSITY),
  85. brightness_(DEFAULT_BRIGHTNESS),
  86. range_(DEFAULT_RANGE),
  87. fov_(DEFAULT_FOV),
  88. aspectRatio_(1.0f),
  89. fadeDistance_(0.0f),
  90. shadowFadeDistance_(0.0f),
  91. shadowIntensity_(0.0f),
  92. shadowResolution_(1.0f),
  93. shadowNearFarRatio_(DEFAULT_SHADOWNEARFARRATIO),
  94. perVertex_(false)
  95. {
  96. }
  97. Light::~Light()
  98. {
  99. }
  100. void Light::RegisterObject(Context* context)
  101. {
  102. context->RegisterFactory<Light>(SCENE_CATEGORY);
  103. ACCESSOR_ATTRIBUTE(Light, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  104. ENUM_ACCESSOR_ATTRIBUTE(Light, "Light Type", GetLightType, SetLightType, LightType, typeNames, DEFAULT_LIGHTTYPE, AM_DEFAULT);
  105. REF_ACCESSOR_ATTRIBUTE(Light, VAR_COLOR, "Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT);
  106. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Specular Intensity", GetSpecularIntensity, SetSpecularIntensity, float, DEFAULT_SPECULARINTENSITY, AM_DEFAULT);
  107. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Brightness Multiplier", GetBrightness, SetBrightness, float, DEFAULT_BRIGHTNESS, AM_DEFAULT);
  108. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Range", GetRange, SetRange, float, DEFAULT_RANGE, AM_DEFAULT);
  109. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Spot FOV", GetFov, SetFov, float, DEFAULT_FOV, AM_DEFAULT);
  110. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Spot Aspect Ratio", GetAspectRatio, SetAspectRatio, float, 1.0f, AM_DEFAULT);
  111. ACCESSOR_ATTRIBUTE(Light, VAR_RESOURCEREF, "Attenuation Texture", GetRampTextureAttr, SetRampTextureAttr, ResourceRef, ResourceRef(Texture2D::GetTypeStatic()), AM_DEFAULT);
  112. ACCESSOR_ATTRIBUTE(Light, VAR_RESOURCEREF, "Light Shape Texture", GetShapeTextureAttr, SetShapeTextureAttr, ResourceRef, ResourceRef(Texture2D::GetTypeStatic()), AM_DEFAULT);
  113. ACCESSOR_ATTRIBUTE(Light, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  114. ATTRIBUTE(Light, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  115. ATTRIBUTE(Light, VAR_BOOL, "Per Vertex", perVertex_, false, AM_DEFAULT);
  116. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  117. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Fade Distance", GetFadeDistance, SetFadeDistance, float, 0.0f, AM_DEFAULT);
  118. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  119. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Fade Distance", GetShadowFadeDistance, SetShadowFadeDistance, float, 0.0f, AM_DEFAULT);
  120. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Intensity", GetShadowIntensity, SetShadowIntensity, float, 0.0f, AM_DEFAULT);
  121. ACCESSOR_ATTRIBUTE(Light, VAR_FLOAT, "Shadow Resolution", GetShadowResolution, SetShadowResolution, float, 1.0f, AM_DEFAULT);
  122. ATTRIBUTE(Light, VAR_BOOL, "Focus To Scene", shadowFocus_.focus_, true, AM_DEFAULT);
  123. ATTRIBUTE(Light, VAR_BOOL, "Non-uniform View", shadowFocus_.nonUniform_, true, AM_DEFAULT);
  124. ATTRIBUTE(Light, VAR_BOOL, "Auto-Reduce Size", shadowFocus_.autoSize_, true, AM_DEFAULT);
  125. ATTRIBUTE(Light, VAR_VECTOR4, "CSM Splits", shadowCascade_.splits_, Vector4(DEFAULT_SHADOWSPLIT, 0.0f, 0.0f, 0.0f), AM_DEFAULT);
  126. ATTRIBUTE(Light, VAR_FLOAT, "CSM Fade Start", shadowCascade_.fadeStart_, DEFAULT_SHADOWFADESTART, AM_DEFAULT);
  127. ATTRIBUTE(Light, VAR_FLOAT, "CSM Bias Auto Adjust", shadowCascade_.biasAutoAdjust_, DEFAULT_BIASAUTOADJUST, AM_DEFAULT);
  128. ATTRIBUTE(Light, VAR_FLOAT, "View Size Quantize", shadowFocus_.quantize_, DEFAULT_SHADOWQUANTIZE, AM_DEFAULT);
  129. ATTRIBUTE(Light, VAR_FLOAT, "View Size Minimum", shadowFocus_.minView_, DEFAULT_SHADOWMINVIEW, AM_DEFAULT);
  130. ATTRIBUTE(Light, VAR_FLOAT, "Depth Constant Bias", shadowBias_.constantBias_, DEFAULT_CONSTANTBIAS, AM_DEFAULT);
  131. ATTRIBUTE(Light, VAR_FLOAT, "Depth Slope Bias", shadowBias_.slopeScaledBias_, DEFAULT_SLOPESCALEDBIAS, AM_DEFAULT);
  132. ATTRIBUTE(Light, VAR_FLOAT, "Near/Farclip Ratio", shadowNearFarRatio_, DEFAULT_SHADOWNEARFARRATIO, AM_DEFAULT);
  133. ATTRIBUTE(Light, VAR_INT, "View Mask", viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
  134. ATTRIBUTE(Light, VAR_INT, "Light Mask", lightMask_, DEFAULT_LIGHTMASK, AM_DEFAULT);
  135. }
  136. void Light::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  137. {
  138. Component::OnSetAttribute(attr, src);
  139. // Validate the bias, cascade & focus parameters
  140. if (attr.offset_ >= offsetof(Light, shadowBias_) && attr.offset_ < (offsetof(Light, shadowBias_) + sizeof(BiasParameters)))
  141. shadowBias_.Validate();
  142. else if (attr.offset_ >= offsetof(Light, shadowCascade_) && attr.offset_ < (offsetof(Light, shadowCascade_) + sizeof(CascadeParameters)))
  143. shadowCascade_.Validate();
  144. else if (attr.offset_ >= offsetof(Light, shadowFocus_) && attr.offset_ < (offsetof(Light, shadowFocus_) + sizeof(FocusParameters)))
  145. shadowFocus_.Validate();
  146. }
  147. void Light::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  148. {
  149. // Do not record a raycast result for a directional light, as it would block all other results
  150. if (lightType_ == LIGHT_DIRECTIONAL)
  151. return;
  152. float distance;
  153. switch (query.level_)
  154. {
  155. case RAY_AABB:
  156. Drawable::ProcessRayQuery(query, results);
  157. return;
  158. case RAY_OBB:
  159. {
  160. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  161. Ray localRay = query.ray_.Transformed(inverse);
  162. distance = localRay.HitDistance(GetWorldBoundingBox().Transformed(inverse));
  163. if (distance >= query.maxDistance_)
  164. return;
  165. }
  166. break;
  167. case RAY_TRIANGLE:
  168. if (lightType_ == LIGHT_SPOT)
  169. {
  170. distance = query.ray_.HitDistance(GetFrustum());
  171. if (distance >= query.maxDistance_)
  172. return;
  173. }
  174. else
  175. {
  176. distance = query.ray_.HitDistance(Sphere(node_->GetWorldPosition(), range_));
  177. if (distance >= query.maxDistance_)
  178. return;
  179. }
  180. break;
  181. }
  182. // If the code reaches here then we have a hit
  183. RayQueryResult result;
  184. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  185. result.normal_ = -query.ray_.direction_;
  186. result.distance_ = distance;
  187. result.drawable_ = this;
  188. result.node_ = node_;
  189. result.subObject_ = M_MAX_UNSIGNED;
  190. results.Push(result);
  191. }
  192. void Light::UpdateBatches(const FrameInfo& frame)
  193. {
  194. switch (lightType_)
  195. {
  196. case LIGHT_DIRECTIONAL:
  197. // Directional light affects the whole scene, so it is always "closest"
  198. distance_ = 0.0f;
  199. break;
  200. default:
  201. distance_ = frame.camera_->GetDistance(node_->GetWorldPosition());
  202. break;
  203. }
  204. }
  205. void Light::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  206. {
  207. Color color = GetEffectiveColor();
  208. if (debug && IsEnabledEffective())
  209. {
  210. switch (lightType_)
  211. {
  212. case LIGHT_DIRECTIONAL:
  213. {
  214. Vector3 start = node_->GetWorldPosition();
  215. Vector3 end = start + node_->GetWorldDirection() * 10.f;
  216. for (short i = -1; i < 2; ++i)
  217. for (short j = -1; j < 2; ++j)
  218. {
  219. Vector3 offset = Vector3::UP * (5.f * i) + Vector3::RIGHT * (5.f * j);
  220. debug->AddSphere(Sphere(start + offset, 0.1f), color, depthTest);
  221. debug->AddLine(start + offset, end + offset, color, depthTest);
  222. }
  223. }
  224. break;
  225. case LIGHT_SPOT:
  226. debug->AddFrustum(GetFrustum(), color, depthTest);
  227. break;
  228. case LIGHT_POINT:
  229. debug->AddSphere(Sphere(node_->GetWorldPosition(), range_), color, depthTest);
  230. break;
  231. }
  232. }
  233. }
  234. void Light::SetLightType(LightType type)
  235. {
  236. lightType_ = type;
  237. OnMarkedDirty(node_);
  238. MarkNetworkUpdate();
  239. }
  240. void Light::SetPerVertex(bool enable)
  241. {
  242. perVertex_ = enable;
  243. MarkNetworkUpdate();
  244. }
  245. void Light::SetColor(const Color& color)
  246. {
  247. color_ = Color(color.r_, color.g_, color.b_, 1.0f);
  248. MarkNetworkUpdate();
  249. }
  250. void Light::SetSpecularIntensity(float intensity)
  251. {
  252. specularIntensity_ = Max(intensity, 0.0f);
  253. MarkNetworkUpdate();
  254. }
  255. void Light::SetBrightness(float brightness)
  256. {
  257. brightness_ = brightness;
  258. MarkNetworkUpdate();
  259. }
  260. void Light::SetRange(float range)
  261. {
  262. range_ = Max(range, 0.0f);
  263. OnMarkedDirty(node_);
  264. MarkNetworkUpdate();
  265. }
  266. void Light::SetFov(float fov)
  267. {
  268. fov_ = Clamp(fov, 0.0f, M_MAX_FOV);
  269. OnMarkedDirty(node_);
  270. MarkNetworkUpdate();
  271. }
  272. void Light::SetAspectRatio(float aspectRatio)
  273. {
  274. aspectRatio_ = Max(aspectRatio, M_EPSILON);
  275. OnMarkedDirty(node_);
  276. MarkNetworkUpdate();
  277. }
  278. void Light::SetShadowNearFarRatio(float nearFarRatio)
  279. {
  280. shadowNearFarRatio_ = Clamp(nearFarRatio, 0.0f, 0.5f);
  281. MarkNetworkUpdate();
  282. }
  283. void Light::SetFadeDistance(float distance)
  284. {
  285. fadeDistance_ = Max(distance, 0.0f);
  286. MarkNetworkUpdate();
  287. }
  288. void Light::SetShadowBias(const BiasParameters& parameters)
  289. {
  290. shadowBias_ = parameters;
  291. shadowBias_.Validate();
  292. MarkNetworkUpdate();
  293. }
  294. void Light::SetShadowCascade(const CascadeParameters& parameters)
  295. {
  296. shadowCascade_ = parameters;
  297. shadowCascade_.Validate();
  298. MarkNetworkUpdate();
  299. }
  300. void Light::SetShadowFocus(const FocusParameters& parameters)
  301. {
  302. shadowFocus_ = parameters;
  303. shadowFocus_.Validate();
  304. MarkNetworkUpdate();
  305. }
  306. void Light::SetShadowFadeDistance(float distance)
  307. {
  308. shadowFadeDistance_ = Max(distance, 0.0f);
  309. MarkNetworkUpdate();
  310. }
  311. void Light::SetShadowIntensity(float intensity)
  312. {
  313. shadowIntensity_ = Clamp(intensity, 0.0f, 1.0f);
  314. MarkNetworkUpdate();
  315. }
  316. void Light::SetShadowResolution(float resolution)
  317. {
  318. shadowResolution_ = Clamp(resolution, 0.125f, 1.0f);
  319. MarkNetworkUpdate();
  320. }
  321. void Light::SetRampTexture(Texture* texture)
  322. {
  323. rampTexture_ = texture;
  324. MarkNetworkUpdate();
  325. }
  326. void Light::SetShapeTexture(Texture* texture)
  327. {
  328. shapeTexture_ = texture;
  329. MarkNetworkUpdate();
  330. }
  331. Frustum Light::GetFrustum() const
  332. {
  333. // Note: frustum is unaffected by node or parent scale
  334. Matrix3x4 frustumTransform(node_ ? Matrix3x4(node_->GetWorldPosition(), node_->GetWorldRotation(), 1.0f) :
  335. Matrix3x4::IDENTITY);
  336. Frustum ret;
  337. ret.Define(fov_, aspectRatio_, 1.0f, M_MIN_NEARCLIP, range_, frustumTransform);
  338. return ret;
  339. }
  340. Matrix3x4 Light::GetDirLightTransform(Camera* camera, bool getNearQuad)
  341. {
  342. if (!camera)
  343. return Matrix3x4::IDENTITY;
  344. Vector3 nearVector, farVector;
  345. camera->GetFrustumSize(nearVector, farVector);
  346. float nearClip = camera->GetNearClip();
  347. float farClip = camera->GetFarClip();
  348. float distance = getNearQuad ? nearClip : farClip;
  349. if (!camera->IsOrthographic())
  350. farVector *= (distance / farClip);
  351. else
  352. farVector.z_ *= (distance / farClip);
  353. // Set an epsilon from clip planes due to possible inaccuracy
  354. /// \todo Rather set an identity projection matrix
  355. farVector.z_ = Clamp(farVector.z_, (1.0f + M_LARGE_EPSILON) * nearClip, (1.0f - M_LARGE_EPSILON) * farClip);
  356. return Matrix3x4(Vector3(0.0f, 0.0f, farVector.z_), Quaternion::IDENTITY, Vector3(farVector.x_, farVector.y_, 1.0f));
  357. }
  358. const Matrix3x4& Light::GetVolumeTransform(Camera* camera)
  359. {
  360. if (!node_)
  361. return Matrix3x4::IDENTITY;
  362. switch (lightType_)
  363. {
  364. case LIGHT_DIRECTIONAL:
  365. volumeTransform_ = GetDirLightTransform(camera);
  366. break;
  367. case LIGHT_SPOT:
  368. {
  369. float yScale = tanf(fov_ * M_DEGTORAD * 0.5f) * range_;
  370. float xScale = aspectRatio_ * yScale;
  371. volumeTransform_ = Matrix3x4(node_->GetWorldPosition(), node_->GetWorldRotation(), Vector3(xScale, yScale, range_));
  372. }
  373. break;
  374. case LIGHT_POINT:
  375. volumeTransform_ = Matrix3x4(node_->GetWorldPosition(), Quaternion::IDENTITY, range_);
  376. break;
  377. }
  378. return volumeTransform_;
  379. }
  380. void Light::SetRampTextureAttr(ResourceRef value)
  381. {
  382. ResourceCache* cache = GetSubsystem<ResourceCache>();
  383. rampTexture_ = static_cast<Texture*>(cache->GetResource(value.type_, value.name_));
  384. }
  385. void Light::SetShapeTextureAttr(ResourceRef value)
  386. {
  387. ResourceCache* cache = GetSubsystem<ResourceCache>();
  388. shapeTexture_ = static_cast<Texture*>(cache->GetResource(value.type_, value.name_));
  389. }
  390. ResourceRef Light::GetRampTextureAttr() const
  391. {
  392. return GetResourceRef(rampTexture_, Texture2D::GetTypeStatic());
  393. }
  394. ResourceRef Light::GetShapeTextureAttr() const
  395. {
  396. return GetResourceRef(shapeTexture_, lightType_ == LIGHT_POINT ? TextureCube::GetTypeStatic() : Texture2D::GetTypeStatic());
  397. }
  398. void Light::OnWorldBoundingBoxUpdate()
  399. {
  400. switch (lightType_)
  401. {
  402. case LIGHT_DIRECTIONAL:
  403. // Directional light always sets humongous bounding box not affected by transform
  404. worldBoundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE);
  405. break;
  406. case LIGHT_SPOT:
  407. // Frustum is already transformed into world space
  408. worldBoundingBox_.Define(GetFrustum());
  409. break;
  410. case LIGHT_POINT:
  411. {
  412. const Vector3& center = node_->GetWorldPosition();
  413. Vector3 edge(range_, range_, range_);
  414. worldBoundingBox_.Define(center - edge, center + edge);
  415. }
  416. break;
  417. }
  418. }
  419. void Light::SetIntensitySortValue(float distance)
  420. {
  421. // When sorting lights globally, give priority to directional lights so that they will be combined into the ambient pass
  422. if (!IsNegative())
  423. {
  424. if (lightType_ != LIGHT_DIRECTIONAL)
  425. sortValue_ = Max(distance, M_MIN_NEARCLIP) / GetIntensityDivisor();
  426. else
  427. sortValue_ = M_EPSILON / GetIntensityDivisor();
  428. }
  429. else
  430. {
  431. // Give extra priority to negative lights in the global sorting order so that they're handled first, right after ambient.
  432. // Positive lights are added after them
  433. if (lightType_ != LIGHT_DIRECTIONAL)
  434. sortValue_ = -Max(distance, M_MIN_NEARCLIP) * GetIntensityDivisor();
  435. else
  436. sortValue_ = -M_LARGE_VALUE * GetIntensityDivisor();
  437. }
  438. }
  439. void Light::SetIntensitySortValue(const BoundingBox& box)
  440. {
  441. // When sorting lights for object's maximum light cap, give priority based on attenuation and intensity
  442. switch (lightType_)
  443. {
  444. case LIGHT_DIRECTIONAL:
  445. sortValue_ = 1.0f / GetIntensityDivisor();
  446. break;
  447. case LIGHT_SPOT:
  448. {
  449. Vector3 centerPos = box.Center();
  450. Vector3 lightPos = node_->GetWorldPosition();
  451. Vector3 lightDir = node_->GetWorldDirection();
  452. Ray lightRay(lightPos, lightDir);
  453. Vector3 centerProj = lightRay.Project(centerPos);
  454. float centerDistance = (centerProj - lightPos).Length();
  455. Ray centerRay(centerProj, centerPos - centerProj);
  456. float centerAngle = centerRay.HitDistance(box) / centerDistance;
  457. // Check if a corner of the bounding box is closer to the light ray than the center, use its angle in that case
  458. Vector3 cornerPos = centerPos + box.HalfSize() * Vector3(centerPos.x_ < centerProj.x_ ? 1.0f : -1.0f,
  459. centerPos.y_ < centerProj.y_ ? 1.0f : -1.0f, centerPos.z_ < centerProj.z_ ? 1.0f : -1.0f);
  460. Vector3 cornerProj = lightRay.Project(cornerPos);
  461. float cornerDistance = (cornerProj - lightPos).Length();
  462. float cornerAngle = (cornerPos - cornerProj).Length() / cornerDistance;
  463. float spotAngle = Min(centerAngle, cornerAngle);
  464. float maxAngle = tanf(fov_ * M_DEGTORAD * 0.5f);
  465. float spotFactor = Min(spotAngle / maxAngle, 1.0f);
  466. // We do not know the actual range attenuation ramp, so take only spot attenuation into account
  467. float att = Max(1.0f - spotFactor * spotFactor, M_EPSILON);
  468. sortValue_ = 1.0f / GetIntensityDivisor(att);
  469. }
  470. break;
  471. case LIGHT_POINT:
  472. {
  473. Vector3 centerPos = box.Center();
  474. Vector3 lightPos = node_->GetWorldPosition();
  475. Vector3 lightDir = (centerPos - lightPos).Normalized();
  476. Ray lightRay(lightPos, lightDir);
  477. float distance = lightRay.HitDistance(box);
  478. float normDistance = distance / range_;
  479. float att = Max(1.0f - normDistance * normDistance, M_EPSILON);
  480. sortValue_ = 1.0f / (Max(color_.SumRGB(), 0.0f) * att + M_EPSILON);
  481. }
  482. break;
  483. }
  484. }
  485. void Light::SetLightQueue(LightBatchQueue* queue)
  486. {
  487. lightQueue_ = queue;
  488. }
  489. }