ElementAnimation.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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/Decorator.h"
  30. #include "../../Include/RmlUi/Core/Element.h"
  31. #include "../../Include/RmlUi/Core/Factory.h"
  32. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  33. #include "../../Include/RmlUi/Core/PropertySpecification.h"
  34. #include "../../Include/RmlUi/Core/StyleSheet.h"
  35. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  36. #include "../../Include/RmlUi/Core/StyleSheetTypes.h"
  37. #include "../../Include/RmlUi/Core/Transform.h"
  38. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  39. #include "ElementStyle.h"
  40. #include "TransformUtilities.h"
  41. namespace Rml {
  42. static Colourf ColourToLinearSpace(Colourb c)
  43. {
  44. Colourf result;
  45. // Approximate inverse sRGB function
  46. result.red = c.red / 255.f;
  47. result.red *= result.red;
  48. result.green = c.green / 255.f;
  49. result.green *= result.green;
  50. result.blue = c.blue / 255.f;
  51. result.blue *= result.blue;
  52. result.alpha = c.alpha / 255.f;
  53. return result;
  54. }
  55. static Colourb ColourFromLinearSpace(Colourf c)
  56. {
  57. Colourb result;
  58. result.red = (byte)Math::Clamp(Math::SquareRoot(c.red) * 255.f, 0.0f, 255.f);
  59. result.green = (byte)Math::Clamp(Math::SquareRoot(c.green) * 255.f, 0.0f, 255.f);
  60. result.blue = (byte)Math::Clamp(Math::SquareRoot(c.blue) * 255.f, 0.0f, 255.f);
  61. result.alpha = (byte)Math::Clamp(c.alpha * 255.f, 0.0f, 255.f);
  62. return result;
  63. }
  64. // Merges all the primitives to a single DecomposedMatrix4 primitive
  65. static bool CombineAndDecompose(Transform& t, Element& e)
  66. {
  67. Matrix4f m = Matrix4f::Identity();
  68. for (TransformPrimitive& primitive : t.GetPrimitives())
  69. {
  70. Matrix4f m_primitive = TransformUtilities::ResolveTransform(primitive, e);
  71. m *= m_primitive;
  72. }
  73. Transforms::DecomposedMatrix4 decomposed;
  74. if (!TransformUtilities::Decompose(decomposed, m))
  75. return false;
  76. t.ClearPrimitives();
  77. t.AddPrimitive(decomposed);
  78. return true;
  79. }
  80. static Property InterpolateProperties(const Property& p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition)
  81. {
  82. if (Any(p0.unit & Unit::NUMBER_LENGTH_PERCENT) && Any(p1.unit & Unit::NUMBER_LENGTH_PERCENT))
  83. {
  84. if (p0.unit == p1.unit || !definition)
  85. {
  86. // If we have the same units, we can just interpolate regardless of what the value represents.
  87. // Or if we have distinct units but no definition, all bets are off. This shouldn't occur, just interpolate values.
  88. float f0 = p0.value.Get<float>();
  89. float f1 = p1.value.Get<float>();
  90. float f = (1.0f - alpha) * f0 + alpha * f1;
  91. return Property{f, p0.unit};
  92. }
  93. else
  94. {
  95. // Otherwise, convert units to pixels.
  96. float f0 = element.GetStyle()->ResolveRelativeLength(p0.GetNumericValue(), definition->GetRelativeTarget());
  97. float f1 = element.GetStyle()->ResolveRelativeLength(p1.GetNumericValue(), definition->GetRelativeTarget());
  98. float f = (1.0f - alpha) * f0 + alpha * f1;
  99. return Property{f, Unit::PX};
  100. }
  101. }
  102. if (p0.unit == Unit::KEYWORD && p1.unit == Unit::KEYWORD)
  103. {
  104. // Discrete interpolation, swap at alpha = 0.5.
  105. // Special case for the 'visibility' property as in the CSS specs:
  106. // Apply the visible property if present during the entire transition period, ie. alpha (0,1).
  107. if (definition && definition->GetId() == PropertyId::Visibility)
  108. {
  109. if (p0.Get<int>() == (int)Style::Visibility::Visible)
  110. return alpha < 1.f ? p0 : p1;
  111. else if (p1.Get<int>() == (int)Style::Visibility::Visible)
  112. return alpha <= 0.f ? p0 : p1;
  113. }
  114. return alpha < 0.5f ? p0 : p1;
  115. }
  116. if (p0.unit == Unit::COLOUR && p1.unit == Unit::COLOUR)
  117. {
  118. Colourf c0 = ColourToLinearSpace(p0.value.Get<Colourb>());
  119. Colourf c1 = ColourToLinearSpace(p1.value.Get<Colourb>());
  120. Colourf c = c0 * (1.0f - alpha) + c1 * alpha;
  121. return Property{ColourFromLinearSpace(c), Unit::COLOUR};
  122. }
  123. if (p0.unit == Unit::TRANSFORM && p1.unit == Unit::TRANSFORM)
  124. {
  125. auto& t0 = p0.value.GetReference<TransformPtr>();
  126. auto& t1 = p1.value.GetReference<TransformPtr>();
  127. const auto& prim0 = t0->GetPrimitives();
  128. const auto& prim1 = t1->GetPrimitives();
  129. if (prim0.size() != prim1.size())
  130. {
  131. RMLUI_ERRORMSG("Transform primitives not of same size during interpolation. Were the transforms properly prepared for interpolation?");
  132. return Property{t0, Unit::TRANSFORM};
  133. }
  134. // Build the new, interpolating transform
  135. UniquePtr<Transform> t(new Transform);
  136. t->GetPrimitives().reserve(t0->GetPrimitives().size());
  137. for (size_t i = 0; i < prim0.size(); i++)
  138. {
  139. TransformPrimitive p = prim0[i];
  140. if (!TransformUtilities::InterpolateWith(p, prim1[i], alpha))
  141. {
  142. RMLUI_ERRORMSG("Transform primitives can not be interpolated. Were the transforms properly prepared for interpolation?");
  143. return Property{t0, Unit::TRANSFORM};
  144. }
  145. t->AddPrimitive(p);
  146. }
  147. return Property{TransformPtr(std::move(t)), Unit::TRANSFORM};
  148. }
  149. struct DecoratorDeclarationView {
  150. DecoratorDeclarationView(const DecoratorDeclaration& declaration) :
  151. type(declaration.type), instancer(declaration.instancer), properties(declaration.properties)
  152. {}
  153. DecoratorDeclarationView(const NamedDecorator* specification) :
  154. type(specification->type), instancer(Factory::GetDecoratorInstancer(specification->type)), properties(specification->properties)
  155. {}
  156. const String& type;
  157. DecoratorInstancer* instancer;
  158. const PropertyDictionary& properties;
  159. };
  160. if (p0.unit == Unit::DECORATOR && p1.unit == Unit::DECORATOR)
  161. {
  162. auto DiscreteInterpolation = [&]() { return alpha < 0.5f ? p0 : p1; };
  163. // If we have an instancer we pass that directly to the declaration view, otherwise look for a named @decorator.
  164. auto GetDecoratorDeclarationView = [&](const DecoratorDeclaration& declaration) -> DecoratorDeclarationView {
  165. if (declaration.instancer)
  166. return DecoratorDeclarationView{declaration};
  167. const StyleSheet* style_sheet = element.GetStyleSheet();
  168. if (!style_sheet)
  169. return DecoratorDeclarationView{declaration};
  170. const NamedDecorator* named_decorator = style_sheet->GetNamedDecorator(declaration.type);
  171. if (!named_decorator)
  172. {
  173. Log::Message(Log::LT_WARNING, "Could not find a named @decorator '%s'.", declaration.type.c_str());
  174. return DecoratorDeclarationView{declaration};
  175. }
  176. return DecoratorDeclarationView{named_decorator};
  177. };
  178. auto& ptr0 = p0.value.GetReference<DecoratorsPtr>();
  179. auto& ptr1 = p1.value.GetReference<DecoratorsPtr>();
  180. if (!ptr0 || !ptr1)
  181. {
  182. RMLUI_ERRORMSG("Invalid decorator pointer, were the decorator keys properly prepared?");
  183. return DiscreteInterpolation();
  184. }
  185. const bool p0_smaller = (ptr0->list.size() < ptr1->list.size());
  186. auto& small = (p0_smaller ? ptr0->list : ptr1->list);
  187. auto& big = (p0_smaller ? ptr1->list : ptr0->list);
  188. // Build the new, interpolated decorator.
  189. UniquePtr<DecoratorDeclarationList> decorator(new DecoratorDeclarationList);
  190. decorator->list.reserve(ptr0->list.size());
  191. // Interpolate decorators that have common types.
  192. for (size_t i = 0; i < small.size(); i++)
  193. {
  194. DecoratorDeclarationView d0_view{GetDecoratorDeclarationView(ptr0->list[i])};
  195. DecoratorDeclarationView d1_view{GetDecoratorDeclarationView(ptr1->list[i])};
  196. if (!d0_view.instancer || !d1_view.instancer)
  197. return DiscreteInterpolation();
  198. if (d0_view.instancer != d1_view.instancer || d0_view.type != d1_view.type ||
  199. d0_view.properties.GetNumProperties() != d1_view.properties.GetNumProperties())
  200. {
  201. // Incompatible decorators, fall back to discrete interpolation.
  202. return DiscreteInterpolation();
  203. }
  204. decorator->list.push_back(DecoratorDeclaration{d0_view.type, d0_view.instancer, PropertyDictionary()});
  205. PropertyDictionary& props = decorator->list.back().properties;
  206. const auto& props0 = d0_view.properties.GetProperties();
  207. const auto& props1 = d1_view.properties.GetProperties();
  208. for (const auto& pair0 : props0)
  209. {
  210. const PropertyId id = pair0.first;
  211. const Property& prop0 = pair0.second;
  212. auto it = props1.find(id);
  213. if (it == props1.end())
  214. {
  215. RMLUI_ERRORMSG("Incompatible decorator properties.");
  216. return DiscreteInterpolation();
  217. }
  218. const Property& prop1 = it->second;
  219. Property p = InterpolateProperties(prop0, prop1, alpha, element, prop0.definition);
  220. p.definition = prop0.definition;
  221. props.SetProperty(id, p);
  222. }
  223. }
  224. // Append any trailing decorators from the largest list and interpolate against the default values of its type.
  225. for (size_t i = small.size(); i < big.size(); i++)
  226. {
  227. DecoratorDeclarationView dbig_view{GetDecoratorDeclarationView(big[i])};
  228. if (!dbig_view.instancer)
  229. return DiscreteInterpolation();
  230. decorator->list.push_back(DecoratorDeclaration{dbig_view.type, dbig_view.instancer, PropertyDictionary()});
  231. DecoratorDeclaration& d_new = decorator->list.back();
  232. const PropertySpecification& specification = d_new.instancer->GetPropertySpecification();
  233. const PropertyMap& props_big = dbig_view.properties.GetProperties();
  234. for (const auto& pair_big : props_big)
  235. {
  236. const PropertyId id = pair_big.first;
  237. const PropertyDefinition* underlying_definition = specification.GetProperty(id);
  238. if (!underlying_definition)
  239. return DiscreteInterpolation();
  240. const Property& p_big = pair_big.second;
  241. const Property& p_small = *underlying_definition->GetDefaultValue();
  242. const Property& p_interp0 = (p0_smaller ? p_small : p_big);
  243. const Property& p_interp1 = (p0_smaller ? p_big : p_small);
  244. Property p = InterpolateProperties(p_interp0, p_interp1, alpha, element, p_big.definition);
  245. p.definition = p_big.definition;
  246. d_new.properties.SetProperty(id, p);
  247. }
  248. }
  249. return Property{DecoratorsPtr(std::move(decorator)), Unit::DECORATOR};
  250. }
  251. // Fall back to discrete interpolation for incompatible units.
  252. return alpha < 0.5f ? p0 : p1;
  253. }
  254. enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 };
  255. static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element)
  256. {
  257. using namespace Transforms;
  258. // Insert or modify primitives such that the two transforms match exactly in both number of and types of primitives.
  259. // Based largely on https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  260. auto& prims0 = t0.GetPrimitives();
  261. auto& prims1 = t1.GetPrimitives();
  262. // Check for trivial case where they contain the same primitives
  263. if (prims0.size() == prims1.size())
  264. {
  265. PrepareTransformResult result = PrepareTransformResult::Unchanged;
  266. bool same_primitives = true;
  267. for (size_t i = 0; i < prims0.size(); i++)
  268. {
  269. auto p0_type = prims0[i].type;
  270. auto p1_type = prims1[i].type;
  271. // See if they are the same or can be converted to a matching generic type.
  272. if (TransformUtilities::TryConvertToMatchingGenericType(prims0[i], prims1[i]))
  273. {
  274. if (prims0[i].type != p0_type)
  275. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT0);
  276. if (prims1[i].type != p1_type)
  277. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT1);
  278. }
  279. else
  280. {
  281. same_primitives = false;
  282. break;
  283. }
  284. }
  285. if (same_primitives)
  286. return result;
  287. }
  288. if (prims0.size() != prims1.size())
  289. {
  290. // Try to match the smallest set of primitives to the larger set, set missing keys in the small set to identity.
  291. // Requirement: The small set must match types in the same order they appear in the big set.
  292. // Example: (letter indicates type, number represents values)
  293. // big: a0 b0 c0 b1
  294. // ^ ^
  295. // small: b2 b3
  296. // ^ ^
  297. // new small: a1 b2 c1 b3
  298. bool prims0_smallest = (prims0.size() < prims1.size());
  299. auto& small = (prims0_smallest ? prims0 : prims1);
  300. auto& big = (prims0_smallest ? prims1 : prims0);
  301. Vector<size_t> matching_indices; // Indices into 'big' for matching types
  302. matching_indices.reserve(small.size() + 1);
  303. size_t i_big = 0;
  304. bool match_success = true;
  305. bool changed_big = false;
  306. // Iterate through the small set to see if its types fit into the big set
  307. for (size_t i_small = 0; i_small < small.size(); i_small++)
  308. {
  309. match_success = false;
  310. for (; i_big < big.size(); i_big++)
  311. {
  312. auto big_type = big[i_big].type;
  313. if (TransformUtilities::TryConvertToMatchingGenericType(small[i_small], big[i_big]))
  314. {
  315. // They matched exactly or in their more generic form. One or both primitives may have been converted.
  316. match_success = true;
  317. if (big[i_big].type != big_type)
  318. changed_big = true;
  319. }
  320. if (match_success)
  321. {
  322. matching_indices.push_back(i_big);
  323. match_success = true;
  324. i_big += 1;
  325. break;
  326. }
  327. }
  328. if (!match_success)
  329. break;
  330. }
  331. if (match_success)
  332. {
  333. // Success, insert the missing primitives into the small set
  334. matching_indices.push_back(big.size()); // Needed to copy elements behind the last matching primitive
  335. small.reserve(big.size());
  336. size_t i0 = 0;
  337. for (size_t match_index : matching_indices)
  338. {
  339. for (size_t i = i0; i < match_index; i++)
  340. {
  341. TransformPrimitive p = big[i];
  342. TransformUtilities::SetIdentity(p);
  343. small.insert(small.begin() + i, p);
  344. }
  345. // Next value to copy is one-past the matching primitive
  346. i0 = match_index + 1;
  347. }
  348. // The small set has always been changed if we get here, but the big set is only changed
  349. // if one or more of its primitives were converted to a general form.
  350. if (changed_big)
  351. return PrepareTransformResult::ChangedT0andT1;
  352. return (prims0_smallest ? PrepareTransformResult::ChangedT0 : PrepareTransformResult::ChangedT1);
  353. }
  354. }
  355. // If we get here, things get tricky. Need to do full matrix interpolation.
  356. // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components.
  357. // Then, during update, interpolate these components and combine into a new transform matrix.
  358. if (!CombineAndDecompose(t0, element))
  359. return PrepareTransformResult::Invalid;
  360. if (!CombineAndDecompose(t1, element))
  361. return PrepareTransformResult::Invalid;
  362. return PrepareTransformResult::ChangedT0andT1;
  363. }
  364. static bool PrepareTransforms(Vector<AnimationKey>& keys, Element& element, int start_index)
  365. {
  366. bool result = true;
  367. // Prepare each transform individually.
  368. for (int i = start_index; i < (int)keys.size(); i++)
  369. {
  370. Property& property = keys[i].property;
  371. RMLUI_ASSERT(property.value.GetType() == Variant::TRANSFORMPTR);
  372. if (!property.value.GetReference<TransformPtr>())
  373. property.value = MakeShared<Transform>();
  374. bool must_decompose = false;
  375. Transform& transform = *property.value.GetReference<TransformPtr>();
  376. for (TransformPrimitive& primitive : transform.GetPrimitives())
  377. {
  378. if (!TransformUtilities::PrepareForInterpolation(primitive, element))
  379. {
  380. must_decompose = true;
  381. break;
  382. }
  383. }
  384. if (must_decompose)
  385. result &= CombineAndDecompose(transform, element);
  386. }
  387. if (!result)
  388. return false;
  389. // We don't need to prepare the transforms pairwise if we only have a single key added so far.
  390. if (keys.size() < 2 || start_index < 1)
  391. return true;
  392. // Now, prepare the transforms pair-wise so they can be interpolated.
  393. const int N = (int)keys.size();
  394. int count_iterations = -1;
  395. const int max_iterations = 3 * N;
  396. Vector<bool> dirty_list(N + 1, false);
  397. dirty_list[start_index] = true;
  398. // For each pair of keys, match the transform primitives such that they can be interpolated during animation update
  399. for (int i = start_index; i < N && count_iterations < max_iterations; count_iterations++)
  400. {
  401. if (!dirty_list[i])
  402. {
  403. ++i;
  404. continue;
  405. }
  406. auto& prop0 = keys[i - 1].property;
  407. auto& prop1 = keys[i].property;
  408. if (prop0.unit != Unit::TRANSFORM || prop1.unit != Unit::TRANSFORM)
  409. return false;
  410. auto& t0 = prop0.value.GetReference<TransformPtr>();
  411. auto& t1 = prop1.value.GetReference<TransformPtr>();
  412. auto prepare_result = PrepareTransformPair(*t0, *t1, element);
  413. if (prepare_result == PrepareTransformResult::Invalid)
  414. return false;
  415. bool changed_t0 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT0);
  416. bool changed_t1 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT1);
  417. dirty_list[i] = false;
  418. dirty_list[i - 1] = dirty_list[i - 1] || changed_t0;
  419. dirty_list[i + 1] = dirty_list[i + 1] || changed_t1;
  420. if (changed_t0 && i > 1)
  421. --i;
  422. else
  423. ++i;
  424. }
  425. // Something has probably gone wrong if we exceeded max_iterations, possibly a bug in PrepareTransformPair()
  426. return (count_iterations < max_iterations);
  427. }
  428. static void PrepareDecorator(AnimationKey& key)
  429. {
  430. Property& property = key.property;
  431. RMLUI_ASSERT(property.value.GetType() == Variant::DECORATORSPTR);
  432. if (!property.value.GetReference<DecoratorsPtr>())
  433. property.value = MakeShared<DecoratorDeclarationList>();
  434. }
  435. ElementAnimation::ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element,
  436. double start_world_time, float duration, int num_iterations, bool alternate_direction) :
  437. property_id(property_id),
  438. duration(duration), num_iterations(num_iterations), alternate_direction(alternate_direction), last_update_world_time(start_world_time),
  439. origin(origin)
  440. {
  441. if (!current_value.definition)
  442. {
  443. Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').",
  444. current_value.ToString().c_str());
  445. }
  446. InternalAddKey(0.0f, current_value, element, Tween{});
  447. }
  448. bool ElementAnimation::InternalAddKey(float time, const Property& in_property, Element& element, Tween tween)
  449. {
  450. const Units valid_units = (Unit::NUMBER_LENGTH_PERCENT | Unit::ANGLE | Unit::COLOUR | Unit::TRANSFORM | Unit::KEYWORD | Unit::DECORATOR);
  451. if (!Any(in_property.unit & valid_units))
  452. {
  453. Log::Message(Log::LT_WARNING, "Property value '%s' is not a valid target for interpolation.", in_property.ToString().c_str());
  454. return false;
  455. }
  456. keys.emplace_back(time, in_property, tween);
  457. bool result = true;
  458. if (keys.back().property.unit == Unit::TRANSFORM)
  459. {
  460. result = PrepareTransforms(keys, element, (int)keys.size() - 1);
  461. }
  462. else if (keys.back().property.unit == Unit::DECORATOR)
  463. {
  464. PrepareDecorator(keys.back());
  465. }
  466. if (!result)
  467. {
  468. Log::Message(Log::LT_WARNING, "Could not add animation key with property '%s'.", in_property.ToString().c_str());
  469. keys.pop_back();
  470. }
  471. return result;
  472. }
  473. bool ElementAnimation::AddKey(float target_time, const Property& in_property, Element& element, Tween tween, bool extend_duration)
  474. {
  475. if (!IsInitalized())
  476. {
  477. Log::Message(Log::LT_WARNING, "Element animation was not initialized properly, can't add key.");
  478. return false;
  479. }
  480. if (!InternalAddKey(target_time, in_property, element, tween))
  481. {
  482. return false;
  483. }
  484. if (extend_duration)
  485. duration = target_time;
  486. return true;
  487. }
  488. float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_key1) const
  489. {
  490. float t = time_since_iteration_start;
  491. if (reverse_direction)
  492. t = duration - t;
  493. int key0 = -1;
  494. int key1 = -1;
  495. {
  496. for (int i = 0; i < (int)keys.size(); i++)
  497. {
  498. if (keys[i].time >= t)
  499. {
  500. key1 = i;
  501. break;
  502. }
  503. }
  504. if (key1 < 0)
  505. key1 = (int)keys.size() - 1;
  506. key0 = (key1 == 0 ? 0 : key1 - 1);
  507. }
  508. RMLUI_ASSERT(key0 >= 0 && key0 < (int)keys.size() && key1 >= 0 && key1 < (int)keys.size());
  509. float alpha = 0.0f;
  510. {
  511. const float t0 = keys[key0].time;
  512. const float t1 = keys[key1].time;
  513. const float eps = 1e-3f;
  514. if (t1 - t0 > eps)
  515. alpha = (t - t0) / (t1 - t0);
  516. alpha = Math::Clamp(alpha, 0.0f, 1.0f);
  517. }
  518. alpha = keys[key1].tween(alpha);
  519. if (out_key0)
  520. *out_key0 = key0;
  521. if (out_key1)
  522. *out_key1 = key1;
  523. return alpha;
  524. }
  525. Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& element)
  526. {
  527. float dt = float(world_time - last_update_world_time);
  528. if (keys.size() < 2 || animation_complete || dt <= 0.0f)
  529. return Property{};
  530. dt = Math::Min(dt, 0.1f);
  531. last_update_world_time = world_time;
  532. time_since_iteration_start += dt;
  533. if (time_since_iteration_start >= duration)
  534. {
  535. // Next iteration
  536. current_iteration += 1;
  537. if (num_iterations == -1 || (current_iteration >= 0 && current_iteration < num_iterations))
  538. {
  539. time_since_iteration_start -= duration;
  540. if (alternate_direction)
  541. reverse_direction = !reverse_direction;
  542. }
  543. else
  544. {
  545. animation_complete = true;
  546. time_since_iteration_start = duration;
  547. }
  548. }
  549. int key0 = -1;
  550. int key1 = -1;
  551. float alpha = GetInterpolationFactorAndKeys(&key0, &key1);
  552. Property result = InterpolateProperties(keys[key0].property, keys[key1].property, alpha, element, keys[0].property.definition);
  553. return result;
  554. }
  555. } // namespace Rml