ElementAnimation.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2018 Michael R. P. Ragazzon
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "ElementAnimation.h"
  29. #include "../../Include/RmlUi/Core/DecorationTypes.h"
  30. #include "../../Include/RmlUi/Core/Decorator.h"
  31. #include "../../Include/RmlUi/Core/Element.h"
  32. #include "../../Include/RmlUi/Core/Filter.h"
  33. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  34. #include "../../Include/RmlUi/Core/PropertySpecification.h"
  35. #include "../../Include/RmlUi/Core/StyleSheet.h"
  36. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  37. #include "../../Include/RmlUi/Core/StyleSheetTypes.h"
  38. #include "../../Include/RmlUi/Core/Transform.h"
  39. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  40. #include "ComputeProperty.h"
  41. #include "ElementStyle.h"
  42. #include "TransformUtilities.h"
  43. namespace Rml {
  44. static Property InterpolateProperties(const Property& p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition);
  45. template <typename T>
  46. static T Mix(const T& v0, const T& v1, float alpha)
  47. {
  48. return v0 * (1.0f - alpha) + v1 * alpha;
  49. }
  50. static Colourf ColourToLinearSpace(Colourb c)
  51. {
  52. Colourf result;
  53. // Approximate inverse sRGB function
  54. result.red = c.red / 255.f;
  55. result.red *= result.red;
  56. result.green = c.green / 255.f;
  57. result.green *= result.green;
  58. result.blue = c.blue / 255.f;
  59. result.blue *= result.blue;
  60. result.alpha = c.alpha / 255.f;
  61. return result;
  62. }
  63. static Colourb ColourFromLinearSpace(Colourf c)
  64. {
  65. Colourb result;
  66. result.red = (byte)Math::Clamp(Math::SquareRoot(c.red) * 255.f, 0.0f, 255.f);
  67. result.green = (byte)Math::Clamp(Math::SquareRoot(c.green) * 255.f, 0.0f, 255.f);
  68. result.blue = (byte)Math::Clamp(Math::SquareRoot(c.blue) * 255.f, 0.0f, 255.f);
  69. result.alpha = (byte)Math::Clamp(c.alpha * 255.f, 0.0f, 255.f);
  70. return result;
  71. }
  72. static Colourb InterpolateColour(Colourb c0, Colourb c1, float alpha)
  73. {
  74. Colourf c0f = ColourToLinearSpace(c0);
  75. Colourf c1f = ColourToLinearSpace(c1);
  76. Colourf c = Mix(c0f, c1f, alpha);
  77. return ColourFromLinearSpace(c);
  78. }
  79. // Merges all the primitives to a single DecomposedMatrix4 primitive
  80. static bool CombineAndDecompose(Transform& t, Element& e)
  81. {
  82. Matrix4f m = Matrix4f::Identity();
  83. for (TransformPrimitive& primitive : t.GetPrimitives())
  84. {
  85. Matrix4f m_primitive = TransformUtilities::ResolveTransform(primitive, e);
  86. m *= m_primitive;
  87. }
  88. Transforms::DecomposedMatrix4 decomposed;
  89. if (!TransformUtilities::Decompose(decomposed, m))
  90. return false;
  91. t.ClearPrimitives();
  92. t.AddPrimitive(decomposed);
  93. return true;
  94. }
  95. /**
  96. An abstraction for decorator and filter declarations.
  97. */
  98. struct EffectDeclarationView {
  99. EffectDeclarationView() = default;
  100. EffectDeclarationView(const DecoratorDeclaration& declaration) :
  101. instancer(declaration.instancer), type(&declaration.type), properties(&declaration.properties), paint_area(declaration.paint_area)
  102. {}
  103. EffectDeclarationView(const NamedDecorator* named_decorator) :
  104. instancer(named_decorator->instancer), type(&named_decorator->type), properties(&named_decorator->properties)
  105. {}
  106. EffectDeclarationView(const FilterDeclaration& declaration) :
  107. instancer(declaration.instancer), type(&declaration.type), properties(&declaration.properties)
  108. {}
  109. EffectSpecification* instancer = nullptr;
  110. const String* type = nullptr;
  111. const PropertyDictionary* properties = nullptr;
  112. BoxArea paint_area = BoxArea::Auto;
  113. explicit operator bool() const { return instancer != nullptr; }
  114. };
  115. // Interpolate two effect declarations. One of them can be empty, in which case the empty one is replaced by default values.
  116. static bool InterpolateEffectProperties(PropertyDictionary& properties, const EffectDeclarationView& d0, const EffectDeclarationView& d1, float alpha,
  117. Element& element)
  118. {
  119. if (d0 && d1)
  120. {
  121. // Both declarations are specified, check if they are compatible for interpolation.
  122. if (!d0.instancer || d0.instancer != d1.instancer || *d0.type != *d1.type ||
  123. d0.properties->GetNumProperties() != d1.properties->GetNumProperties() || d0.paint_area != d1.paint_area)
  124. return false;
  125. const auto& properties0 = d0.properties->GetProperties();
  126. const auto& properties1 = d1.properties->GetProperties();
  127. for (const auto& pair0 : properties0)
  128. {
  129. const PropertyId id = pair0.first;
  130. const Property& prop0 = pair0.second;
  131. auto it = properties1.find(id);
  132. if (it == properties1.end())
  133. {
  134. RMLUI_ERRORMSG("Incompatible decorator properties.");
  135. return false;
  136. }
  137. const Property& prop1 = it->second;
  138. Property p = InterpolateProperties(prop0, prop1, alpha, element, prop0.definition);
  139. p.definition = prop0.definition;
  140. properties.SetProperty(id, p);
  141. }
  142. return true;
  143. }
  144. else if ((d0 && !d1) || (!d0 && d1))
  145. {
  146. // One of the declarations is empty, interpolate against the default values of its type.
  147. const auto& d_filled = (d0 ? d0 : d1);
  148. const PropertySpecification& specification = d_filled.instancer->GetPropertySpecification();
  149. const PropertyMap& properties_filled = d_filled.properties->GetProperties();
  150. for (const auto& pair_filled : properties_filled)
  151. {
  152. const PropertyId id = pair_filled.first;
  153. const PropertyDefinition* underlying_definition = specification.GetProperty(id);
  154. if (!underlying_definition)
  155. return false;
  156. const Property& p_filled = pair_filled.second;
  157. const Property& p_default = *underlying_definition->GetDefaultValue();
  158. const Property& p_interp0 = (d0 ? p_filled : p_default);
  159. const Property& p_interp1 = (d1 ? p_filled : p_default);
  160. Property p = InterpolateProperties(p_interp0, p_interp1, alpha, element, p_filled.definition);
  161. p.definition = p_filled.definition;
  162. properties.SetProperty(id, p);
  163. }
  164. return true;
  165. }
  166. return false;
  167. }
  168. static NumericValue InterpolateNumericValue(NumericValue v0, NumericValue v1, float alpha, Element& element, const PropertyDefinition* definition)
  169. {
  170. // If we have the same units, we can simply interpolate regardless of what the value represents.
  171. if (v0.unit == v1.unit)
  172. return NumericValue{Mix(v0.number, v1.number, alpha), v0.unit};
  173. // When mixing lengths or relative sizes, resolve them to pixel lengths and interpolate. This only works if we have a definition.
  174. if (Any(v0.unit & Unit::NUMBER_LENGTH_PERCENT) && Any(v1.unit & Unit::NUMBER_LENGTH_PERCENT) && definition)
  175. {
  176. float f0 = element.GetStyle()->ResolveRelativeLength(v0, definition->GetRelativeTarget());
  177. float f1 = element.GetStyle()->ResolveRelativeLength(v1, definition->GetRelativeTarget());
  178. return NumericValue{Mix(f0, f1, alpha), Unit::PX};
  179. }
  180. // As long as we don't mix lengths and percentages, we can still resolve lengths without a definition.
  181. if (Any(v0.unit & Unit::LENGTH) && Any(v1.unit & Unit::LENGTH))
  182. {
  183. float f0 = element.ResolveLength(v0);
  184. float f1 = element.ResolveLength(v0);
  185. return NumericValue{Mix(f0, f1, alpha), Unit::PX};
  186. }
  187. if (Any(v0.unit & Unit::ANGLE) && Any(v1.unit & Unit::ANGLE))
  188. {
  189. float f = Mix(ComputeAngle(v0), ComputeAngle(v1), alpha);
  190. return NumericValue{f, Unit::RAD};
  191. }
  192. // Fall back to discrete interpolation for incompatible units.
  193. return alpha < 0.5f ? v0 : v1;
  194. }
  195. static Property InterpolateProperties(const Property& p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition)
  196. {
  197. const Property& p_discrete = (alpha < 0.5f ? p0 : p1);
  198. if (Any(p0.unit & Unit::NUMERIC) && Any(p1.unit & Unit::NUMERIC))
  199. {
  200. NumericValue v = InterpolateNumericValue(p0.GetNumericValue(), p1.GetNumericValue(), alpha, element, definition);
  201. return Property{v.number, v.unit};
  202. }
  203. if (p0.unit == Unit::KEYWORD && p1.unit == Unit::KEYWORD)
  204. {
  205. // Discrete interpolation, swap at alpha = 0.5.
  206. // Special case for the 'visibility' and 'display' properties as in the CSS specs:
  207. // If present, apply the 'visible' / non-'none' keyword during the entire transition period, i.e. alpha (0,1).
  208. // See: https://www.w3.org/TR/css-display-4/#display-animation
  209. if (definition && definition->GetId() == PropertyId::Visibility)
  210. {
  211. if (p0.Get<int>() == (int)Style::Visibility::Visible)
  212. return alpha < 1.f ? p0 : p1;
  213. else if (p1.Get<int>() == (int)Style::Visibility::Visible)
  214. return alpha <= 0.f ? p0 : p1;
  215. }
  216. if (definition && definition->GetId() == PropertyId::Display)
  217. {
  218. if (p0.Get<int>() == (int)Style::Display::None)
  219. return alpha <= 0.f ? p0 : p1;
  220. else if (p1.Get<int>() == (int)Style::Display::None)
  221. return alpha < 1.f ? p0 : p1;
  222. }
  223. return p_discrete;
  224. }
  225. if (p0.unit == Unit::COLOUR && p1.unit == Unit::COLOUR)
  226. {
  227. Colourb c = InterpolateColour(p0.value.Get<Colourb>(), p1.value.Get<Colourb>(), alpha);
  228. return Property{c, Unit::COLOUR};
  229. }
  230. if (p0.unit == Unit::TRANSFORM && p1.unit == Unit::TRANSFORM)
  231. {
  232. auto& t0 = p0.value.GetReference<TransformPtr>();
  233. auto& t1 = p1.value.GetReference<TransformPtr>();
  234. const auto& prim0 = t0->GetPrimitives();
  235. const auto& prim1 = t1->GetPrimitives();
  236. if (prim0.size() != prim1.size())
  237. {
  238. RMLUI_ERRORMSG("Transform primitives not of same size during interpolation. Were the transforms properly prepared for interpolation?");
  239. return Property{t0, Unit::TRANSFORM};
  240. }
  241. // Build the new, interpolating transform
  242. UniquePtr<Transform> t(new Transform);
  243. t->GetPrimitives().reserve(t0->GetPrimitives().size());
  244. for (size_t i = 0; i < prim0.size(); i++)
  245. {
  246. TransformPrimitive p = prim0[i];
  247. if (!TransformUtilities::InterpolateWith(p, prim1[i], alpha))
  248. {
  249. RMLUI_ERRORMSG("Transform primitives can not be interpolated. Were the transforms properly prepared for interpolation?");
  250. return Property{t0, Unit::TRANSFORM};
  251. }
  252. t->AddPrimitive(p);
  253. }
  254. return Property{TransformPtr(std::move(t)), Unit::TRANSFORM};
  255. }
  256. if (p0.unit == Unit::DECORATOR && p1.unit == Unit::DECORATOR)
  257. {
  258. auto GetEffectDeclarationView = [](const Vector<DecoratorDeclaration>& declarations, size_t i, Element& element) -> EffectDeclarationView {
  259. if (i >= declarations.size())
  260. return EffectDeclarationView();
  261. const DecoratorDeclaration& declaration = declarations[i];
  262. if (declaration.instancer)
  263. return EffectDeclarationView(declaration);
  264. // If we don't have a decorator instancer, then this should be a named @decorator, look for one now.
  265. const StyleSheet* style_sheet = element.GetStyleSheet();
  266. if (!style_sheet)
  267. return EffectDeclarationView();
  268. const NamedDecorator* named_decorator = style_sheet->GetNamedDecorator(declaration.type);
  269. if (!named_decorator)
  270. {
  271. Log::Message(Log::LT_WARNING, "Could not find a named @decorator '%s'.", declaration.type.c_str());
  272. return EffectDeclarationView();
  273. }
  274. return EffectDeclarationView(named_decorator);
  275. };
  276. auto& ptr0 = p0.value.GetReference<DecoratorsPtr>();
  277. auto& ptr1 = p1.value.GetReference<DecoratorsPtr>();
  278. if (!ptr0 || !ptr1)
  279. {
  280. RMLUI_ERRORMSG("Invalid decorator pointer, were the decorator keys properly prepared?");
  281. return p_discrete;
  282. }
  283. // Build the new, interpolated decorator list.
  284. const bool p0_bigger = ptr0->list.size() > ptr1->list.size();
  285. auto& big_list = (p0_bigger ? ptr0->list : ptr1->list);
  286. auto decorator = MakeUnique<DecoratorDeclarationList>();
  287. auto& list = decorator->list;
  288. list.reserve(big_list.size());
  289. for (size_t i = 0; i < big_list.size(); i++)
  290. {
  291. EffectDeclarationView d0 = GetEffectDeclarationView(ptr0->list, i, element);
  292. EffectDeclarationView d1 = GetEffectDeclarationView(ptr1->list, i, element);
  293. const EffectDeclarationView& declaration = (p0_bigger ? d0 : d1);
  294. list.push_back(DecoratorDeclaration{*declaration.type, static_cast<DecoratorInstancer*>(declaration.instancer), PropertyDictionary(),
  295. declaration.paint_area});
  296. if (!InterpolateEffectProperties(list.back().properties, d0, d1, alpha, element))
  297. return p_discrete;
  298. }
  299. return Property{DecoratorsPtr(std::move(decorator)), Unit::DECORATOR};
  300. }
  301. if (p0.unit == Unit::FILTER && p1.unit == Unit::FILTER)
  302. {
  303. auto GetEffectDeclarationView = [](const Vector<FilterDeclaration>& declarations, size_t i) -> EffectDeclarationView {
  304. if (i >= declarations.size())
  305. return EffectDeclarationView();
  306. return EffectDeclarationView(declarations[i]);
  307. };
  308. auto& ptr0 = p0.value.GetReference<FiltersPtr>();
  309. auto& ptr1 = p1.value.GetReference<FiltersPtr>();
  310. if (!ptr0 || !ptr1)
  311. {
  312. RMLUI_ERRORMSG("Invalid filter pointer, were the filter keys properly prepared?");
  313. return p_discrete;
  314. }
  315. // Build the new, interpolated filter list.
  316. const bool p0_bigger = ptr0->list.size() > ptr1->list.size();
  317. auto& big_list = (p0_bigger ? ptr0->list : ptr1->list);
  318. auto filter = MakeUnique<FilterDeclarationList>();
  319. auto& list = filter->list;
  320. list.reserve(big_list.size());
  321. for (size_t i = 0; i < big_list.size(); i++)
  322. {
  323. EffectDeclarationView d0 = GetEffectDeclarationView(ptr0->list, i);
  324. EffectDeclarationView d1 = GetEffectDeclarationView(ptr1->list, i);
  325. const EffectDeclarationView& declaration = (p0_bigger ? d0 : d1);
  326. list.push_back(FilterDeclaration{*declaration.type, static_cast<FilterInstancer*>(declaration.instancer), PropertyDictionary()});
  327. if (!InterpolateEffectProperties(list.back().properties, d0, d1, alpha, element))
  328. return p_discrete;
  329. }
  330. return Property{FiltersPtr(std::move(filter)), Unit::FILTER};
  331. }
  332. if (p0.unit == Unit::COLORSTOPLIST && p1.unit == Unit::COLORSTOPLIST)
  333. {
  334. RMLUI_ASSERT(p0.value.GetType() == Variant::COLORSTOPLIST && p1.value.GetType() == Variant::COLORSTOPLIST);
  335. const auto& c0 = p0.value.GetReference<ColorStopList>();
  336. const auto& c1 = p1.value.GetReference<ColorStopList>();
  337. if (c0.size() != c1.size())
  338. return p_discrete;
  339. const size_t N = c0.size();
  340. ColorStopList result(N);
  341. for (size_t i = 0; i < N; i++)
  342. {
  343. result[i].color = InterpolateColour(c0[i].color.ToNonPremultiplied(), c1[i].color.ToNonPremultiplied(), alpha).ToPremultiplied();
  344. // We don't provide the property definition in the following, because it doesn't actually represent how
  345. // percentages are resolved for stop positions. Here, we don't trivially know how they are resolved, so if
  346. // users try to mix lengths and percentages, we instead fall back to discrete interpolation. See the
  347. // gradient decorators for how stop positions are resolved.
  348. result[i].position = InterpolateNumericValue(c0[i].position, c1[i].position, alpha, element, nullptr);
  349. }
  350. return Property{std::move(result), Unit::COLORSTOPLIST};
  351. }
  352. // Fall back to discrete interpolation for incompatible units.
  353. return p_discrete;
  354. }
  355. enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 };
  356. static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element)
  357. {
  358. using namespace Transforms;
  359. // Insert or modify primitives such that the two transforms match exactly in both number of and types of primitives.
  360. // Based largely on https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  361. auto& prims0 = t0.GetPrimitives();
  362. auto& prims1 = t1.GetPrimitives();
  363. // Check for trivial case where they contain the same primitives
  364. if (prims0.size() == prims1.size())
  365. {
  366. PrepareTransformResult result = PrepareTransformResult::Unchanged;
  367. bool same_primitives = true;
  368. for (size_t i = 0; i < prims0.size(); i++)
  369. {
  370. auto p0_type = prims0[i].type;
  371. auto p1_type = prims1[i].type;
  372. // See if they are the same or can be converted to a matching generic type.
  373. if (TransformUtilities::TryConvertToMatchingGenericType(prims0[i], prims1[i]))
  374. {
  375. if (prims0[i].type != p0_type)
  376. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT0);
  377. if (prims1[i].type != p1_type)
  378. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT1);
  379. }
  380. else
  381. {
  382. same_primitives = false;
  383. break;
  384. }
  385. }
  386. if (same_primitives)
  387. return result;
  388. }
  389. if (prims0.size() != prims1.size())
  390. {
  391. // Try to match the smallest set of primitives to the larger set, set missing keys in the small set to identity.
  392. // Requirement: The small set must match types in the same order they appear in the big set.
  393. // Example: (letter indicates type, number represents values)
  394. // big: a0 b0 c0 b1
  395. // ^ ^
  396. // small: b2 b3
  397. // ^ ^
  398. // new small: a1 b2 c1 b3
  399. bool prims0_smallest = (prims0.size() < prims1.size());
  400. auto& small = (prims0_smallest ? prims0 : prims1);
  401. auto& big = (prims0_smallest ? prims1 : prims0);
  402. Vector<size_t> matching_indices; // Indices into 'big' for matching types
  403. matching_indices.reserve(small.size() + 1);
  404. size_t i_big = 0;
  405. bool match_success = true;
  406. bool changed_big = false;
  407. // Iterate through the small set to see if its types fit into the big set
  408. for (size_t i_small = 0; i_small < small.size(); i_small++)
  409. {
  410. match_success = false;
  411. for (; i_big < big.size(); i_big++)
  412. {
  413. auto big_type = big[i_big].type;
  414. if (TransformUtilities::TryConvertToMatchingGenericType(small[i_small], big[i_big]))
  415. {
  416. // They matched exactly or in their more generic form. One or both primitives may have been converted.
  417. if (big[i_big].type != big_type)
  418. changed_big = true;
  419. matching_indices.push_back(i_big);
  420. match_success = true;
  421. i_big += 1;
  422. break;
  423. }
  424. }
  425. if (!match_success)
  426. break;
  427. }
  428. if (match_success)
  429. {
  430. // Success, insert the missing primitives into the small set
  431. matching_indices.push_back(big.size()); // Needed to copy elements behind the last matching primitive
  432. small.reserve(big.size());
  433. size_t i0 = 0;
  434. for (size_t match_index : matching_indices)
  435. {
  436. for (size_t i = i0; i < match_index; i++)
  437. {
  438. TransformPrimitive p = big[i];
  439. TransformUtilities::SetIdentity(p);
  440. small.insert(small.begin() + i, p);
  441. }
  442. // Next value to copy is one-past the matching primitive
  443. i0 = match_index + 1;
  444. }
  445. // The small set has always been changed if we get here, but the big set is only changed
  446. // if one or more of its primitives were converted to a general form.
  447. if (changed_big)
  448. return PrepareTransformResult::ChangedT0andT1;
  449. return (prims0_smallest ? PrepareTransformResult::ChangedT0 : PrepareTransformResult::ChangedT1);
  450. }
  451. }
  452. // If we get here, things get tricky. Need to do full matrix interpolation.
  453. // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components.
  454. // Then, during update, interpolate these components and combine into a new transform matrix.
  455. if (!CombineAndDecompose(t0, element))
  456. return PrepareTransformResult::Invalid;
  457. if (!CombineAndDecompose(t1, element))
  458. return PrepareTransformResult::Invalid;
  459. return PrepareTransformResult::ChangedT0andT1;
  460. }
  461. static bool PrepareTransforms(Vector<AnimationKey>& keys, Element& element, int start_index)
  462. {
  463. bool result = true;
  464. // Prepare each transform individually.
  465. for (int i = start_index; i < (int)keys.size(); i++)
  466. {
  467. Property& property = keys[i].property;
  468. RMLUI_ASSERT(property.value.GetType() == Variant::TRANSFORMPTR);
  469. if (!property.value.GetReference<TransformPtr>())
  470. property.value = MakeShared<Transform>();
  471. bool must_decompose = false;
  472. Transform& transform = *property.value.GetReference<TransformPtr>();
  473. for (TransformPrimitive& primitive : transform.GetPrimitives())
  474. {
  475. if (!TransformUtilities::PrepareForInterpolation(primitive, element))
  476. {
  477. must_decompose = true;
  478. break;
  479. }
  480. }
  481. if (must_decompose)
  482. result &= CombineAndDecompose(transform, element);
  483. }
  484. if (!result)
  485. return false;
  486. // We don't need to prepare the transforms pairwise if we only have a single key added so far.
  487. if (keys.size() < 2 || start_index < 1)
  488. return true;
  489. // Now, prepare the transforms pair-wise so they can be interpolated.
  490. const int N = (int)keys.size();
  491. int count_iterations = -1;
  492. const int max_iterations = 3 * N;
  493. Vector<bool> dirty_list(N + 1, false);
  494. dirty_list[start_index] = true;
  495. // For each pair of keys, match the transform primitives such that they can be interpolated during animation update
  496. for (int i = start_index; i < N && count_iterations < max_iterations; count_iterations++)
  497. {
  498. if (!dirty_list[i])
  499. {
  500. ++i;
  501. continue;
  502. }
  503. auto& prop0 = keys[i - 1].property;
  504. auto& prop1 = keys[i].property;
  505. if (prop0.unit != Unit::TRANSFORM || prop1.unit != Unit::TRANSFORM)
  506. return false;
  507. auto& t0 = prop0.value.GetReference<TransformPtr>();
  508. auto& t1 = prop1.value.GetReference<TransformPtr>();
  509. auto prepare_result = PrepareTransformPair(*t0, *t1, element);
  510. if (prepare_result == PrepareTransformResult::Invalid)
  511. return false;
  512. bool changed_t0 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT0);
  513. bool changed_t1 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT1);
  514. dirty_list[i] = false;
  515. dirty_list[i - 1] = dirty_list[i - 1] || changed_t0;
  516. dirty_list[i + 1] = dirty_list[i + 1] || changed_t1;
  517. if (changed_t0 && i > 1)
  518. --i;
  519. else
  520. ++i;
  521. }
  522. // Something has probably gone wrong if we exceeded max_iterations, possibly a bug in PrepareTransformPair()
  523. return (count_iterations < max_iterations);
  524. }
  525. static void PrepareDecorator(AnimationKey& key)
  526. {
  527. Property& property = key.property;
  528. RMLUI_ASSERT(property.value.GetType() == Variant::DECORATORSPTR);
  529. if (!property.value.GetReference<DecoratorsPtr>())
  530. property.value = MakeShared<DecoratorDeclarationList>();
  531. }
  532. static void PrepareFilter(AnimationKey& key)
  533. {
  534. Property& property = key.property;
  535. RMLUI_ASSERT(property.value.GetType() == Variant::FILTERSPTR);
  536. if (!property.value.GetReference<FiltersPtr>())
  537. property.value = MakeShared<FilterDeclarationList>();
  538. }
  539. ElementAnimation::ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element,
  540. double start_world_time, float duration, int num_iterations, bool alternate_direction) :
  541. property_id(property_id), duration(duration), num_iterations(num_iterations), alternate_direction(alternate_direction),
  542. last_update_world_time(start_world_time), origin(origin)
  543. {
  544. if (!current_value.definition)
  545. {
  546. Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').",
  547. current_value.ToString().c_str());
  548. }
  549. InternalAddKey(0.0f, current_value, element, Tween{});
  550. }
  551. bool ElementAnimation::InternalAddKey(float time, const Property& in_property, Element& element, Tween tween)
  552. {
  553. const Units valid_units =
  554. (Unit::NUMBER_LENGTH_PERCENT | Unit::ANGLE | Unit::COLOUR | Unit::TRANSFORM | Unit::KEYWORD | Unit::DECORATOR | Unit::FILTER);
  555. if (!Any(in_property.unit & valid_units))
  556. {
  557. const char* property_type = (in_property.unit == Unit::BOXSHADOWLIST ? "Box shadows do not" : "Property value does not");
  558. Log::Message(Log::LT_WARNING, "%s support animations or transitions. Value: %s", property_type, in_property.ToString().c_str());
  559. return false;
  560. }
  561. keys.emplace_back(time, in_property, tween);
  562. Property& property = keys.back().property;
  563. bool result = true;
  564. if (property.unit == Unit::TRANSFORM)
  565. {
  566. result = PrepareTransforms(keys, element, (int)keys.size() - 1);
  567. }
  568. else if (property.unit == Unit::DECORATOR)
  569. {
  570. PrepareDecorator(keys.back());
  571. }
  572. else if (property.unit == Unit::FILTER)
  573. {
  574. PrepareFilter(keys.back());
  575. }
  576. if (!result)
  577. {
  578. Log::Message(Log::LT_WARNING, "Could not add animation key with property '%s'.", in_property.ToString().c_str());
  579. keys.pop_back();
  580. }
  581. return result;
  582. }
  583. bool ElementAnimation::AddKey(float target_time, const Property& in_property, Element& element, Tween tween, bool extend_duration)
  584. {
  585. if (!IsInitalized())
  586. {
  587. Log::Message(Log::LT_WARNING, "Element animation was not initialized properly, can't add key.");
  588. return false;
  589. }
  590. if (!InternalAddKey(target_time, in_property, element, tween))
  591. {
  592. return false;
  593. }
  594. if (extend_duration)
  595. duration = target_time;
  596. return true;
  597. }
  598. float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_key1) const
  599. {
  600. float t = time_since_iteration_start;
  601. if (reverse_direction)
  602. t = duration - t;
  603. int key0 = -1;
  604. int key1 = -1;
  605. {
  606. for (int i = 0; i < (int)keys.size(); i++)
  607. {
  608. if (keys[i].time >= t)
  609. {
  610. key1 = i;
  611. break;
  612. }
  613. }
  614. if (key1 < 0)
  615. key1 = (int)keys.size() - 1;
  616. key0 = (key1 == 0 ? 0 : key1 - 1);
  617. }
  618. RMLUI_ASSERT(key0 >= 0 && key0 < (int)keys.size() && key1 >= 0 && key1 < (int)keys.size());
  619. float alpha = 0.0f;
  620. {
  621. const float t0 = keys[key0].time;
  622. const float t1 = keys[key1].time;
  623. const float eps = 1e-3f;
  624. if (t1 - t0 > eps)
  625. alpha = (t - t0) / (t1 - t0);
  626. alpha = Math::Clamp(alpha, 0.0f, 1.0f);
  627. }
  628. alpha = keys[key1].tween(alpha);
  629. if (out_key0)
  630. *out_key0 = key0;
  631. if (out_key1)
  632. *out_key1 = key1;
  633. return alpha;
  634. }
  635. Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& element)
  636. {
  637. float dt = float(world_time - last_update_world_time);
  638. if (keys.size() < 2 || animation_complete || dt <= 0.0f)
  639. return Property{};
  640. dt = Math::Min(dt, 0.1f);
  641. last_update_world_time = world_time;
  642. time_since_iteration_start += dt;
  643. if (time_since_iteration_start >= duration)
  644. {
  645. // Next iteration
  646. current_iteration += 1;
  647. if (num_iterations == -1 || (current_iteration >= 0 && current_iteration < num_iterations))
  648. {
  649. time_since_iteration_start -= duration;
  650. if (alternate_direction)
  651. reverse_direction = !reverse_direction;
  652. }
  653. else
  654. {
  655. animation_complete = true;
  656. time_since_iteration_start = duration;
  657. }
  658. }
  659. int key0 = -1;
  660. int key1 = -1;
  661. float alpha = GetInterpolationFactorAndKeys(&key0, &key1);
  662. Property result = InterpolateProperties(keys[key0].property, keys[key1].property, alpha, element, keys[0].property.definition);
  663. return result;
  664. }
  665. } // namespace Rml