Light.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. //
  2. // Copyright (c) 2008-2020 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. /// \file
  23. #pragma once
  24. #include "../Math/Color.h"
  25. #include "../Graphics/Drawable.h"
  26. #include "../Math/Frustum.h"
  27. #include "../Graphics/Texture.h"
  28. namespace Urho3D
  29. {
  30. class Camera;
  31. struct LightBatchQueue;
  32. /// %Light types.
  33. enum LightType
  34. {
  35. LIGHT_DIRECTIONAL = 0,
  36. LIGHT_SPOT,
  37. LIGHT_POINT
  38. };
  39. static const float SHADOW_MIN_QUANTIZE = 0.1f;
  40. static const float SHADOW_MIN_VIEW = 1.0f;
  41. static const int MAX_LIGHT_SPLITS = 6;
  42. #ifdef DESKTOP_GRAPHICS
  43. static const unsigned MAX_CASCADE_SPLITS = 4;
  44. #else
  45. static const unsigned MAX_CASCADE_SPLITS = 1;
  46. #endif
  47. /// Depth bias parameters. Used both by lights (for shadow mapping) and materials.
  48. struct URHO3D_API BiasParameters
  49. {
  50. /// Construct undefined.
  51. BiasParameters() = default;
  52. /// Construct with initial values.
  53. BiasParameters(float constantBias, float slopeScaledBias, float normalOffset = 0.0f) :
  54. constantBias_(constantBias),
  55. slopeScaledBias_(slopeScaledBias),
  56. normalOffset_(normalOffset)
  57. {
  58. }
  59. /// Validate parameters.
  60. void Validate();
  61. /// Constant bias.
  62. float constantBias_;
  63. /// Slope scaled bias.
  64. float slopeScaledBias_;
  65. /// Normal offset multiplier.
  66. float normalOffset_;
  67. };
  68. /// Cascaded shadow map parameters.
  69. struct URHO3D_API CascadeParameters
  70. {
  71. /// Construct undefined.
  72. CascadeParameters() = default;
  73. /// Construct with initial values.
  74. CascadeParameters(float split1, float split2, float split3, float split4, float fadeStart, float biasAutoAdjust = 1.0f) :
  75. fadeStart_(fadeStart),
  76. biasAutoAdjust_(biasAutoAdjust)
  77. {
  78. splits_[0] = split1;
  79. splits_[1] = split2;
  80. splits_[2] = split3;
  81. splits_[3] = split4;
  82. }
  83. /// Validate parameters.
  84. void Validate();
  85. /// Return shadow maximum range.
  86. float GetShadowRange() const
  87. {
  88. float ret = 0.0f;
  89. for (unsigned i = 0; i < MAX_CASCADE_SPLITS; ++i)
  90. ret = Max(ret, splits_[i]);
  91. return ret;
  92. }
  93. /// Far clip values of the splits.
  94. Vector4 splits_;
  95. /// The point relative to the total shadow range where shadow fade begins (0.0 - 1.0).
  96. float fadeStart_{};
  97. /// Automatic depth bias adjustment strength.
  98. float biasAutoAdjust_{};
  99. };
  100. /// Shadow map focusing parameters.
  101. struct URHO3D_API FocusParameters
  102. {
  103. /// Construct undefined.
  104. FocusParameters() = default;
  105. /// Construct with initial values.
  106. FocusParameters(bool focus, bool nonUniform, bool autoSize, float quantize, float minView) :
  107. focus_(focus),
  108. nonUniform_(nonUniform),
  109. autoSize_(autoSize),
  110. quantize_(quantize),
  111. minView_(minView)
  112. {
  113. }
  114. /// Validate parameters.
  115. void Validate();
  116. /// Focus flag.
  117. bool focus_;
  118. /// Non-uniform focusing flag.
  119. bool nonUniform_;
  120. /// Auto-size (reduce resolution when far away) flag.
  121. bool autoSize_;
  122. /// Focus quantization.
  123. float quantize_;
  124. /// Minimum view size.
  125. float minView_;
  126. };
  127. /// %Light component.
  128. class URHO3D_API Light : public Drawable
  129. {
  130. URHO3D_OBJECT(Light, Drawable);
  131. public:
  132. /// Construct.
  133. explicit Light(Context* context);
  134. /// Destruct.
  135. ~Light() override;
  136. /// Register object factory. Drawable must be registered first.
  137. static void RegisterObject(Context* context);
  138. /// Process octree raycast. May be called from a worker thread.
  139. void ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results) override;
  140. /// Calculate distance and prepare batches for rendering. May be called from worker thread(s), possibly re-entrantly.
  141. void UpdateBatches(const FrameInfo& frame) override;
  142. /// Visualize the component as debug geometry.
  143. void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
  144. /// Set light type.
  145. void SetLightType(LightType type);
  146. /// Set vertex lighting mode.
  147. void SetPerVertex(bool enable);
  148. /// Set color.
  149. void SetColor(const Color& color);
  150. /// Set temperature of the light in Kelvin. Modulates the light color when "use physical values" is enabled.
  151. void SetTemperature(float temperature);
  152. /// Set area light radius. Greater than zero activates area light mode. Works only with PBR shaders.
  153. void SetRadius(float radius);
  154. /// Set tube area light length. Works only with PBR shaders.
  155. void SetLength(float length);
  156. /// Set use physical light values.
  157. void SetUsePhysicalValues(bool enable);
  158. /// Set specular intensity. Zero disables specular calculations.
  159. void SetSpecularIntensity(float intensity);
  160. /// Set light brightness multiplier. Both the color and specular intensity are multiplied with this. When "use physical values" is enabled, the value is specified in lumens.
  161. void SetBrightness(float brightness);
  162. /// Set range.
  163. void SetRange(float range);
  164. /// Set spotlight field of view.
  165. void SetFov(float fov);
  166. /// Set spotlight aspect ratio.
  167. void SetAspectRatio(float aspectRatio);
  168. /// Set fade out start distance.
  169. void SetFadeDistance(float distance);
  170. /// Set shadow fade out start distance. Only has effect if shadow distance is also non-zero.
  171. void SetShadowFadeDistance(float distance);
  172. /// Set shadow depth bias parameters.
  173. void SetShadowBias(const BiasParameters& parameters);
  174. /// Set directional light cascaded shadow parameters.
  175. void SetShadowCascade(const CascadeParameters& parameters);
  176. /// Set shadow map focusing parameters.
  177. void SetShadowFocus(const FocusParameters& parameters);
  178. /// Set light intensity in shadow between 0.0 - 1.0. 0.0 (the default) gives fully dark shadows.
  179. void SetShadowIntensity(float intensity);
  180. /// Set shadow resolution between 0.25 - 1.0. Determines the shadow map to use.
  181. void SetShadowResolution(float resolution);
  182. /// Set shadow camera near/far clip distance ratio for spot and point lights. Does not affect directional lights, since they are orthographic and have near clip 0.
  183. void SetShadowNearFarRatio(float nearFarRatio);
  184. /// Set maximum shadow extrusion for directional lights. The actual extrusion will be the smaller of this and camera far clip. Default 1000.
  185. void SetShadowMaxExtrusion(float extrusion);
  186. /// Set range attenuation texture.
  187. void SetRampTexture(Texture* texture);
  188. /// Set spotlight attenuation texture.
  189. void SetShapeTexture(Texture* texture);
  190. /// Return light type.
  191. LightType GetLightType() const { return lightType_; }
  192. /// Return vertex lighting mode.
  193. bool GetPerVertex() const { return perVertex_; }
  194. /// Return color.
  195. const Color& GetColor() const { return color_; }
  196. /// Return the temperature of the light in Kelvin.
  197. float GetTemperature() const { return temperature_; }
  198. /// Return area light mode radius. Works only with PBR shaders.
  199. float GetRadius() const { return lightRad_; }
  200. /// Return area tube light length. Works only with PBR shaders.
  201. float GetLength() const { return lightLength_; }
  202. /// Return if light uses temperature and brightness in lumens.
  203. bool GetUsePhysicalValues() const { return usePhysicalValues_; }
  204. /// Return the color value of the temperature in Kelvin.
  205. Color GetColorFromTemperature() const;
  206. /// Return specular intensity.
  207. float GetSpecularIntensity() const { return specularIntensity_; }
  208. /// Return brightness multiplier. Specified in lumens when "use physical values" is enabled.
  209. float GetBrightness() const { return brightness_; }
  210. /// Return effective color, multiplied by brightness and affected by temperature when "use physical values" is enabled. Alpha is always 1 so that can compare against the default black color to detect a light with no effect.
  211. Color GetEffectiveColor() const;
  212. /// Return effective specular intensity, multiplied by absolute value of brightness.
  213. float GetEffectiveSpecularIntensity() const { return specularIntensity_ * Abs(brightness_); }
  214. /// Return range.
  215. float GetRange() const { return range_; }
  216. /// Return spotlight field of view.
  217. float GetFov() const { return fov_; }
  218. /// Return spotlight aspect ratio.
  219. float GetAspectRatio() const { return aspectRatio_; }
  220. /// Return fade start distance.
  221. float GetFadeDistance() const { return fadeDistance_; }
  222. /// Return shadow fade start distance.
  223. float GetShadowFadeDistance() const { return shadowFadeDistance_; }
  224. /// Return shadow depth bias parameters.
  225. const BiasParameters& GetShadowBias() const { return shadowBias_; }
  226. /// Return directional light cascaded shadow parameters.
  227. const CascadeParameters& GetShadowCascade() const { return shadowCascade_; }
  228. /// Return shadow map focus parameters.
  229. const FocusParameters& GetShadowFocus() const { return shadowFocus_; }
  230. /// Return light intensity in shadow.
  231. float GetShadowIntensity() const { return shadowIntensity_; }
  232. /// Return shadow resolution.
  233. float GetShadowResolution() const { return shadowResolution_; }
  234. /// Return shadow camera near/far clip distance ratio.
  235. float GetShadowNearFarRatio() const { return shadowNearFarRatio_; }
  236. /// Return maximum shadow extrusion distance for directional lights.
  237. float GetShadowMaxExtrusion() const { return shadowMaxExtrusion_; }
  238. /// Return range attenuation texture.
  239. Texture* GetRampTexture() const { return rampTexture_; }
  240. /// Return spotlight attenuation texture.
  241. Texture* GetShapeTexture() const { return shapeTexture_; }
  242. /// Return spotlight frustum.
  243. Frustum GetFrustum() const;
  244. /// Return spotlight frustum in the specified view space.
  245. Frustum GetViewSpaceFrustum(const Matrix3x4& view) const;
  246. /// Return number of shadow map cascade splits for a directional light, considering also graphics API limitations.
  247. int GetNumShadowSplits() const;
  248. /// Return whether light has negative (darkening) color.
  249. bool IsNegative() const { return GetEffectiveColor().SumRGB() < 0.0f; }
  250. /// Set sort value based on intensity and view distance.
  251. void SetIntensitySortValue(float distance);
  252. /// Set sort value based on overall intensity over a bounding box.
  253. void SetIntensitySortValue(const BoundingBox& box);
  254. /// Set light queue used for this light. Called by View.
  255. void SetLightQueue(LightBatchQueue* queue);
  256. /// Return light volume model transform.
  257. const Matrix3x4& GetVolumeTransform(Camera* camera);
  258. /// Return light queue. Called by View.
  259. LightBatchQueue* GetLightQueue() const { return lightQueue_; }
  260. /// Return a divisor value based on intensity for calculating the sort value.
  261. float GetIntensityDivisor(float attenuation = 1.0f) const
  262. {
  263. return Max(GetEffectiveColor().SumRGB(), 0.0f) * attenuation + M_EPSILON;
  264. }
  265. /// Set ramp texture attribute.
  266. void SetRampTextureAttr(const ResourceRef& value);
  267. /// Set shape texture attribute.
  268. void SetShapeTextureAttr(const ResourceRef& value);
  269. /// Return ramp texture attribute.
  270. ResourceRef GetRampTextureAttr() const;
  271. /// Return shape texture attribute.
  272. ResourceRef GetShapeTextureAttr() const;
  273. /// Return a transform for deferred fullscreen quad (directional light) rendering.
  274. static Matrix3x4 GetFullscreenQuadTransform(Camera* camera);
  275. protected:
  276. /// Recalculate the world-space bounding box.
  277. void OnWorldBoundingBoxUpdate() override;
  278. private:
  279. /// Validate shadow focus.
  280. void ValidateShadowFocus() { shadowFocus_.Validate(); }
  281. /// Validate shadow cascade.
  282. void ValidateShadowCascade() { shadowCascade_.Validate(); }
  283. /// Validate shadow bias.
  284. void ValidateShadowBias() { shadowBias_.Validate(); }
  285. /// Light type.
  286. LightType lightType_;
  287. /// Color.
  288. Color color_;
  289. /// Light temperature.
  290. float temperature_;
  291. /// Radius of the light source. If above 0 it will turn the light into an area light. Works only with PBR shaders.
  292. float lightRad_;
  293. /// Length of the light source. If above 0 and radius is above 0 it will create a tube light. Works only with PBR shaders.
  294. float lightLength_;
  295. /// Shadow depth bias parameters.
  296. BiasParameters shadowBias_;
  297. /// Directional light cascaded shadow parameters.
  298. CascadeParameters shadowCascade_;
  299. /// Shadow map focus parameters.
  300. FocusParameters shadowFocus_;
  301. /// Custom world transform for the light volume.
  302. Matrix3x4 volumeTransform_;
  303. /// Range attenuation texture.
  304. SharedPtr<Texture> rampTexture_;
  305. /// Spotlight attenuation texture.
  306. SharedPtr<Texture> shapeTexture_;
  307. /// Light queue.
  308. LightBatchQueue* lightQueue_;
  309. /// Specular intensity.
  310. float specularIntensity_;
  311. /// Brightness multiplier.
  312. float brightness_;
  313. /// Range.
  314. float range_;
  315. /// Spotlight field of view.
  316. float fov_;
  317. /// Spotlight aspect ratio.
  318. float aspectRatio_;
  319. /// Fade start distance.
  320. float fadeDistance_;
  321. /// Shadow fade start distance.
  322. float shadowFadeDistance_;
  323. /// Light intensity in shadow.
  324. float shadowIntensity_;
  325. /// Shadow resolution.
  326. float shadowResolution_;
  327. /// Shadow camera near/far clip distance ratio.
  328. float shadowNearFarRatio_;
  329. /// Directional shadow max. extrusion distance.
  330. float shadowMaxExtrusion_;
  331. /// Per-vertex lighting flag.
  332. bool perVertex_;
  333. /// Use physical light values flag.
  334. bool usePhysicalValues_;
  335. };
  336. inline bool CompareLights(Light* lhs, Light* rhs)
  337. {
  338. // When sorting lights, give priority to per-vertex lights, so that vertex lit base pass can be evaluated first
  339. if (lhs->GetPerVertex() != rhs->GetPerVertex())
  340. return lhs->GetPerVertex();
  341. else
  342. return lhs->GetSortValue() < rhs->GetSortValue();
  343. }
  344. }