Light.cpp 20 KB

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