Light.cpp 21 KB

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