Interpolation.cpp 28 KB

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