ElementAnimation.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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), paint_area(declaration.paint_area)
  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. BoxArea paint_area = BoxArea::Auto;
  160. };
  161. if (p0.unit == Unit::DECORATOR && p1.unit == Unit::DECORATOR)
  162. {
  163. auto DiscreteInterpolation = [&]() { return alpha < 0.5f ? p0 : p1; };
  164. // If we have an instancer we pass that directly to the declaration view, otherwise look for a named @decorator.
  165. auto GetDecoratorDeclarationView = [&](const DecoratorDeclaration& declaration) -> DecoratorDeclarationView {
  166. if (declaration.instancer)
  167. return DecoratorDeclarationView{declaration};
  168. const StyleSheet* style_sheet = element.GetStyleSheet();
  169. if (!style_sheet)
  170. return DecoratorDeclarationView{declaration};
  171. const NamedDecorator* named_decorator = style_sheet->GetNamedDecorator(declaration.type);
  172. if (!named_decorator)
  173. {
  174. Log::Message(Log::LT_WARNING, "Could not find a named @decorator '%s'.", declaration.type.c_str());
  175. return DecoratorDeclarationView{declaration};
  176. }
  177. return DecoratorDeclarationView{named_decorator};
  178. };
  179. auto& ptr0 = p0.value.GetReference<DecoratorsPtr>();
  180. auto& ptr1 = p1.value.GetReference<DecoratorsPtr>();
  181. if (!ptr0 || !ptr1)
  182. {
  183. RMLUI_ERRORMSG("Invalid decorator pointer, were the decorator keys properly prepared?");
  184. return DiscreteInterpolation();
  185. }
  186. const bool p0_smaller = (ptr0->list.size() < ptr1->list.size());
  187. auto& small = (p0_smaller ? ptr0->list : ptr1->list);
  188. auto& big = (p0_smaller ? ptr1->list : ptr0->list);
  189. // Build the new, interpolated decorator.
  190. UniquePtr<DecoratorDeclarationList> decorator(new DecoratorDeclarationList);
  191. decorator->list.reserve(ptr0->list.size());
  192. // Interpolate decorators that have common types.
  193. for (size_t i = 0; i < small.size(); i++)
  194. {
  195. DecoratorDeclarationView d0_view{GetDecoratorDeclarationView(ptr0->list[i])};
  196. DecoratorDeclarationView d1_view{GetDecoratorDeclarationView(ptr1->list[i])};
  197. if (!d0_view.instancer || !d1_view.instancer)
  198. return DiscreteInterpolation();
  199. if (d0_view.instancer != d1_view.instancer || d0_view.type != d1_view.type ||
  200. d0_view.properties.GetNumProperties() != d1_view.properties.GetNumProperties() || d0_view.paint_area != d1_view.paint_area)
  201. {
  202. // Incompatible decorators, fall back to discrete interpolation.
  203. return DiscreteInterpolation();
  204. }
  205. decorator->list.push_back(DecoratorDeclaration{d0_view.type, d0_view.instancer, PropertyDictionary(), d0_view.paint_area});
  206. PropertyDictionary& props = decorator->list.back().properties;
  207. const auto& props0 = d0_view.properties.GetProperties();
  208. const auto& props1 = d1_view.properties.GetProperties();
  209. for (const auto& pair0 : props0)
  210. {
  211. const PropertyId id = pair0.first;
  212. const Property& prop0 = pair0.second;
  213. auto it = props1.find(id);
  214. if (it == props1.end())
  215. {
  216. RMLUI_ERRORMSG("Incompatible decorator properties.");
  217. return DiscreteInterpolation();
  218. }
  219. const Property& prop1 = it->second;
  220. Property p = InterpolateProperties(prop0, prop1, alpha, element, prop0.definition);
  221. p.definition = prop0.definition;
  222. props.SetProperty(id, p);
  223. }
  224. }
  225. // Append any trailing decorators from the largest list and interpolate against the default values of its type.
  226. for (size_t i = small.size(); i < big.size(); i++)
  227. {
  228. DecoratorDeclarationView dbig_view{GetDecoratorDeclarationView(big[i])};
  229. if (!dbig_view.instancer)
  230. return DiscreteInterpolation();
  231. decorator->list.push_back(DecoratorDeclaration{dbig_view.type, dbig_view.instancer, PropertyDictionary(), dbig_view.paint_area});
  232. DecoratorDeclaration& d_new = decorator->list.back();
  233. const PropertySpecification& specification = d_new.instancer->GetPropertySpecification();
  234. const PropertyMap& props_big = dbig_view.properties.GetProperties();
  235. for (const auto& pair_big : props_big)
  236. {
  237. const PropertyId id = pair_big.first;
  238. const PropertyDefinition* underlying_definition = specification.GetProperty(id);
  239. if (!underlying_definition)
  240. return DiscreteInterpolation();
  241. const Property& p_big = pair_big.second;
  242. const Property& p_small = *underlying_definition->GetDefaultValue();
  243. const Property& p_interp0 = (p0_smaller ? p_small : p_big);
  244. const Property& p_interp1 = (p0_smaller ? p_big : p_small);
  245. Property p = InterpolateProperties(p_interp0, p_interp1, alpha, element, p_big.definition);
  246. p.definition = p_big.definition;
  247. d_new.properties.SetProperty(id, p);
  248. }
  249. }
  250. return Property{DecoratorsPtr(std::move(decorator)), Unit::DECORATOR};
  251. }
  252. // Fall back to discrete interpolation for incompatible units.
  253. return alpha < 0.5f ? p0 : p1;
  254. }
  255. enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 };
  256. static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element)
  257. {
  258. using namespace Transforms;
  259. // Insert or modify primitives such that the two transforms match exactly in both number of and types of primitives.
  260. // Based largely on https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  261. auto& prims0 = t0.GetPrimitives();
  262. auto& prims1 = t1.GetPrimitives();
  263. // Check for trivial case where they contain the same primitives
  264. if (prims0.size() == prims1.size())
  265. {
  266. PrepareTransformResult result = PrepareTransformResult::Unchanged;
  267. bool same_primitives = true;
  268. for (size_t i = 0; i < prims0.size(); i++)
  269. {
  270. auto p0_type = prims0[i].type;
  271. auto p1_type = prims1[i].type;
  272. // See if they are the same or can be converted to a matching generic type.
  273. if (TransformUtilities::TryConvertToMatchingGenericType(prims0[i], prims1[i]))
  274. {
  275. if (prims0[i].type != p0_type)
  276. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT0);
  277. if (prims1[i].type != p1_type)
  278. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT1);
  279. }
  280. else
  281. {
  282. same_primitives = false;
  283. break;
  284. }
  285. }
  286. if (same_primitives)
  287. return result;
  288. }
  289. if (prims0.size() != prims1.size())
  290. {
  291. // Try to match the smallest set of primitives to the larger set, set missing keys in the small set to identity.
  292. // Requirement: The small set must match types in the same order they appear in the big set.
  293. // Example: (letter indicates type, number represents values)
  294. // big: a0 b0 c0 b1
  295. // ^ ^
  296. // small: b2 b3
  297. // ^ ^
  298. // new small: a1 b2 c1 b3
  299. bool prims0_smallest = (prims0.size() < prims1.size());
  300. auto& small = (prims0_smallest ? prims0 : prims1);
  301. auto& big = (prims0_smallest ? prims1 : prims0);
  302. Vector<size_t> matching_indices; // Indices into 'big' for matching types
  303. matching_indices.reserve(small.size() + 1);
  304. size_t i_big = 0;
  305. bool match_success = true;
  306. bool changed_big = false;
  307. // Iterate through the small set to see if its types fit into the big set
  308. for (size_t i_small = 0; i_small < small.size(); i_small++)
  309. {
  310. match_success = false;
  311. for (; i_big < big.size(); i_big++)
  312. {
  313. auto big_type = big[i_big].type;
  314. if (TransformUtilities::TryConvertToMatchingGenericType(small[i_small], big[i_big]))
  315. {
  316. // They matched exactly or in their more generic form. One or both primitives may have been converted.
  317. match_success = true;
  318. if (big[i_big].type != big_type)
  319. changed_big = true;
  320. }
  321. if (match_success)
  322. {
  323. matching_indices.push_back(i_big);
  324. match_success = true;
  325. i_big += 1;
  326. break;
  327. }
  328. }
  329. if (!match_success)
  330. break;
  331. }
  332. if (match_success)
  333. {
  334. // Success, insert the missing primitives into the small set
  335. matching_indices.push_back(big.size()); // Needed to copy elements behind the last matching primitive
  336. small.reserve(big.size());
  337. size_t i0 = 0;
  338. for (size_t match_index : matching_indices)
  339. {
  340. for (size_t i = i0; i < match_index; i++)
  341. {
  342. TransformPrimitive p = big[i];
  343. TransformUtilities::SetIdentity(p);
  344. small.insert(small.begin() + i, p);
  345. }
  346. // Next value to copy is one-past the matching primitive
  347. i0 = match_index + 1;
  348. }
  349. // The small set has always been changed if we get here, but the big set is only changed
  350. // if one or more of its primitives were converted to a general form.
  351. if (changed_big)
  352. return PrepareTransformResult::ChangedT0andT1;
  353. return (prims0_smallest ? PrepareTransformResult::ChangedT0 : PrepareTransformResult::ChangedT1);
  354. }
  355. }
  356. // If we get here, things get tricky. Need to do full matrix interpolation.
  357. // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components.
  358. // Then, during update, interpolate these components and combine into a new transform matrix.
  359. if (!CombineAndDecompose(t0, element))
  360. return PrepareTransformResult::Invalid;
  361. if (!CombineAndDecompose(t1, element))
  362. return PrepareTransformResult::Invalid;
  363. return PrepareTransformResult::ChangedT0andT1;
  364. }
  365. static bool PrepareTransforms(Vector<AnimationKey>& keys, Element& element, int start_index)
  366. {
  367. bool result = true;
  368. // Prepare each transform individually.
  369. for (int i = start_index; i < (int)keys.size(); i++)
  370. {
  371. Property& property = keys[i].property;
  372. RMLUI_ASSERT(property.value.GetType() == Variant::TRANSFORMPTR);
  373. if (!property.value.GetReference<TransformPtr>())
  374. property.value = MakeShared<Transform>();
  375. bool must_decompose = false;
  376. Transform& transform = *property.value.GetReference<TransformPtr>();
  377. for (TransformPrimitive& primitive : transform.GetPrimitives())
  378. {
  379. if (!TransformUtilities::PrepareForInterpolation(primitive, element))
  380. {
  381. must_decompose = true;
  382. break;
  383. }
  384. }
  385. if (must_decompose)
  386. result &= CombineAndDecompose(transform, element);
  387. }
  388. if (!result)
  389. return false;
  390. // We don't need to prepare the transforms pairwise if we only have a single key added so far.
  391. if (keys.size() < 2 || start_index < 1)
  392. return true;
  393. // Now, prepare the transforms pair-wise so they can be interpolated.
  394. const int N = (int)keys.size();
  395. int count_iterations = -1;
  396. const int max_iterations = 3 * N;
  397. Vector<bool> dirty_list(N + 1, false);
  398. dirty_list[start_index] = true;
  399. // For each pair of keys, match the transform primitives such that they can be interpolated during animation update
  400. for (int i = start_index; i < N && count_iterations < max_iterations; count_iterations++)
  401. {
  402. if (!dirty_list[i])
  403. {
  404. ++i;
  405. continue;
  406. }
  407. auto& prop0 = keys[i - 1].property;
  408. auto& prop1 = keys[i].property;
  409. if (prop0.unit != Unit::TRANSFORM || prop1.unit != Unit::TRANSFORM)
  410. return false;
  411. auto& t0 = prop0.value.GetReference<TransformPtr>();
  412. auto& t1 = prop1.value.GetReference<TransformPtr>();
  413. auto prepare_result = PrepareTransformPair(*t0, *t1, element);
  414. if (prepare_result == PrepareTransformResult::Invalid)
  415. return false;
  416. bool changed_t0 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT0);
  417. bool changed_t1 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT1);
  418. dirty_list[i] = false;
  419. dirty_list[i - 1] = dirty_list[i - 1] || changed_t0;
  420. dirty_list[i + 1] = dirty_list[i + 1] || changed_t1;
  421. if (changed_t0 && i > 1)
  422. --i;
  423. else
  424. ++i;
  425. }
  426. // Something has probably gone wrong if we exceeded max_iterations, possibly a bug in PrepareTransformPair()
  427. return (count_iterations < max_iterations);
  428. }
  429. static void PrepareDecorator(AnimationKey& key)
  430. {
  431. Property& property = key.property;
  432. RMLUI_ASSERT(property.value.GetType() == Variant::DECORATORSPTR);
  433. if (!property.value.GetReference<DecoratorsPtr>())
  434. property.value = MakeShared<DecoratorDeclarationList>();
  435. }
  436. ElementAnimation::ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element,
  437. double start_world_time, float duration, int num_iterations, bool alternate_direction) :
  438. property_id(property_id),
  439. duration(duration), num_iterations(num_iterations), alternate_direction(alternate_direction), last_update_world_time(start_world_time),
  440. origin(origin)
  441. {
  442. if (!current_value.definition)
  443. {
  444. Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').",
  445. current_value.ToString().c_str());
  446. }
  447. InternalAddKey(0.0f, current_value, element, Tween{});
  448. }
  449. bool ElementAnimation::InternalAddKey(float time, const Property& in_property, Element& element, Tween tween)
  450. {
  451. const Units valid_units = (Unit::NUMBER_LENGTH_PERCENT | Unit::ANGLE | Unit::COLOUR | Unit::TRANSFORM | Unit::KEYWORD | Unit::DECORATOR);
  452. if (!Any(in_property.unit & valid_units))
  453. {
  454. Log::Message(Log::LT_WARNING, "Property value '%s' is not a valid target for interpolation.", in_property.ToString().c_str());
  455. return false;
  456. }
  457. keys.emplace_back(time, in_property, tween);
  458. bool result = true;
  459. if (keys.back().property.unit == Unit::TRANSFORM)
  460. {
  461. result = PrepareTransforms(keys, element, (int)keys.size() - 1);
  462. }
  463. else if (keys.back().property.unit == Unit::DECORATOR)
  464. {
  465. PrepareDecorator(keys.back());
  466. }
  467. if (!result)
  468. {
  469. Log::Message(Log::LT_WARNING, "Could not add animation key with property '%s'.", in_property.ToString().c_str());
  470. keys.pop_back();
  471. }
  472. return result;
  473. }
  474. bool ElementAnimation::AddKey(float target_time, const Property& in_property, Element& element, Tween tween, bool extend_duration)
  475. {
  476. if (!IsInitalized())
  477. {
  478. Log::Message(Log::LT_WARNING, "Element animation was not initialized properly, can't add key.");
  479. return false;
  480. }
  481. if (!InternalAddKey(target_time, in_property, element, tween))
  482. {
  483. return false;
  484. }
  485. if (extend_duration)
  486. duration = target_time;
  487. return true;
  488. }
  489. float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_key1) const
  490. {
  491. float t = time_since_iteration_start;
  492. if (reverse_direction)
  493. t = duration - t;
  494. int key0 = -1;
  495. int key1 = -1;
  496. {
  497. for (int i = 0; i < (int)keys.size(); i++)
  498. {
  499. if (keys[i].time >= t)
  500. {
  501. key1 = i;
  502. break;
  503. }
  504. }
  505. if (key1 < 0)
  506. key1 = (int)keys.size() - 1;
  507. key0 = (key1 == 0 ? 0 : key1 - 1);
  508. }
  509. RMLUI_ASSERT(key0 >= 0 && key0 < (int)keys.size() && key1 >= 0 && key1 < (int)keys.size());
  510. float alpha = 0.0f;
  511. {
  512. const float t0 = keys[key0].time;
  513. const float t1 = keys[key1].time;
  514. const float eps = 1e-3f;
  515. if (t1 - t0 > eps)
  516. alpha = (t - t0) / (t1 - t0);
  517. alpha = Math::Clamp(alpha, 0.0f, 1.0f);
  518. }
  519. alpha = keys[key1].tween(alpha);
  520. if (out_key0)
  521. *out_key0 = key0;
  522. if (out_key1)
  523. *out_key1 = key1;
  524. return alpha;
  525. }
  526. Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& element)
  527. {
  528. float dt = float(world_time - last_update_world_time);
  529. if (keys.size() < 2 || animation_complete || dt <= 0.0f)
  530. return Property{};
  531. dt = Math::Min(dt, 0.1f);
  532. last_update_world_time = world_time;
  533. time_since_iteration_start += dt;
  534. if (time_since_iteration_start >= duration)
  535. {
  536. // Next iteration
  537. current_iteration += 1;
  538. if (num_iterations == -1 || (current_iteration >= 0 && current_iteration < num_iterations))
  539. {
  540. time_since_iteration_start -= duration;
  541. if (alternate_direction)
  542. reverse_direction = !reverse_direction;
  543. }
  544. else
  545. {
  546. animation_complete = true;
  547. time_since_iteration_start = duration;
  548. }
  549. }
  550. int key0 = -1;
  551. int key1 = -1;
  552. float alpha = GetInterpolationFactorAndKeys(&key0, &key1);
  553. Property result = InterpolateProperties(keys[key0].property, keys[key1].property, alpha, element, keys[0].property.definition);
  554. return result;
  555. }
  556. } // namespace Rml