HslColor.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Globalization;
  4. using System.Runtime.InteropServices;
  5. using Microsoft.Xna.Framework;
  6. namespace MonoGame.Extended
  7. {
  8. /// <summary>
  9. /// Represents a color in the HSL (Hue, Saturation, Lightness) color space.
  10. /// </summary>
  11. /// <remarks>
  12. /// <list type="bullet">
  13. /// <item>Hue (H) represents the color, ranging from 0 to 360 degrees on the color wheel.</item>
  14. /// <item>Saturation (S) represents the intensity of the color, ranging from 0.0 (gray) to 1.0 (full color).</item>
  15. /// <item>Lightness (L) represents the brightness, ranging from 0.0 (black) to 1.0 (white).</item>
  16. /// </list>
  17. /// </remarks>
  18. [StructLayout(LayoutKind.Sequential)]
  19. public struct HslColor : IEquatable<HslColor>, IComparable<HslColor>
  20. {
  21. private float _h;
  22. private float _s;
  23. private float _l;
  24. /// <summary>
  25. /// The hue component value (in degrees) of the color ranging from 0.0 to 360.0.
  26. /// </summary>
  27. public readonly float H => _h;
  28. /// <summary>
  29. /// The saturation component value of the color ranging from 0.0 to 1.0.
  30. /// </summary>
  31. public readonly float S => _s;
  32. /// <summary>
  33. /// The lightness component value of the color ranging from 0.0 to 1.0.
  34. /// </summary>
  35. public readonly float L => _l;
  36. /// <summary>
  37. /// Normalizes a hue value to be within the range [0, 360).
  38. /// Handles negative values by wrapping them around.
  39. /// </summary>
  40. /// <param name="h">The hue value to normalize.</param>
  41. /// <returns>The normalized hue value.</returns>
  42. private static float NormalizeHue(float h)
  43. {
  44. if (h < 0) return h + 360 * ((int)(h / 360) + 1);
  45. return h % 360;
  46. }
  47. /// <summary>
  48. /// Initializes a new instance of the <see cref="HslColor"/> struct with the specified hue, saturation,
  49. /// and lightness component values.
  50. /// </summary>
  51. /// <param name="h">The hue component value (in degrees) from 0.0 to 360.0.</param>
  52. /// <param name="s">The saturation component value from 0.0 to 1.0.</param>
  53. /// <param name="l">The lightness component value from 0.0 to 1.0.</param>
  54. public HslColor(float h, float s, float l)
  55. {
  56. _h = Math.Clamp(h, 0.0f, 360.0f);
  57. _s = Math.Clamp(s, 0.0f, 1.0f);
  58. _l = Math.Clamp(l, 0.0f, 1.0f);
  59. }
  60. /// <summary>
  61. /// Copies the values of this <see cref="HslColor"/> struct to a new instance.
  62. /// </summary>
  63. /// <param name="destination">When this method returns, contains a copy of this <see cref="HslColor"/>.</param>
  64. [Obsolete("Use CopyToRef instead. This will be removed in the next major SemVer release.")]
  65. public readonly void CopyTo(out HslColor destination)
  66. {
  67. destination = new HslColor(H, S, L);
  68. }
  69. /// <summary>
  70. /// Copies the value of this <see cref="HslColor"/> struct to an existing destination.
  71. /// </summary>
  72. /// <param name="destination">A reference to the destination <see cref="HslColor"/> struct where values will be copied to.</param>
  73. /// <remarks>
  74. /// This method directly modifies the internal components of the destination struct for improved performance.
  75. /// Unlike typical operations on immutable structs, this method does not create a new instance but alters
  76. /// the existing one in-place. It should be used only in scenarios where performance is critical.
  77. /// </remarks>
  78. public readonly void CopyToRef(ref HslColor destination)
  79. {
  80. destination._h = _h;
  81. destination._s = _s;
  82. destination._l = _l;
  83. }
  84. /// <summary>
  85. /// Deconstructs this <see cref="HslColor"/> into its hue, saturation, and lightness component values.
  86. /// </summary>
  87. /// <param name="h">When this method returns, contains the hue component value of this <see cref="HslColor"/>.</param>
  88. /// <param name="s">When this method returns, contains the saturation component value of this <see cref="HslColor"/>.</param>
  89. /// <param name="l">When this method returns, contains the lightness component value of this <see cref="HslColor"/>.</param>
  90. [Obsolete("Will be removed in next major SemVer release. Use Deconstruct instead.")]
  91. public readonly void Destructure(out float h, out float s, out float l)
  92. {
  93. h = H;
  94. s = S;
  95. l = L;
  96. }
  97. /// <summary>
  98. /// Deconstructs this <see cref="HslColor"/> into its hue, saturation, and lightness component values.
  99. /// </summary>
  100. /// <param name="h">When this method returns, contains the hue component value of this <see cref="HslColor"/>.</param>
  101. /// <param name="s">When this method returns, contains the saturation component value of this <see cref="HslColor"/>.</param>
  102. /// <param name="l">When this method returns, contains the lightness component value of this <see cref="HslColor"/>.</param>
  103. public readonly void Deconstruct(out float h, out float s, out float l)
  104. {
  105. h = H;
  106. s = S;
  107. l = L;
  108. }
  109. /// <summary>
  110. /// Executes a callback with the components of this <see cref="HslColor"/>.
  111. /// </summary>
  112. /// <param name="callback">The callback to execute.</param>
  113. /// <exception cref="ArgumentNullException">
  114. /// Thrown when <paramref name="callback"/> is <see langword="null"/>.
  115. /// </exception>
  116. public readonly void Match(Action<float, float, float> callback)
  117. {
  118. ArgumentNullException.ThrowIfNull(callback);
  119. callback(H, S, L);
  120. }
  121. /// <summary>
  122. /// Maps the components of this <see cref="HslColor"/> to a new value using the specified mapping function.
  123. /// </summary>
  124. /// <typeparam name="T">The type of the result of the mapping function.</typeparam>
  125. /// <param name="map">The mapping function to apply to the components of this <see cref="HslColor"/>.</param>
  126. /// <returns>
  127. /// The result of applying the mapping function to the components of this <see cref="HslColor"/>.
  128. /// </returns>
  129. /// <exception cref="ArgumentNullException">
  130. /// Thrown when <paramref name="map"/> is <see langword="null"/>.
  131. /// </exception>
  132. public readonly T Map<T>(Func<float, float, float, T> map)
  133. {
  134. ArgumentNullException.ThrowIfNull(map);
  135. return map(H, S, L);
  136. }
  137. /// <summary>
  138. /// Implicitly converts a string to an <see cref="HslColor"/>.
  139. /// </summary>
  140. /// <param name="value">The string to convert.</param>
  141. /// <returns>The <see cref="HslColor"/> represented by the string.</returns>
  142. [Obsolete("Use HslColor.Parse instead to make string parsing explicit and improve code readability. This method will be removed in the next major SemVer release.")]
  143. public static implicit operator HslColor(string value)
  144. {
  145. return Parse(value);
  146. }
  147. /// <inheritdoc/>
  148. /// <remarks>
  149. /// This comparison uses a weighted approach that establishes a hierarchy of importance among the HSL components:
  150. ///
  151. /// <list type="bullet">
  152. /// <item>Hue is the primary sorting factor (weighted by 100)</item>
  153. /// <item>Saturation is the secondary sorting factor (weighted by 10)</item>
  154. /// <item>Lightness is the tertiary sorting factor (weight of 1)</item>
  155. /// </list>
  156. ///
  157. /// This weighting ensures that differences in hue will dominate the comparison result, followed by
  158. /// saturation, and then lightness, creating a sorting order that aligns with the perceptual importance
  159. /// of each component in the HSL color space.
  160. /// </remarks>
  161. public readonly int CompareTo(HslColor other)
  162. {
  163. return _h.CompareTo(other._h) * 100 +
  164. _s.CompareTo(other._s) * 10 +
  165. _l.CompareTo(other._l);
  166. }
  167. /// <inheritdoc/>
  168. public override bool Equals([NotNullWhen(true)] object obj)
  169. {
  170. return obj is HslColor other && Equals(other);
  171. }
  172. /// <inheritdoc/>
  173. public readonly bool Equals(HslColor value)
  174. {
  175. return H.Equals(value.H) &&
  176. L.Equals(value.L) &&
  177. S.Equals(value.S);
  178. }
  179. /// <inheritdoc/>
  180. public override readonly int GetHashCode()
  181. {
  182. return H.GetHashCode() ^
  183. S.GetHashCode() ^
  184. L.GetHashCode();
  185. }
  186. /// <inheritdoc/>
  187. public override readonly string ToString()
  188. {
  189. return string.Format(CultureInfo.InvariantCulture, "H:{0:N1}° S:{1:N1} L:{2:N1}",
  190. H, 100 * S, 100 * L);
  191. }
  192. /// <summary>
  193. /// Parses a string into an <see cref="HslColor"/>.
  194. /// </summary>
  195. /// <param name="s">The string to parse.</param>
  196. /// <returns>The <see cref="HslColor"/> represented by the string.</returns>
  197. /// <remarks>
  198. /// The input string should be in the format "hue,saturation,lightness", where hue is in degrees
  199. /// (optionally followed by the '°' symbol), and saturation and lightness are decimal values.
  200. /// </remarks>
  201. public static HslColor Parse(string s)
  202. {
  203. var hsl = s.Split(',');
  204. var hue = float.Parse(hsl[0].TrimEnd('°'), CultureInfo.InvariantCulture.NumberFormat);
  205. var sat = float.Parse(hsl[1], CultureInfo.InvariantCulture.NumberFormat);
  206. var lig = float.Parse(hsl[2], CultureInfo.InvariantCulture.NumberFormat);
  207. return new HslColor(hue, sat, lig);
  208. }
  209. /// <summary>
  210. /// Determines whether two <see cref="HslColor"/> values are equal.
  211. /// </summary>
  212. /// <param name="x">The first <see cref="HslColor"/> to compare.</param>
  213. /// <param name="y">The second <see cref="HslColor"/> to compare.</param>
  214. /// <returns>
  215. /// <see langword="true"/> if the <see cref="HslColor"/> values are equal; otherwise, <see langword="false"/>.
  216. /// </returns>
  217. public static bool operator ==(HslColor x, HslColor y)
  218. {
  219. return x.Equals(y);
  220. }
  221. /// <summary>
  222. /// Determines whether two <see cref="HslColor"/> values are not equal.
  223. /// </summary>
  224. /// <param name="x">The first <see cref="HslColor"/> to compare.</param>
  225. /// <param name="y">The second <see cref="HslColor"/> to compare.</param>
  226. /// <returns>
  227. /// <see langword="true"/> if the <see cref="HslColor"/> values are not equal; otherwise, <see langword="false"/>.
  228. /// </returns>
  229. public static bool operator !=(HslColor x, HslColor y)
  230. {
  231. return !x.Equals(y);
  232. }
  233. /// <summary>
  234. /// Adds two <see cref="HslColor"/> values together.
  235. /// </summary>
  236. /// <param name="a">The first <see cref="HslColor"/> to add.</param>
  237. /// <param name="b">The second <see cref="HslColor"/> to add.</param>
  238. /// <returns>
  239. /// A new <see cref="HslColor"/> value where the hue, saturation, and light component values are the sum of
  240. /// the components of the two input colors.
  241. /// </returns>
  242. public static HslColor operator +(HslColor a, HslColor b)
  243. {
  244. return new HslColor(
  245. a._h + b._h,
  246. a._s + b._s,
  247. a._l + b._l
  248. );
  249. }
  250. /// <summary>
  251. /// Subtracts one <see cref="HslColor"/> value from another.
  252. /// </summary>
  253. /// <param name="a">The <see cref="HslColor"/> to subtract from.</param>
  254. /// <param name="b">The <see cref="HslColor"/> to subtract.</param>
  255. /// <returns>
  256. /// A new <see cref="HslColor"/> value where the hue, saturation, and light component values are the difference
  257. /// of the components of the two input colors.
  258. /// </returns>
  259. public static HslColor operator -(HslColor a, HslColor b)
  260. {
  261. return new HslColor(
  262. a._h - b._h,
  263. a._s - b._s,
  264. a._l - b._l
  265. );
  266. }
  267. /// <summary>
  268. /// Linearly interpolates between two <see cref="HslColor"/> values.
  269. /// </summary>
  270. /// <param name="c1">The first <see cref="HslColor"/>.</param>
  271. /// <param name="c2">The second <see cref="HslColor"/>.</param>
  272. /// <param name="t">The interpolation factor. A value of 0 returns <paramref name="c1"/>, a value of 1 returns <paramref name="c2"/>.</param>
  273. /// <returns>The interpolated <see cref="HslColor"/>.</returns>
  274. public static HslColor Lerp(HslColor c1, HslColor c2, float t)
  275. {
  276. // loop around if c2.H < c1.HF
  277. var h2 = c2.H >= c1.H ? c2.H : c2.H + 360;
  278. return new HslColor(
  279. c1.H + t * (h2 - c1.H),
  280. c1.S + t * (c2.S - c1.S),
  281. c1.L + t * (c2.L - c1.L));
  282. }
  283. /// <summary>
  284. /// Convers a <see cref="HslColor"/> value to a <see cref="Microsoft.Xna.Framework.Color"/> value.
  285. /// </summary>
  286. /// <param name="hsl">The <see cref="HslColor"/> value to convert.</param>
  287. /// <returns>
  288. /// A <see cref="Microsoft.Xna.Framework.Color"/> value representing the RGB equivalent of the specified
  289. /// <see cref="HslColor"/> value.
  290. /// </returns>
  291. public static Color ToRgb(HslColor hsl)
  292. {
  293. float h = hsl._h;
  294. float s = hsl._s;
  295. float l = hsl._l;
  296. if (s < MathExtended.MachineEpsilon)
  297. {
  298. return new Color(l, l, l);
  299. }
  300. if (l <= MathExtended.MachineEpsilon)
  301. {
  302. return Color.Black;
  303. }
  304. h /= 360.0f;
  305. float max = l < 0.5f ?
  306. l * (1 + s) :
  307. l + s - l * s;
  308. float min = 2.0f * l - max;
  309. float r = RgbFromHue(min, max, h + 0.3333333f);
  310. float g = RgbFromHue(min, max, h);
  311. float b = RgbFromHue(min, max, h - 0.3333333f);
  312. return new Color(r, g, b);
  313. }
  314. private static float RgbFromHue(float min, float max, float hue)
  315. {
  316. hue = (hue + 1.0f) % 1.0f;
  317. if (hue * 6.0f < 1.0f)
  318. {
  319. return min + (max - min) * 6.0f * hue;
  320. }
  321. if (hue * 2.0f < 1.0f)
  322. {
  323. return max;
  324. }
  325. if (hue * 3.0f < 2.0f)
  326. {
  327. return min + (max - min) * (2.0f / 3.0f - hue) * 6.0f;
  328. }
  329. return min;
  330. }
  331. /// <summary>
  332. /// Converts an RGB color to an HSL color.
  333. /// </summary>
  334. /// <param name="color">The RGB color to convert.</param>
  335. /// <returns>The equivalent HSL color.</returns>
  336. public static HslColor FromRgb(Color color)
  337. {
  338. float r = color.R / 255f;
  339. float g = color.G / 255f;
  340. float b = color.B / 255f;
  341. float max = MathF.Max(r, MathF.Max(g, b));
  342. float min = MathF.Min(r, MathF.Min(g, b));
  343. float delta = max - min;
  344. float h = 0.0f;
  345. float s = 0.0f;
  346. float l = (max + min) * 0.5f;
  347. if (MathF.Abs(delta) < float.Epsilon)
  348. {
  349. return new HslColor(h, s, l);
  350. }
  351. if (MathF.Abs(r - max) < float.Epsilon)
  352. {
  353. h = (g - b) / delta;
  354. }
  355. else if (MathF.Abs(g - max) < float.Epsilon)
  356. {
  357. h = (b - r) / delta + 2.0f;
  358. }
  359. else if (MathF.Abs(b - max) < float.Epsilon)
  360. {
  361. h = (r - g) / delta + 4.0f;
  362. }
  363. h *= 60.0f;
  364. h = NormalizeHue(h);
  365. if (l <= 0.5f)
  366. {
  367. s = delta / (max + min);
  368. }
  369. else
  370. {
  371. s = delta / (2.0f - max - min);
  372. }
  373. return new HslColor(h, s, l);
  374. }
  375. }
  376. }