PropertyParserColour.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. #include "PropertyParserColour.h"
  2. #include "ControlledLifetimeResource.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <string.h>
  6. #include <utility>
  7. namespace Rml {
  8. // Helper function for hsl->rgb conversion.
  9. static float HSL_f(float h, float s, float l, float n)
  10. {
  11. float k = std::fmod((n + h * (1.0f / 30.0f)), 12.0f);
  12. float a = s * std::min(l, 1.0f - l);
  13. return l - a * std::max(-1.0f, std::min({k - 3.0f, 9.0f - k, 1.0f}));
  14. }
  15. // Reference: https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative
  16. static void HSLAToRGBA(Array<float, 4>& vals)
  17. {
  18. if (vals[1] == 0.0f)
  19. {
  20. vals[0] = vals[1] = vals[2];
  21. }
  22. else
  23. {
  24. float h = std::fmod(vals[0], 360.0f);
  25. if (h < 0)
  26. h += 360.0f;
  27. float s = vals[1];
  28. float l = vals[2];
  29. vals[0] = HSL_f(h, s, l, 0.0f);
  30. vals[1] = HSL_f(h, s, l, 8.0f);
  31. vals[2] = HSL_f(h, s, l, 4.0f);
  32. }
  33. }
  34. // Reference: https://en.wikipedia.org/wiki/SRGB#Definition
  35. static float InverseSRGBNonlinearTransfer(float channel)
  36. {
  37. return channel > 0.0031308f ? 1.055f * std::pow(channel, 1.0f / 2.4f) - 0.055f : 12.92f * channel;
  38. }
  39. // Reference: https://en.wikipedia.org/wiki/CIELAB_color_space#Converting_between_CIELAB_and_CIE_XYZ_coordinates
  40. static void CIELABToRGBA(Array<float, 4>& values)
  41. {
  42. float y_double_prime = (values[0] + 16.0f) / 116.0f;
  43. float x_double_prime = (values[1] / 500.0f) + y_double_prime;
  44. float z_double_prime = y_double_prime - (values[2] / 200.0f);
  45. float x_prime = (x_double_prime * x_double_prime * x_double_prime) > 0.008856f ? (x_double_prime * x_double_prime * x_double_prime)
  46. : (x_double_prime - (16.0f / 116.0f)) / 7.787f;
  47. float y_prime = (y_double_prime * y_double_prime * y_double_prime) > 0.008856f ? (y_double_prime * y_double_prime * y_double_prime)
  48. : (y_double_prime - (16.0f / 116.0f)) / 7.787f;
  49. float z_prime = (z_double_prime * z_double_prime * z_double_prime) > 0.008856f ? (z_double_prime * z_double_prime * z_double_prime)
  50. : (z_double_prime - (16.0f / 116.0f)) / 7.787f;
  51. static const Vector3f illuminant_d65_multiplicands(0.95047f, 1.0f, 1.08883f);
  52. float x = x_prime * illuminant_d65_multiplicands.x;
  53. float y = y_prime * illuminant_d65_multiplicands.y;
  54. float z = z_prime * illuminant_d65_multiplicands.z;
  55. static constexpr Array<Array<float, 3>, 3> xyz_to_srgb_matrix{
  56. Array<float, 3>{+3.2404548f, -1.5371389f, -0.4985315f},
  57. Array<float, 3>{-0.9692664f, +1.8760109f, +0.0415561f},
  58. Array<float, 3>{+0.0556434f, -0.2040259f, +1.0572252f},
  59. };
  60. float r = xyz_to_srgb_matrix[0][0] * x + xyz_to_srgb_matrix[0][1] * y + xyz_to_srgb_matrix[0][2] * z;
  61. float g = xyz_to_srgb_matrix[1][0] * x + xyz_to_srgb_matrix[1][1] * y + xyz_to_srgb_matrix[1][2] * z;
  62. float b = xyz_to_srgb_matrix[2][0] * x + xyz_to_srgb_matrix[2][1] * y + xyz_to_srgb_matrix[2][2] * z;
  63. values[0] = Math::Clamp(InverseSRGBNonlinearTransfer(r), 0.0f, 1.0f);
  64. values[1] = Math::Clamp(InverseSRGBNonlinearTransfer(g), 0.0f, 1.0f);
  65. values[2] = Math::Clamp(InverseSRGBNonlinearTransfer(b), 0.0f, 1.0f);
  66. }
  67. // References: https://en.wikipedia.org/wiki/Oklab_color_space#Conversions_between_color_spaces and https://bottosson.github.io/posts/oklab/
  68. static void OklabToRGBA(Array<float, 4>& values)
  69. {
  70. static constexpr Array<Array<float, 3>, 3> oklab_to_lms_prime_matrix{
  71. Array<float, 3>{+1.0f, +0.3963377774f, +0.2158037573f},
  72. Array<float, 3>{+1.0f, -0.1055613458f, -0.0638541728f},
  73. Array<float, 3>{+1.0f, -0.0894841775f, -1.2914855480f},
  74. };
  75. float lightness = values[0];
  76. float a_axis = values[1];
  77. float b_axis = values[2];
  78. float l_prime = oklab_to_lms_prime_matrix[0][0] * lightness + oklab_to_lms_prime_matrix[0][1] * a_axis + oklab_to_lms_prime_matrix[0][2] * b_axis;
  79. float m_prime = oklab_to_lms_prime_matrix[1][0] * lightness + oklab_to_lms_prime_matrix[1][1] * a_axis + oklab_to_lms_prime_matrix[1][2] * b_axis;
  80. float s_prime = oklab_to_lms_prime_matrix[2][0] * lightness + oklab_to_lms_prime_matrix[2][1] * a_axis + oklab_to_lms_prime_matrix[2][2] * b_axis;
  81. float l = l_prime * l_prime * l_prime;
  82. float m = m_prime * m_prime * m_prime;
  83. float s = s_prime * s_prime * s_prime;
  84. static constexpr Array<Array<float, 3>, 3> lms_to_srgb_matrix{
  85. Array<float, 3>{+4.0767416621f, -3.3077115913f, +0.2309699292f},
  86. Array<float, 3>{-1.2684380046f, +2.6097574011f, -0.3413193965f},
  87. Array<float, 3>{-0.0041960863f, -0.7034186147f, +1.7076147010f},
  88. };
  89. float r = lms_to_srgb_matrix[0][0] * l + lms_to_srgb_matrix[0][1] * m + lms_to_srgb_matrix[0][2] * s;
  90. float g = lms_to_srgb_matrix[1][0] * l + lms_to_srgb_matrix[1][1] * m + lms_to_srgb_matrix[1][2] * s;
  91. float b = lms_to_srgb_matrix[2][0] * l + lms_to_srgb_matrix[2][1] * m + lms_to_srgb_matrix[2][2] * s;
  92. values[0] = Math::Clamp(InverseSRGBNonlinearTransfer(r), 0.0f, 1.0f);
  93. values[1] = Math::Clamp(InverseSRGBNonlinearTransfer(g), 0.0f, 1.0f);
  94. values[2] = Math::Clamp(InverseSRGBNonlinearTransfer(b), 0.0f, 1.0f);
  95. }
  96. struct PropertyParserColourData {
  97. const UnorderedMap<String, Colourb> html_colours = {
  98. {"black", Colourb(0, 0, 0)},
  99. {"silver", Colourb(192, 192, 192)},
  100. {"gray", Colourb(128, 128, 128)},
  101. {"grey", Colourb(128, 128, 128)},
  102. {"white", Colourb(255, 255, 255)},
  103. {"maroon", Colourb(128, 0, 0)},
  104. {"red", Colourb(255, 0, 0)},
  105. {"orange", Colourb(255, 165, 0)},
  106. {"purple", Colourb(128, 0, 128)},
  107. {"fuchsia", Colourb(255, 0, 255)},
  108. {"green", Colourb(0, 128, 0)},
  109. {"lime", Colourb(0, 255, 0)},
  110. {"olive", Colourb(128, 128, 0)},
  111. {"yellow", Colourb(255, 255, 0)},
  112. {"navy", Colourb(0, 0, 128)},
  113. {"blue", Colourb(0, 0, 255)},
  114. {"teal", Colourb(0, 128, 128)},
  115. {"aqua", Colourb(0, 255, 255)},
  116. {"transparent", Colourb(0, 0, 0, 0)},
  117. };
  118. };
  119. ControlledLifetimeResource<PropertyParserColourData> PropertyParserColour::parser_data;
  120. void PropertyParserColour::Initialize()
  121. {
  122. parser_data.Initialize();
  123. }
  124. void PropertyParserColour::Shutdown()
  125. {
  126. parser_data.Shutdown();
  127. }
  128. PropertyParserColour::PropertyParserColour() {}
  129. PropertyParserColour::~PropertyParserColour() {}
  130. bool PropertyParserColour::ParseValue(Property& property, const String& value, const ParameterMap& /*parameters*/) const
  131. {
  132. Colourb colour;
  133. if (!ParseColour(colour, value))
  134. return false;
  135. property.value = Variant(colour);
  136. property.unit = Unit::COLOUR;
  137. return true;
  138. }
  139. bool PropertyParserColour::ParseColour(Colourb& colour, const String& value)
  140. {
  141. if (value.empty())
  142. return false;
  143. colour = {};
  144. if (value[0] == '#')
  145. {
  146. if (!ParseHexColour(colour, value))
  147. return false;
  148. }
  149. else if (value.substr(0, 3) == "rgb")
  150. {
  151. if (!ParseRGBColour(colour, value))
  152. return false;
  153. }
  154. else if (value.substr(0, 3) == "hsl")
  155. {
  156. if (!ParseHSLColour(colour, value))
  157. return false;
  158. }
  159. else if (value.substr(0, 3) == "lab" || value.substr(0, 3) == "lch")
  160. {
  161. if (!ParseCIELABColour(colour, value))
  162. return false;
  163. }
  164. else if (value.substr(0, 5) == "oklab" || value.substr(0, 5) == "oklch")
  165. {
  166. if (!ParseOklabColour(colour, value))
  167. return false;
  168. }
  169. else
  170. {
  171. // Check for the specification of an HTML colour.
  172. auto it = parser_data->html_colours.find(StringUtilities::ToLower(value));
  173. if (it == parser_data->html_colours.end())
  174. return false;
  175. else
  176. colour = it->second;
  177. }
  178. return true;
  179. }
  180. bool PropertyParserColour::ParseHexColour(Colourb& colour, const String& value)
  181. {
  182. char hex_values[4][2] = {{'f', 'f'}, {'f', 'f'}, {'f', 'f'}, {'f', 'f'}};
  183. switch (value.size())
  184. {
  185. // Single hex digit per channel, RGB and alpha.
  186. case 5:
  187. hex_values[3][0] = hex_values[3][1] = value[4];
  188. //-fallthrough
  189. // Single hex digit per channel, RGB only.
  190. case 4:
  191. hex_values[0][0] = hex_values[0][1] = value[1];
  192. hex_values[1][0] = hex_values[1][1] = value[2];
  193. hex_values[2][0] = hex_values[2][1] = value[3];
  194. break;
  195. // Two hex digits per channel, RGB and alpha.
  196. case 9:
  197. hex_values[3][0] = value[7];
  198. hex_values[3][1] = value[8];
  199. //-fallthrough
  200. // Two hex digits per channel, RGB only.
  201. case 7: memcpy(hex_values, &value.c_str()[1], sizeof(char) * 6); break;
  202. default: return false;
  203. }
  204. // Parse each of the colour elements.
  205. for (int i = 0; i < 4; i++)
  206. {
  207. int tens = Math::HexToDecimal(hex_values[i][0]);
  208. int ones = Math::HexToDecimal(hex_values[i][1]);
  209. if (tens == -1 || ones == -1)
  210. return false;
  211. colour[i] = (byte)(tens * 16 + ones);
  212. }
  213. return true;
  214. }
  215. bool PropertyParserColour::ParseRGBColour(Colourb& colour, const String& value)
  216. {
  217. StringList values;
  218. values.reserve(4);
  219. if (!GetColourFunctionValues(values, value, true))
  220. return false;
  221. // Check if we're parsing an 'rgba' or 'rgb' colour declaration.
  222. if (value.size() > 3 && value[3] == 'a')
  223. {
  224. if (values.size() != 4)
  225. return false;
  226. }
  227. else
  228. {
  229. if (values.size() != 3)
  230. return false;
  231. values.push_back("255");
  232. }
  233. // Parse the RGBA values.
  234. for (int i = 0; i < 4; ++i)
  235. {
  236. int component;
  237. // We're parsing a percentage value.
  238. if (values[i].size() > 0 && values[i][values[i].size() - 1] == '%')
  239. component = int((float)atof(values[i].substr(0, values[i].size() - 1).c_str()) * (255.0f / 100.0f));
  240. // We're parsing a 0 -> 255 integer value.
  241. else
  242. component = atoi(values[i].c_str());
  243. colour[i] = (byte)(Math::Clamp(component, 0, 255));
  244. }
  245. return true;
  246. }
  247. bool PropertyParserColour::ParseHSLColour(Colourb& colour, const String& value)
  248. {
  249. StringList values;
  250. values.reserve(4);
  251. if (!GetColourFunctionValues(values, value, true))
  252. return false;
  253. // Check if we're parsing an 'hsla' or 'hsl' colour declaration.
  254. if (value.size() > 3 && value[3] == 'a')
  255. {
  256. if (values.size() != 4)
  257. return false;
  258. }
  259. else
  260. {
  261. if (values.size() != 3)
  262. return false;
  263. values.push_back("1.0");
  264. }
  265. // Parse the HSLA values.
  266. Array<float, 4> vals;
  267. // H is a number in degrees, A is a number between 0.0 and 1.0.
  268. for (int i : {0, 3})
  269. vals[i] = (float)atof(values[i].c_str());
  270. // S and L are percentage values.
  271. for (int i : {1, 2})
  272. if (values[i].size() > 0 && values[i][values[i].size() - 1] == '%')
  273. vals[i] = (float)atof(values[i].substr(0, values[i].size() - 1).c_str()) * (1.0f / 100.0f);
  274. else
  275. return false;
  276. HSLAToRGBA(vals);
  277. for (int i = 0; i < 4; ++i)
  278. colour[i] = (byte)(Math::Clamp((int)(vals[i] * 255.0f), 0, 255));
  279. return true;
  280. }
  281. bool PropertyParserColour::ParseCIELABColour(Colourb& colour, const String& value)
  282. {
  283. StringList values;
  284. values.reserve(5);
  285. if (!GetColourFunctionValues(values, value, false))
  286. return false;
  287. // Check if we have an alpha component.
  288. if (values.size() == 5)
  289. {
  290. if (values[3] != "/")
  291. return false;
  292. values[3] = std::move(values[4]);
  293. values.pop_back();
  294. }
  295. else
  296. {
  297. if (values.size() != 3)
  298. return false;
  299. values.push_back("1.0");
  300. }
  301. Array<float, 4> lab_values;
  302. // Parse lightness and alpha (same for both lab and lch).
  303. for (int i : {0, 3})
  304. {
  305. // Value can either be 'none' (representing 0.0), a percentage between 0% and 100%, or a number (between 0.0 and 100.0 for lightness and between 0.0 and 1.0 for alpha).
  306. if (values[i] == "none")
  307. lab_values[i] = 0.0f;
  308. else if (values[i][values[i].size() - 1] == '%')
  309. {
  310. lab_values[i] = (float)atof(values[i].substr(0, values[i].size() - 1).c_str());
  311. if (i == 3)
  312. lab_values[i] /= 100.0f;
  313. }
  314. else
  315. lab_values[i] = (float)atof(values[i].c_str());
  316. lab_values[i] = Math::Clamp(lab_values[i], 0.0f, i == 0 ? 100.0f : 1.0f);
  317. }
  318. // Determine if colour is in CIELAB or CIELCh space.
  319. if (value.substr(0, 3) == "lab")
  320. {
  321. // Parse A-axis (green-to-red) and B-axis (blue-to-yellow).
  322. for (int i : {1, 2})
  323. {
  324. // Value can either be 'none' (representing 0.0), a percentage between -100% and +100% (representing -125.0 to +125.0), or a number.
  325. if (values[i] == "none")
  326. lab_values[i] = 0.0f;
  327. else if (values[i][values[i].size() - 1] == '%')
  328. {
  329. static constexpr float cielab_axis_percentage_bound = 125.0f;
  330. lab_values[i] = (float)atof(values[i].substr(0, values[i].size() - 1).c_str()) / 100.0f * cielab_axis_percentage_bound;
  331. }
  332. else
  333. lab_values[i] = (float)atof(values[i].c_str());
  334. // Whilst the axis values are theoretically unbounded, in practice, they only exist between -160.0 and +160.0.
  335. static constexpr float cielab_axis_bound_limit = 160.0f;
  336. lab_values[i] = Math::Clamp(lab_values[i], -cielab_axis_bound_limit, +cielab_axis_bound_limit);
  337. }
  338. }
  339. else
  340. {
  341. // Parse chroma; value can either be 'none' (representing 0.0), a percentage between 0% and 100% (representing 0.0 to 150.0), or a number.
  342. float chroma = 0.0f;
  343. if (values[1] == "none")
  344. chroma = 0.0f;
  345. else if (values[1][values[1].size() - 1] == '%')
  346. {
  347. static constexpr float cielch_maximum_percentage_chroma = 150.0f;
  348. chroma = (float)atof(values[1].substr(0, values[1].size() - 1).c_str()) / 100.0f * cielch_maximum_percentage_chroma;
  349. }
  350. else
  351. chroma = (float)atof(values[1].c_str());
  352. // Whilst the chroma is theoretically unbounded, in practice, it does not exceed 230.0.
  353. static constexpr float cielch_maximum_chroma = 230.0f;
  354. chroma = Math::Clamp(chroma, 0.0f, cielch_maximum_chroma);
  355. // Parse hue; value can either be 'none' (representing 0.0), or an angle.
  356. float hue = 0.0f;
  357. if (values[2] == "none")
  358. hue = 0.0f;
  359. else
  360. hue = (float)atof(values[2].c_str());
  361. // Convert LCh polar coordinates to LAB Cartesian coordinates.
  362. lab_values[1] = chroma * Math::Cos(Math::DegreesToRadians(hue));
  363. lab_values[2] = chroma * Math::Sin(Math::DegreesToRadians(hue));
  364. }
  365. CIELABToRGBA(lab_values);
  366. for (int i = 0; i < 4; ++i)
  367. colour[i] = (byte)(Math::Clamp((int)(lab_values[i] * 255.0f), 0, 255));
  368. return true;
  369. }
  370. bool PropertyParserColour::ParseOklabColour(Colourb& colour, const String& value)
  371. {
  372. StringList values;
  373. values.reserve(5);
  374. if (!GetColourFunctionValues(values, value, false))
  375. return false;
  376. // Check if we have an alpha component.
  377. if (values.size() == 5)
  378. {
  379. if (values[3] != "/")
  380. return false;
  381. values[3] = std::move(values[4]);
  382. values.pop_back();
  383. }
  384. else
  385. {
  386. if (values.size() != 3)
  387. return false;
  388. values.push_back("1.0");
  389. }
  390. Array<float, 4> oklab_values;
  391. // Parse lightness and alpha (same for both Oklab and Oklch).
  392. for (int i : {0, 3})
  393. {
  394. // Value can either be 'none' (representing 0.0), a percentage between 0% and 100%, or a number between 0.0 and 1.0.
  395. if (values[i] == "none")
  396. oklab_values[i] = 0.0f;
  397. else if (values[i][values[i].size() - 1] == '%')
  398. oklab_values[i] = (float)atof(values[i].substr(0, values[i].size() - 1).c_str()) / 100.0f;
  399. else
  400. oklab_values[i] = (float)atof(values[i].c_str());
  401. oklab_values[i] = Math::Clamp(oklab_values[i], 0.0f, 1.0f);
  402. }
  403. // Determine if colour is in Oklab or Oklch space.
  404. if (value.substr(0, 5) == "oklab")
  405. {
  406. // Parse A-axis (green-to-red) and B-axis (blue-to-yellow).
  407. for (int i : {1, 2})
  408. {
  409. // Value can either be 'none' (representing 0.0), a percentage between -100% and +100% (representing -0.4 to +0.4), or a number.
  410. if (values[i] == "none")
  411. oklab_values[i] = 0.0f;
  412. else if (values[i][values[i].size() - 1] == '%')
  413. {
  414. static constexpr float oklab_axis_percentage_bound = 0.4f;
  415. oklab_values[i] = (float)atof(values[i].substr(0, values[i].size() - 1).c_str()) / 100.0f * oklab_axis_percentage_bound;
  416. }
  417. else
  418. oklab_values[i] = (float)atof(values[i].c_str());
  419. // Whilst the axis values are theoretically unbounded, in practice, they only exist between -0.5 and +0.5.
  420. static constexpr float oklab_axis_bound_limit = 0.5f;
  421. oklab_values[i] = Math::Clamp(oklab_values[i], -oklab_axis_bound_limit, +oklab_axis_bound_limit);
  422. }
  423. }
  424. else
  425. {
  426. // Parse chroma; value can either be 'none' (representing 0.0), a percentage between 0% and 100% (representing 0.0 to 0.4), or a number.
  427. float chroma = 0.0f;
  428. if (values[1] == "none")
  429. chroma = 0.0f;
  430. else if (values[1][values[1].size() - 1] == '%')
  431. {
  432. static constexpr float oklch_maximum_percentage_chroma = 0.4f;
  433. chroma = (float)atof(values[1].substr(0, values[1].size() - 1).c_str()) / 100.0f * oklch_maximum_percentage_chroma;
  434. }
  435. else
  436. chroma = (float)atof(values[1].c_str());
  437. // Whilst the chroma is theoretically unbounded, in practice, it does not exceed 0.5.
  438. static constexpr float oklch_maximum_chroma = 0.5f;
  439. chroma = Math::Clamp(chroma, 0.0f, oklch_maximum_chroma);
  440. // Parse hue; value can either be 'none' (representing 0.0), or an angle.
  441. float hue = 0.0f;
  442. if (values[2] == "none")
  443. hue = 0.0f;
  444. else
  445. hue = (float)atof(values[2].c_str());
  446. // Convert Oklch polar coordinates to Oklab Cartesian coordinates.
  447. oklab_values[1] = chroma * Math::Cos(Math::DegreesToRadians(hue));
  448. oklab_values[2] = chroma * Math::Sin(Math::DegreesToRadians(hue));
  449. }
  450. OklabToRGBA(oklab_values);
  451. for (int i = 0; i < 4; ++i)
  452. colour[i] = (byte)(Math::Clamp((int)(oklab_values[i] * 255.0f), 0, 255));
  453. return true;
  454. }
  455. bool PropertyParserColour::GetColourFunctionValues(StringList& values, const String& value, bool is_comma_separated)
  456. {
  457. size_t find = value.find('(');
  458. if (find == String::npos)
  459. return false;
  460. size_t begin_values = find + 1;
  461. StringUtilities::ExpandString(values, value.substr(begin_values, value.rfind(')') - begin_values), is_comma_separated ? ',' : ' ',
  462. !is_comma_separated);
  463. return true;
  464. }
  465. } // namespace Rml