Interpolation.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. * Copyright (c) 2021-2024, Sam Atkins <sam@ladybird.org>
  5. * Copyright (c) 2024, Matthew Olsson <mattco@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include "Interpolation.h"
  10. #include <LibWeb/CSS/PropertyID.h>
  11. #include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
  12. #include <LibWeb/CSS/StyleValues/CSSColorValue.h>
  13. #include <LibWeb/CSS/StyleValues/CSSKeywordValue.h>
  14. #include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
  15. #include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
  16. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  17. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  18. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  19. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  20. #include <LibWeb/CSS/StyleValues/RectStyleValue.h>
  21. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  22. #include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
  23. #include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
  24. #include <LibWeb/CSS/Transformation.h>
  25. #include <LibWeb/DOM/Element.h>
  26. #include <LibWeb/Layout/Node.h>
  27. #include <LibWeb/Painting/PaintableBox.h>
  28. namespace Web::CSS {
  29. template<typename T>
  30. static T interpolate_raw(T from, T to, float delta)
  31. {
  32. if constexpr (AK::Detail::IsSame<T, double>) {
  33. return from + (to - from) * static_cast<double>(delta);
  34. } else {
  35. return static_cast<AK::Detail::RemoveCVReference<T>>(from + (to - from) * delta);
  36. }
  37. }
  38. ValueComparingRefPtr<CSSStyleValue const> interpolate_property(DOM::Element& element, PropertyID property_id, CSSStyleValue const& from, CSSStyleValue const& to, float delta)
  39. {
  40. auto animation_type = animation_type_from_longhand_property(property_id);
  41. switch (animation_type) {
  42. case AnimationType::ByComputedValue:
  43. return interpolate_value(element, from, to, delta);
  44. case AnimationType::None:
  45. return to;
  46. case AnimationType::Custom: {
  47. if (property_id == PropertyID::Transform) {
  48. if (auto interpolated_transform = interpolate_transform(element, from, to, delta))
  49. return *interpolated_transform;
  50. // https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  51. // In some cases, an animation might cause a transformation matrix to be singular or non-invertible.
  52. // For example, an animation in which scale moves from 1 to -1. At the time when the matrix is in
  53. // such a state, the transformed element is not rendered.
  54. return {};
  55. }
  56. if (property_id == PropertyID::BoxShadow)
  57. return interpolate_box_shadow(element, from, to, delta);
  58. // FIXME: Handle all custom animatable properties
  59. [[fallthrough]];
  60. }
  61. // FIXME: Handle repeatable-list animatable properties
  62. case AnimationType::RepeatableList:
  63. case AnimationType::Discrete:
  64. default:
  65. return delta >= 0.5f ? to : from;
  66. }
  67. }
  68. // https://drafts.csswg.org/css-transitions/#transitionable
  69. bool property_values_are_transitionable(PropertyID property_id, CSSStyleValue const& old_value, CSSStyleValue const& new_value)
  70. {
  71. // When comparing the before-change style and after-change style for a given property,
  72. // the property values are transitionable if they have an animation type that is neither not animatable nor discrete.
  73. auto animation_type = animation_type_from_longhand_property(property_id);
  74. if (animation_type == AnimationType::None || animation_type == AnimationType::Discrete)
  75. return false;
  76. // FIXME: Even when a property is transitionable, the two values may not be. The spec uses the example of inset/non-inset shadows.
  77. (void)old_value;
  78. (void)new_value;
  79. return true;
  80. }
  81. // A null return value means the interpolated matrix was not invertible or otherwise invalid
  82. RefPtr<CSSStyleValue const> interpolate_transform(DOM::Element& element, CSSStyleValue const& from, CSSStyleValue const& to, float delta)
  83. {
  84. // Note that the spec uses column-major notation, so all the matrix indexing is reversed.
  85. static constexpr auto make_transformation = [](TransformationStyleValue const& transformation) -> AK::Optional<Transformation> {
  86. AK::Vector<TransformValue> values;
  87. for (auto const& value : transformation.values()) {
  88. switch (value->type()) {
  89. case CSSStyleValue::Type::Angle:
  90. values.append(AngleOrCalculated { value->as_angle().angle() });
  91. break;
  92. case CSSStyleValue::Type::Math:
  93. values.append(LengthPercentage { value->as_math() });
  94. break;
  95. case CSSStyleValue::Type::Length:
  96. values.append(LengthPercentage { value->as_length().length() });
  97. break;
  98. case CSSStyleValue::Type::Percentage:
  99. values.append(LengthPercentage { value->as_percentage().percentage() });
  100. break;
  101. case CSSStyleValue::Type::Number:
  102. values.append(NumberPercentage { Number(Number::Type::Number, value->as_number().number()) });
  103. break;
  104. default:
  105. return {};
  106. }
  107. }
  108. return Transformation { transformation.transform_function(), move(values) };
  109. };
  110. static constexpr auto transformation_style_value_to_matrix = [](DOM::Element& element, TransformationStyleValue const& value) -> Optional<FloatMatrix4x4> {
  111. auto transformation = make_transformation(value);
  112. if (!transformation.has_value())
  113. return {};
  114. Optional<Painting::PaintableBox const&> paintable_box;
  115. if (auto layout_node = element.layout_node()) {
  116. if (auto paintable = layout_node->paintable(); paintable && is<Painting::PaintableBox>(paintable))
  117. paintable_box = *static_cast<Painting::PaintableBox*>(paintable);
  118. }
  119. if (auto matrix = transformation->to_matrix(paintable_box); !matrix.is_error())
  120. return matrix.value();
  121. return {};
  122. };
  123. static constexpr auto style_value_to_matrix = [](DOM::Element& element, CSSStyleValue const& value) -> FloatMatrix4x4 {
  124. if (value.is_transformation())
  125. return transformation_style_value_to_matrix(element, value.as_transformation()).value_or(FloatMatrix4x4::identity());
  126. // This encompasses both the allowed value "none" and any invalid values
  127. if (!value.is_value_list())
  128. return FloatMatrix4x4::identity();
  129. auto matrix = FloatMatrix4x4::identity();
  130. for (auto const& value_element : value.as_value_list().values()) {
  131. if (value_element->is_transformation()) {
  132. if (auto value_matrix = transformation_style_value_to_matrix(element, value_element->as_transformation()); value_matrix.has_value())
  133. matrix = matrix * value_matrix.value();
  134. }
  135. }
  136. return matrix;
  137. };
  138. struct DecomposedValues {
  139. FloatVector3 translation;
  140. FloatVector3 scale;
  141. FloatVector3 skew;
  142. FloatVector4 rotation;
  143. FloatVector4 perspective;
  144. };
  145. // https://drafts.csswg.org/css-transforms-2/#decomposing-a-3d-matrix
  146. static constexpr auto decompose = [](FloatMatrix4x4 matrix) -> Optional<DecomposedValues> {
  147. // https://drafts.csswg.org/css-transforms-1/#supporting-functions
  148. static constexpr auto combine = [](auto a, auto b, float ascl, float bscl) {
  149. return FloatVector3 {
  150. ascl * a[0] + bscl * b[0],
  151. ascl * a[1] + bscl * b[1],
  152. ascl * a[2] + bscl * b[2],
  153. };
  154. };
  155. // Normalize the matrix.
  156. if (matrix(3, 3) == 0.f)
  157. return {};
  158. for (int i = 0; i < 4; i++)
  159. for (int j = 0; j < 4; j++)
  160. matrix(i, j) /= matrix(3, 3);
  161. // perspectiveMatrix is used to solve for perspective, but it also provides
  162. // an easy way to test for singularity of the upper 3x3 component.
  163. auto perspective_matrix = matrix;
  164. for (int i = 0; i < 3; i++)
  165. perspective_matrix(3, i) = 0.f;
  166. perspective_matrix(3, 3) = 1.f;
  167. if (!perspective_matrix.is_invertible())
  168. return {};
  169. DecomposedValues values;
  170. // First, isolate perspective.
  171. if (matrix(3, 0) != 0.f || matrix(3, 1) != 0.f || matrix(3, 2) != 0.f) {
  172. // rightHandSide is the right hand side of the equation.
  173. // Note: It is the bottom side in a row-major matrix
  174. FloatVector4 bottom_side = {
  175. matrix(3, 0),
  176. matrix(3, 1),
  177. matrix(3, 2),
  178. matrix(3, 3),
  179. };
  180. // Solve the equation by inverting perspectiveMatrix and multiplying
  181. // rightHandSide by the inverse.
  182. auto inverse_perspective_matrix = perspective_matrix.inverse();
  183. auto transposed_inverse_perspective_matrix = inverse_perspective_matrix.transpose();
  184. values.perspective = transposed_inverse_perspective_matrix * bottom_side;
  185. } else {
  186. // No perspective.
  187. values.perspective = { 0.0, 0.0, 0.0, 1.0 };
  188. }
  189. // Next take care of translation
  190. for (int i = 0; i < 3; i++)
  191. values.translation[i] = matrix(i, 3);
  192. // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
  193. FloatVector3 row[3];
  194. for (int i = 0; i < 3; i++)
  195. row[i] = { matrix(0, i), matrix(1, i), matrix(2, i) };
  196. // Compute X scale factor and normalize first row.
  197. values.scale[0] = row[0].length();
  198. row[0].normalize();
  199. // Compute XY shear factor and make 2nd row orthogonal to 1st.
  200. values.skew[0] = row[0].dot(row[1]);
  201. row[1] = combine(row[1], row[0], 1.f, -values.skew[0]);
  202. // Now, compute Y scale and normalize 2nd row.
  203. values.scale[1] = row[1].length();
  204. row[1].normalize();
  205. values.skew[0] /= values.scale[1];
  206. // Compute XZ and YZ shears, orthogonalize 3rd row
  207. values.skew[1] = row[0].dot(row[2]);
  208. row[2] = combine(row[2], row[0], 1.f, -values.skew[1]);
  209. values.skew[2] = row[1].dot(row[2]);
  210. row[2] = combine(row[2], row[1], 1.f, -values.skew[2]);
  211. // Next, get Z scale and normalize 3rd row.
  212. values.scale[2] = row[2].length();
  213. row[2].normalize();
  214. values.skew[1] /= values.scale[2];
  215. values.skew[2] /= values.scale[2];
  216. // At this point, the matrix (in rows) is orthonormal.
  217. // Check for a coordinate system flip. If the determinant
  218. // is -1, then negate the matrix and the scaling factors.
  219. auto pdum3 = row[1].cross(row[2]);
  220. if (row[0].dot(pdum3) < 0.f) {
  221. for (int i = 0; i < 3; i++) {
  222. values.scale[i] *= -1.f;
  223. row[i][0] *= -1.f;
  224. row[i][1] *= -1.f;
  225. row[i][2] *= -1.f;
  226. }
  227. }
  228. // Now, get the rotations out
  229. values.rotation[0] = 0.5f * sqrt(max(1.f + row[0][0] - row[1][1] - row[2][2], 0.f));
  230. values.rotation[1] = 0.5f * sqrt(max(1.f - row[0][0] + row[1][1] - row[2][2], 0.f));
  231. values.rotation[2] = 0.5f * sqrt(max(1.f - row[0][0] - row[1][1] + row[2][2], 0.f));
  232. values.rotation[3] = 0.5f * sqrt(max(1.f + row[0][0] + row[1][1] + row[2][2], 0.f));
  233. if (row[2][1] > row[1][2])
  234. values.rotation[0] = -values.rotation[0];
  235. if (row[0][2] > row[2][0])
  236. values.rotation[1] = -values.rotation[1];
  237. if (row[1][0] > row[0][1])
  238. values.rotation[2] = -values.rotation[2];
  239. // FIXME: This accounts for the fact that the browser coordinate system is left-handed instead of right-handed.
  240. // The reason for this is that the positive Y-axis direction points down instead of up. To fix this, we
  241. // invert the Y axis. However, it feels like the spec pseudo-code above should have taken something like
  242. // this into account, so we're probably doing something else wrong.
  243. values.rotation[2] *= -1;
  244. return values;
  245. };
  246. // https://drafts.csswg.org/css-transforms-2/#recomposing-to-a-3d-matrix
  247. static constexpr auto recompose = [](DecomposedValues const& values) -> FloatMatrix4x4 {
  248. auto matrix = FloatMatrix4x4::identity();
  249. // apply perspective
  250. for (int i = 0; i < 4; i++)
  251. matrix(3, i) = values.perspective[i];
  252. // apply translation
  253. for (int i = 0; i < 4; i++) {
  254. for (int j = 0; j < 3; j++)
  255. matrix(i, 3) += values.translation[j] * matrix(i, j);
  256. }
  257. // apply rotation
  258. auto x = values.rotation[0];
  259. auto y = values.rotation[1];
  260. auto z = values.rotation[2];
  261. auto w = values.rotation[3];
  262. // Construct a composite rotation matrix from the quaternion values
  263. // rotationMatrix is a identity 4x4 matrix initially
  264. auto rotation_matrix = FloatMatrix4x4::identity();
  265. rotation_matrix(0, 0) = 1.f - 2.f * (y * y + z * z);
  266. rotation_matrix(1, 0) = 2.f * (x * y - z * w);
  267. rotation_matrix(2, 0) = 2.f * (x * z + y * w);
  268. rotation_matrix(0, 1) = 2.f * (x * y + z * w);
  269. rotation_matrix(1, 1) = 1.f - 2.f * (x * x + z * z);
  270. rotation_matrix(2, 1) = 2.f * (y * z - x * w);
  271. rotation_matrix(0, 2) = 2.f * (x * z - y * w);
  272. rotation_matrix(1, 2) = 2.f * (y * z + x * w);
  273. rotation_matrix(2, 2) = 1.f - 2.f * (x * x + y * y);
  274. matrix = matrix * rotation_matrix;
  275. // apply skew
  276. // temp is a identity 4x4 matrix initially
  277. auto temp = FloatMatrix4x4::identity();
  278. if (values.skew[2] != 0.f) {
  279. temp(1, 2) = values.skew[2];
  280. matrix = matrix * temp;
  281. }
  282. if (values.skew[1] != 0.f) {
  283. temp(1, 2) = 0.f;
  284. temp(0, 2) = values.skew[1];
  285. matrix = matrix * temp;
  286. }
  287. if (values.skew[0] != 0.f) {
  288. temp(0, 2) = 0.f;
  289. temp(0, 1) = values.skew[0];
  290. matrix = matrix * temp;
  291. }
  292. // apply scale
  293. for (int i = 0; i < 3; i++) {
  294. for (int j = 0; j < 4; j++)
  295. matrix(j, i) *= values.scale[i];
  296. }
  297. return matrix;
  298. };
  299. // https://drafts.csswg.org/css-transforms-2/#interpolation-of-decomposed-3d-matrix-values
  300. static constexpr auto interpolate = [](DecomposedValues& from, DecomposedValues& to, float delta) -> DecomposedValues {
  301. auto product = clamp(from.rotation.dot(to.rotation), -1.0f, 1.0f);
  302. FloatVector4 interpolated_rotation;
  303. if (fabsf(product) == 1.0f) {
  304. interpolated_rotation = from.rotation;
  305. } else {
  306. auto theta = acos(product);
  307. auto w = sin(delta * theta) / sqrtf(1.0f - product * product);
  308. for (int i = 0; i < 4; i++) {
  309. from.rotation[i] *= cos(delta * theta) - product * w;
  310. to.rotation[i] *= w;
  311. interpolated_rotation[i] = from.rotation[i] + to.rotation[i];
  312. }
  313. }
  314. return {
  315. interpolate_raw(from.translation, to.translation, delta),
  316. interpolate_raw(from.scale, to.scale, delta),
  317. interpolate_raw(from.skew, to.skew, delta),
  318. interpolated_rotation,
  319. interpolate_raw(from.perspective, to.perspective, delta),
  320. };
  321. };
  322. auto from_matrix = style_value_to_matrix(element, from);
  323. auto to_matrix = style_value_to_matrix(element, to);
  324. auto from_decomposed = decompose(from_matrix);
  325. auto to_decomposed = decompose(to_matrix);
  326. if (!from_decomposed.has_value() || !to_decomposed.has_value())
  327. return {};
  328. auto interpolated_decomposed = interpolate(from_decomposed.value(), to_decomposed.value(), delta);
  329. auto interpolated = recompose(interpolated_decomposed);
  330. StyleValueVector values;
  331. values.ensure_capacity(16);
  332. for (int i = 0; i < 16; i++)
  333. values.append(NumberStyleValue::create(static_cast<double>(interpolated(i % 4, i / 4))));
  334. return StyleValueList::create({ TransformationStyleValue::create(TransformFunction::Matrix3d, move(values)) }, StyleValueList::Separator::Comma);
  335. }
  336. Color interpolate_color(Color from, Color to, float delta)
  337. {
  338. // https://drafts.csswg.org/css-color/#interpolation-space
  339. // If the host syntax does not define what color space interpolation should take place in, it defaults to Oklab.
  340. auto from_oklab = from.to_oklab();
  341. auto to_oklab = to.to_oklab();
  342. auto color = Color::from_oklab(
  343. interpolate_raw(from_oklab.L, to_oklab.L, delta),
  344. interpolate_raw(from_oklab.a, to_oklab.a, delta),
  345. interpolate_raw(from_oklab.b, to_oklab.b, delta));
  346. color.set_alpha(interpolate_raw(from.alpha(), to.alpha(), delta));
  347. return color;
  348. }
  349. NonnullRefPtr<CSSStyleValue const> interpolate_box_shadow(DOM::Element& element, CSSStyleValue const& from, CSSStyleValue const& to, float delta)
  350. {
  351. // https://drafts.csswg.org/css-backgrounds/#box-shadow
  352. // Animation type: by computed value, treating none as a zero-item list and appending blank shadows
  353. // (transparent 0 0 0 0) with a corresponding inset keyword as needed to match the longer list if
  354. // the shorter list is otherwise compatible with the longer one
  355. static constexpr auto process_list = [](CSSStyleValue const& value) {
  356. StyleValueVector shadows;
  357. if (value.is_value_list()) {
  358. for (auto const& element : value.as_value_list().values()) {
  359. if (element->is_shadow())
  360. shadows.append(element);
  361. }
  362. } else if (value.is_shadow()) {
  363. shadows.append(value);
  364. } else if (!value.is_keyword() || value.as_keyword().keyword() != Keyword::None) {
  365. VERIFY_NOT_REACHED();
  366. }
  367. return shadows;
  368. };
  369. static constexpr auto extend_list_if_necessary = [](StyleValueVector& values, StyleValueVector const& other) {
  370. values.ensure_capacity(other.size());
  371. for (size_t i = values.size(); i < other.size(); i++) {
  372. values.unchecked_append(ShadowStyleValue::create(
  373. CSSColorValue::create_from_color(Color::Transparent),
  374. LengthStyleValue::create(Length::make_px(0)),
  375. LengthStyleValue::create(Length::make_px(0)),
  376. LengthStyleValue::create(Length::make_px(0)),
  377. LengthStyleValue::create(Length::make_px(0)),
  378. other[i]->as_shadow().placement()));
  379. }
  380. };
  381. StyleValueVector from_shadows = process_list(from);
  382. StyleValueVector to_shadows = process_list(to);
  383. extend_list_if_necessary(from_shadows, to_shadows);
  384. extend_list_if_necessary(to_shadows, from_shadows);
  385. VERIFY(from_shadows.size() == to_shadows.size());
  386. StyleValueVector result_shadows;
  387. result_shadows.ensure_capacity(from_shadows.size());
  388. for (size_t i = 0; i < from_shadows.size(); i++) {
  389. auto const& from_shadow = from_shadows[i]->as_shadow();
  390. auto const& to_shadow = to_shadows[i]->as_shadow();
  391. auto result_shadow = ShadowStyleValue::create(
  392. CSSColorValue::create_from_color(interpolate_color(from_shadow.color()->to_color({}), to_shadow.color()->to_color({}), delta)),
  393. interpolate_value(element, from_shadow.offset_x(), to_shadow.offset_x(), delta),
  394. interpolate_value(element, from_shadow.offset_y(), to_shadow.offset_y(), delta),
  395. interpolate_value(element, from_shadow.blur_radius(), to_shadow.blur_radius(), delta),
  396. interpolate_value(element, from_shadow.spread_distance(), to_shadow.spread_distance(), delta),
  397. delta >= 0.5f ? to_shadow.placement() : from_shadow.placement());
  398. result_shadows.unchecked_append(result_shadow);
  399. }
  400. return StyleValueList::create(move(result_shadows), StyleValueList::Separator::Comma);
  401. }
  402. NonnullRefPtr<CSSStyleValue const> interpolate_value(DOM::Element& element, CSSStyleValue const& from, CSSStyleValue const& to, float delta)
  403. {
  404. if (from.type() != to.type()) {
  405. // Handle mixed percentage and dimension types
  406. // https://www.w3.org/TR/css-values-4/#mixed-percentages
  407. struct NumericBaseTypeAndDefault {
  408. CSSNumericType::BaseType base_type;
  409. ValueComparingNonnullRefPtr<CSSStyleValue> default_value;
  410. };
  411. static constexpr auto numeric_base_type_and_default = [](CSSStyleValue const& value) -> Optional<NumericBaseTypeAndDefault> {
  412. switch (value.type()) {
  413. case CSSStyleValue::Type::Angle: {
  414. static auto default_angle_value = AngleStyleValue::create(Angle::make_degrees(0));
  415. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Angle, default_angle_value };
  416. }
  417. case CSSStyleValue::Type::Frequency: {
  418. static auto default_frequency_value = FrequencyStyleValue::create(Frequency::make_hertz(0));
  419. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Frequency, default_frequency_value };
  420. }
  421. case CSSStyleValue::Type::Length: {
  422. static auto default_length_value = LengthStyleValue::create(Length::make_px(0));
  423. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Length, default_length_value };
  424. }
  425. case CSSStyleValue::Type::Percentage: {
  426. static auto default_percentage_value = PercentageStyleValue::create(Percentage { 0.0 });
  427. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Percent, default_percentage_value };
  428. }
  429. case CSSStyleValue::Type::Time: {
  430. static auto default_time_value = TimeStyleValue::create(Time::make_seconds(0));
  431. return NumericBaseTypeAndDefault { CSSNumericType::BaseType::Time, default_time_value };
  432. }
  433. default:
  434. return {};
  435. }
  436. };
  437. static constexpr auto to_calculation_node = [](CSSStyleValue const& value) -> NonnullOwnPtr<CalculationNode> {
  438. switch (value.type()) {
  439. case CSSStyleValue::Type::Angle:
  440. return NumericCalculationNode::create(value.as_angle().angle());
  441. case CSSStyleValue::Type::Frequency:
  442. return NumericCalculationNode::create(value.as_frequency().frequency());
  443. case CSSStyleValue::Type::Length:
  444. return NumericCalculationNode::create(value.as_length().length());
  445. case CSSStyleValue::Type::Percentage:
  446. return NumericCalculationNode::create(value.as_percentage().percentage());
  447. case CSSStyleValue::Type::Time:
  448. return NumericCalculationNode::create(value.as_time().time());
  449. default:
  450. VERIFY_NOT_REACHED();
  451. }
  452. };
  453. auto from_base_type_and_default = numeric_base_type_and_default(from);
  454. auto to_base_type_and_default = numeric_base_type_and_default(to);
  455. if (from_base_type_and_default.has_value() && to_base_type_and_default.has_value() && (from_base_type_and_default->base_type == CSSNumericType::BaseType::Percent || to_base_type_and_default->base_type == CSSNumericType::BaseType::Percent)) {
  456. // This is an interpolation from a numeric unit to a percentage, or vice versa. The trick here is to
  457. // interpolate two separate values. For example, consider an interpolation from 30px to 80%. It's quite
  458. // hard to understand how this interpolation works, but if instead we rewrite the values as "30px + 0%" and
  459. // "0px + 80%", then it is very simple to understand; we just interpolate each component separately.
  460. auto interpolated_from = interpolate_value(element, from, from_base_type_and_default->default_value, delta);
  461. auto interpolated_to = interpolate_value(element, to_base_type_and_default->default_value, to, delta);
  462. Vector<NonnullOwnPtr<CalculationNode>> values;
  463. values.ensure_capacity(2);
  464. values.unchecked_append(to_calculation_node(interpolated_from));
  465. values.unchecked_append(to_calculation_node(interpolated_to));
  466. auto calc_node = SumCalculationNode::create(move(values));
  467. return CSSMathValue::create(move(calc_node), CSSNumericType { to_base_type_and_default->base_type, 1 });
  468. }
  469. return delta >= 0.5f ? to : from;
  470. }
  471. switch (from.type()) {
  472. case CSSStyleValue::Type::Angle:
  473. return AngleStyleValue::create(Angle::make_degrees(interpolate_raw(from.as_angle().angle().to_degrees(), to.as_angle().angle().to_degrees(), delta)));
  474. case CSSStyleValue::Type::Color: {
  475. Optional<Layout::NodeWithStyle const&> layout_node;
  476. if (auto node = element.layout_node())
  477. layout_node = *node;
  478. return CSSColorValue::create_from_color(interpolate_color(from.to_color(layout_node), to.to_color(layout_node), delta));
  479. }
  480. case CSSStyleValue::Type::Integer:
  481. return IntegerStyleValue::create(interpolate_raw(from.as_integer().integer(), to.as_integer().integer(), delta));
  482. case CSSStyleValue::Type::Length: {
  483. auto& from_length = from.as_length().length();
  484. auto& to_length = to.as_length().length();
  485. return LengthStyleValue::create(Length(interpolate_raw(from_length.raw_value(), to_length.raw_value(), delta), from_length.type()));
  486. }
  487. case CSSStyleValue::Type::Number:
  488. return NumberStyleValue::create(interpolate_raw(from.as_number().number(), to.as_number().number(), delta));
  489. case CSSStyleValue::Type::Percentage:
  490. return PercentageStyleValue::create(Percentage(interpolate_raw(from.as_percentage().percentage().value(), to.as_percentage().percentage().value(), delta)));
  491. case CSSStyleValue::Type::Position: {
  492. // https://www.w3.org/TR/css-values-4/#combine-positions
  493. // FIXME: Interpolation of <position> is defined as the independent interpolation of each component (x, y) normalized as an offset from the top left corner as a <length-percentage>.
  494. auto& from_position = from.as_position();
  495. auto& to_position = to.as_position();
  496. return PositionStyleValue::create(
  497. interpolate_value(element, from_position.edge_x(), to_position.edge_x(), delta)->as_edge(),
  498. interpolate_value(element, from_position.edge_y(), to_position.edge_y(), delta)->as_edge());
  499. }
  500. case CSSStyleValue::Type::Ratio: {
  501. auto from_ratio = from.as_ratio().ratio();
  502. auto to_ratio = to.as_ratio().ratio();
  503. // The interpolation of a <ratio> is defined by converting each <ratio> to a number by dividing the first value
  504. // by the second (so a ratio of 3 / 2 would become 1.5), taking the logarithm of that result (so the 1.5 would
  505. // become approximately 0.176), then interpolating those values. The result during the interpolation is
  506. // converted back to a <ratio> by inverting the logarithm, then interpreting the result as a <ratio> with the
  507. // result as the first value and 1 as the second value.
  508. auto from_number = log(from_ratio.value());
  509. auto to_number = log(to_ratio.value());
  510. auto interp_number = interpolate_raw(from_number, to_number, delta);
  511. return RatioStyleValue::create(Ratio(pow(M_E, interp_number)));
  512. }
  513. case CSSStyleValue::Type::Rect: {
  514. auto from_rect = from.as_rect().rect();
  515. auto to_rect = to.as_rect().rect();
  516. return RectStyleValue::create({
  517. Length(interpolate_raw(from_rect.top_edge.raw_value(), to_rect.top_edge.raw_value(), delta), from_rect.top_edge.type()),
  518. Length(interpolate_raw(from_rect.right_edge.raw_value(), to_rect.right_edge.raw_value(), delta), from_rect.right_edge.type()),
  519. Length(interpolate_raw(from_rect.bottom_edge.raw_value(), to_rect.bottom_edge.raw_value(), delta), from_rect.bottom_edge.type()),
  520. Length(interpolate_raw(from_rect.left_edge.raw_value(), to_rect.left_edge.raw_value(), delta), from_rect.left_edge.type()),
  521. });
  522. }
  523. case CSSStyleValue::Type::Transformation:
  524. VERIFY_NOT_REACHED();
  525. case CSSStyleValue::Type::ValueList: {
  526. auto& from_list = from.as_value_list();
  527. auto& to_list = to.as_value_list();
  528. if (from_list.size() != to_list.size())
  529. return from;
  530. StyleValueVector interpolated_values;
  531. interpolated_values.ensure_capacity(from_list.size());
  532. for (size_t i = 0; i < from_list.size(); ++i)
  533. interpolated_values.append(interpolate_value(element, from_list.values()[i], to_list.values()[i], delta));
  534. return StyleValueList::create(move(interpolated_values), from_list.separator());
  535. }
  536. default:
  537. return from;
  538. }
  539. }
  540. }