Light.cpp 24 KB

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