GradientPainting.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Checked.h>
  7. #include <AK/Math.h>
  8. #include <LibGfx/Gamma.h>
  9. #include <LibGfx/Line.h>
  10. #include <LibWeb/CSS/StyleValue.h>
  11. #include <LibWeb/Painting/GradientPainting.h>
  12. namespace Web::Painting {
  13. static float normalized_gradient_angle_radians(float gradient_angle)
  14. {
  15. // Adjust angle so 0 degrees is bottom
  16. float real_angle = 90 - gradient_angle;
  17. return real_angle * (AK::Pi<float> / 180);
  18. }
  19. static float calulate_gradient_length(Gfx::IntSize const& gradient_size, float sin_angle, float cos_angle)
  20. {
  21. return AK::fabs(gradient_size.height() * sin_angle) + AK::fabs(gradient_size.width() * cos_angle);
  22. }
  23. static float calulate_gradient_length(Gfx::IntSize const& gradient_size, float gradient_angle)
  24. {
  25. float angle = normalized_gradient_angle_radians(gradient_angle);
  26. float sin_angle, cos_angle;
  27. AK::sincos(angle, sin_angle, cos_angle);
  28. return calulate_gradient_length(gradient_size, sin_angle, cos_angle);
  29. }
  30. static ColorStopData resolve_color_stop_positions(auto const& color_stop_list, auto resolve_position_to_float, bool repeating)
  31. {
  32. VERIFY(color_stop_list.size() >= 2);
  33. ColorStopList resolved_color_stops;
  34. auto color_stop_length = [&](auto& stop) {
  35. return stop.color_stop.second_position.has_value() ? 2 : 1;
  36. };
  37. size_t expanded_size = 0;
  38. for (auto& stop : color_stop_list)
  39. expanded_size += color_stop_length(stop);
  40. resolved_color_stops.ensure_capacity(expanded_size);
  41. for (auto& stop : color_stop_list) {
  42. auto resolved_stop = ColorStop { .color = stop.color_stop.color };
  43. for (int i = 0; i < color_stop_length(stop); i++)
  44. resolved_color_stops.append(resolved_stop);
  45. }
  46. // 1. If the first color stop does not have a position, set its position to 0%.
  47. resolved_color_stops.first().position = 0;
  48. // If the last color stop does not have a position, set its position to 100%
  49. resolved_color_stops.last().position = 1.0f;
  50. // 2. If a color stop or transition hint has a position that is less than the
  51. // specified position of any color stop or transition hint before it in the list,
  52. // set its position to be equal to the largest specified position of any color stop
  53. // or transition hint before it.
  54. auto max_previous_color_stop_or_hint = resolved_color_stops[0].position;
  55. auto resolve_stop_position = [&](auto& position) {
  56. float value = resolve_position_to_float(position);
  57. value = max(value, max_previous_color_stop_or_hint);
  58. max_previous_color_stop_or_hint = value;
  59. return value;
  60. };
  61. // Move this step somewhere generic (since I think this code can be mostly reused for conic gradients)
  62. size_t resolved_index = 0;
  63. for (auto& stop : color_stop_list) {
  64. if (stop.transition_hint.has_value())
  65. resolved_color_stops[resolved_index].transition_hint = resolve_stop_position(stop.transition_hint->value);
  66. if (stop.color_stop.position.has_value())
  67. resolved_color_stops[resolved_index].position = resolve_stop_position(*stop.color_stop.position);
  68. if (stop.color_stop.second_position.has_value())
  69. resolved_color_stops[++resolved_index].position = resolve_stop_position(*stop.color_stop.second_position);
  70. ++resolved_index;
  71. }
  72. // 3. If any color stop still does not have a position, then, for each run of adjacent color stops
  73. // without positions, set their positions so that they are evenly spaced between the preceding
  74. // and following color stops with positions.
  75. // Note: Though not mentioned anywhere in the specification transition hints are counted as "color stops with positions".
  76. size_t i = 1;
  77. auto find_run_end = [&] {
  78. auto color_stop_has_position = [](auto& color_stop) {
  79. return color_stop.transition_hint.has_value() || isfinite(color_stop.position);
  80. };
  81. while (i < color_stop_list.size() - 1 && !color_stop_has_position(resolved_color_stops[i])) {
  82. i++;
  83. }
  84. return i;
  85. };
  86. while (i < resolved_color_stops.size() - 1) {
  87. auto& stop = resolved_color_stops[i];
  88. if (!isfinite(stop.position)) {
  89. auto run_start = i - 1;
  90. auto start_position = resolved_color_stops[i++].transition_hint.value_or(resolved_color_stops[run_start].position);
  91. auto run_end = find_run_end();
  92. auto end_position = resolved_color_stops[run_end].transition_hint.value_or(resolved_color_stops[run_end].position);
  93. auto spacing = (end_position - start_position) / (run_end - run_start);
  94. for (auto j = run_start + 1; j < run_end; j++) {
  95. resolved_color_stops[j].position = start_position + (j - run_start) * spacing;
  96. }
  97. }
  98. i++;
  99. }
  100. // Determine the location of the transition hint as a percentage of the distance between the two color stops,
  101. // denoted as a number between 0 and 1, where 0 indicates the hint is placed right on the first color stop,
  102. // and 1 indicates the hint is placed right on the second color stop.
  103. for (size_t i = 1; i < resolved_color_stops.size(); i++) {
  104. auto& color_stop = resolved_color_stops[i];
  105. auto& previous_color_stop = resolved_color_stops[i - 1];
  106. if (color_stop.transition_hint.has_value()) {
  107. auto stop_length = color_stop.position - previous_color_stop.position;
  108. color_stop.transition_hint = stop_length > 0 ? (*color_stop.transition_hint - previous_color_stop.position) / stop_length : 0;
  109. }
  110. }
  111. Optional<float> repeat_length = {};
  112. if (repeating)
  113. repeat_length = resolved_color_stops.last().position - resolved_color_stops.first().position;
  114. return { resolved_color_stops, repeat_length };
  115. }
  116. LinearGradientData resolve_linear_gradient_data(Layout::Node const& node, Gfx::FloatSize const& gradient_size, CSS::LinearGradientStyleValue const& linear_gradient)
  117. {
  118. auto gradient_angle = linear_gradient.angle_degrees(gradient_size);
  119. auto gradient_length_px = calulate_gradient_length(gradient_size.to_rounded<int>(), gradient_angle);
  120. auto gradient_length = CSS::Length::make_px(gradient_length_px);
  121. auto resolved_color_stops = resolve_color_stop_positions(
  122. linear_gradient.color_stop_list(), [&](auto const& length_percentage) {
  123. return length_percentage.resolved(node, gradient_length).to_px(node) / gradient_length_px;
  124. },
  125. linear_gradient.is_repeating());
  126. return { gradient_angle, resolved_color_stops };
  127. }
  128. ConicGradientData resolve_conic_gradient_data(Layout::Node const& node, CSS::ConicGradientStyleValue const& conic_gradient)
  129. {
  130. CSS::Angle one_turn(360.0f, CSS::Angle::Type::Deg);
  131. auto resolved_color_stops = resolve_color_stop_positions(
  132. conic_gradient.color_stop_list(), [&](auto const& angle_percentage) {
  133. return angle_percentage.resolved(node, one_turn).to_degrees() / one_turn.to_degrees();
  134. },
  135. conic_gradient.is_repeating());
  136. return { conic_gradient.angle_degrees(), resolved_color_stops };
  137. }
  138. static float color_stop_step(ColorStop const& previous_stop, ColorStop const& next_stop, float position)
  139. {
  140. if (position < previous_stop.position)
  141. return 0;
  142. if (position > next_stop.position)
  143. return 1;
  144. // For any given point between the two color stops,
  145. // determine the point’s location as a percentage of the distance between the two color stops.
  146. // Let this percentage be P.
  147. auto stop_length = next_stop.position - previous_stop.position;
  148. // FIXME: Avoids NaNs... Still not quite correct?
  149. if (stop_length <= 0)
  150. return 1;
  151. auto p = (position - previous_stop.position) / stop_length;
  152. if (!next_stop.transition_hint.has_value())
  153. return p;
  154. if (*next_stop.transition_hint >= 1)
  155. return 0;
  156. if (*next_stop.transition_hint <= 0)
  157. return 1;
  158. // Let C, the color weighting at that point, be equal to P^(logH(.5)).
  159. auto c = AK::pow(p, AK::log<float>(0.5) / AK::log(*next_stop.transition_hint));
  160. // The color at that point is then a linear blend between the colors of the two color stops,
  161. // blending (1 - C) of the first stop and C of the second stop.
  162. return c;
  163. }
  164. class GradientLine {
  165. public:
  166. GradientLine(int gradient_length, ColorStopData const& color_stops)
  167. : m_repeating { color_stops.repeat_length.has_value() }
  168. , m_start_offset { round_to<int>((m_repeating ? color_stops.list.first().position : 0.0f) * gradient_length) }
  169. {
  170. // Note: color_count will be < gradient_length for repeating gradients.
  171. auto color_count = round_to<int>(color_stops.repeat_length.value_or(1.0f) * gradient_length);
  172. m_gradient_line_colors.resize(color_count);
  173. // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in:
  174. // https://drafts.csswg.org/css-images/#coloring-gradient-line
  175. auto& stop_list = color_stops.list;
  176. for (int loc = 0; loc < color_count; loc++) {
  177. auto relative_loc = float(loc + m_start_offset) / gradient_length;
  178. Gfx::Color gradient_color = stop_list[0].color.mixed_with(
  179. stop_list[1].color,
  180. color_stop_step(stop_list[0], stop_list[1], relative_loc));
  181. for (size_t i = 1; i < stop_list.size() - 1; i++) {
  182. gradient_color = gradient_color.mixed_with(
  183. stop_list[i + 1].color,
  184. color_stop_step(stop_list[i], stop_list[i + 1], relative_loc));
  185. }
  186. m_gradient_line_colors[loc] = gradient_color;
  187. }
  188. }
  189. Gfx::Color get_color(int index) const
  190. {
  191. return m_gradient_line_colors[clamp(index, 0, m_gradient_line_colors.size() - 1)];
  192. }
  193. Gfx::Color sample_color(float loc) const
  194. {
  195. auto repeat_wrap_if_required = [&](int loc) {
  196. if (m_repeating)
  197. return (loc + m_start_offset) % static_cast<int>(m_gradient_line_colors.size());
  198. return loc;
  199. };
  200. auto int_loc = static_cast<int>(floor(loc));
  201. auto blend = loc - int_loc;
  202. auto color = get_color(repeat_wrap_if_required(int_loc));
  203. // Blend between the two neighbouring colors (this fixes some nasty aliasing issues at small angles)
  204. if (blend >= 0.004f)
  205. color = color.mixed_with(get_color(repeat_wrap_if_required(int_loc + 1)), blend);
  206. return color;
  207. }
  208. void paint_into_rect(Gfx::Painter& painter, Gfx::IntRect const& rect, auto location_transform)
  209. {
  210. for (int y = 0; y < rect.height(); y++) {
  211. for (int x = 0; x < rect.width(); x++) {
  212. auto gradient_color = sample_color(location_transform(x, y));
  213. painter.set_pixel(rect.x() + x, rect.y() + y, gradient_color, gradient_color.alpha() < 255);
  214. }
  215. }
  216. }
  217. private:
  218. bool m_repeating;
  219. int m_start_offset;
  220. Vector<Gfx::Color, 1024> m_gradient_line_colors;
  221. };
  222. void paint_linear_gradient(PaintContext& context, Gfx::IntRect const& gradient_rect, LinearGradientData const& data)
  223. {
  224. float angle = normalized_gradient_angle_radians(data.gradient_angle);
  225. float sin_angle, cos_angle;
  226. AK::sincos(angle, sin_angle, cos_angle);
  227. // Full length of the gradient
  228. auto gradient_length_px = round_to<int>(calulate_gradient_length(gradient_rect.size(), sin_angle, cos_angle));
  229. Gfx::FloatPoint offset { cos_angle * (gradient_length_px / 2), sin_angle * (gradient_length_px / 2) };
  230. auto center = gradient_rect.translated(-gradient_rect.location()).center();
  231. auto start_point = center.to_type<float>() - offset;
  232. // Rotate gradient line to be horizontal
  233. auto rotated_start_point_x = start_point.x() * cos_angle - start_point.y() * -sin_angle;
  234. GradientLine gradient_line(gradient_length_px, data.color_stops);
  235. gradient_line.paint_into_rect(context.painter(), gradient_rect, [&](int x, int y) {
  236. return (x * cos_angle - (gradient_rect.height() - y) * -sin_angle) - rotated_start_point_x;
  237. });
  238. }
  239. void paint_conic_gradient(PaintContext& context, Gfx::IntRect const& gradient_rect, ConicGradientData const& data, Gfx::IntPoint position)
  240. {
  241. // FIXME: Do we need/want sub-degree accuracy for the gradient line?
  242. GradientLine gradient_line(360, data.color_stops);
  243. float start_angle = (360.0f - data.start_angle) + 90.0f;
  244. // Translate position/center to the center of the pixel (avoids some funky painting)
  245. auto center_point = Gfx::FloatPoint { position }.translated(0.5, 0.5);
  246. gradient_line.paint_into_rect(context.painter(), gradient_rect, [&](int x, int y) {
  247. auto point = Gfx::FloatPoint { x, y } - center_point;
  248. // FIXME: We could probably get away with some approximation here:
  249. // Note: We need too floor the angle here or the colors will start to diverge as you get further from the center.
  250. return floor(fmod((AK::atan2(point.y(), point.x()) * 180.0f / AK::Pi<float> + 360.0f + start_angle), 360.0f));
  251. });
  252. }
  253. }