Light.cpp 20 KB

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