ElementAnimation.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. /*
  2. * This source file is part of libRocket, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://www.librocket.com
  5. *
  6. * Copyright (c) 2018 Michael Ragazzon
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. *
  26. */
  27. #include "precompiled.h"
  28. #include "ElementAnimation.h"
  29. #include "ElementStyle.h"
  30. #include "../../Include/Rocket/Core/TransformPrimitive.h"
  31. #include "../../Include/Rocket/Core/StyleSheetSpecification.h"
  32. namespace Rocket {
  33. namespace Core {
  34. static Colourf ColourToLinearSpace(Colourb c)
  35. {
  36. Colourf result;
  37. // Approximate inverse sRGB function
  38. result.red = Math::SquareRoot((float)c.red / 255.f);
  39. result.green = Math::SquareRoot((float)c.green / 255.f);
  40. result.blue = Math::SquareRoot((float)c.blue / 255.f);
  41. result.alpha = (float)c.alpha / 255.f;
  42. return result;
  43. }
  44. static Colourb ColourFromLinearSpace(Colourf c)
  45. {
  46. Colourb result;
  47. result.red = (Rocket::Core::byte)Math::Clamp(c.red*c.red*255.f, 0.0f, 255.f);
  48. result.green = (Rocket::Core::byte)Math::Clamp(c.green*c.green*255.f, 0.0f, 255.f);
  49. result.blue = (Rocket::Core::byte)Math::Clamp(c.blue*c.blue*255.f, 0.0f, 255.f);
  50. result.alpha = (Rocket::Core::byte)Math::Clamp(c.alpha*255.f, 0.0f, 255.f);
  51. return result;
  52. }
  53. // Merges all the primitives to a single DecomposedMatrix4 primitive
  54. static bool CombineAndDecompose(Transform& t, Element& e)
  55. {
  56. Matrix4f m = Matrix4f::Identity();
  57. for (auto& primitive : t.GetPrimitives())
  58. {
  59. Matrix4f m_primitive;
  60. if (primitive.ResolveTransform(m_primitive, e))
  61. m *= m_primitive;
  62. }
  63. Transforms::DecomposedMatrix4 decomposed;
  64. if (!decomposed.Decompose(m))
  65. return false;
  66. t.ClearPrimitives();
  67. t.AddPrimitive(decomposed);
  68. return true;
  69. }
  70. static Property InterpolateProperties(const Property & p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition)
  71. {
  72. if ((p0.unit & Property::NUMBER_LENGTH_PERCENT) && (p1.unit & Property::NUMBER_LENGTH_PERCENT))
  73. {
  74. if (p0.unit == p1.unit || !definition)
  75. {
  76. // If we have the same units, we can just interpolate regardless of what the value represents.
  77. // Or if we have distinct units but no definition, all bets are off. This shouldn't occur, just interpolate values.
  78. float f0 = p0.value.Get<float>();
  79. float f1 = p1.value.Get<float>();
  80. float f = (1.0f - alpha) * f0 + alpha * f1;
  81. return Property{ f, p0.unit };
  82. }
  83. else
  84. {
  85. // Otherwise, convert units to pixels.
  86. float f0 = element.GetStyle()->ResolveNumberLengthPercentage(&p0, definition->GetRelativeTarget());
  87. float f1 = element.GetStyle()->ResolveNumberLengthPercentage(&p1, definition->GetRelativeTarget());
  88. float f = (1.0f - alpha) * f0 + alpha * f1;
  89. return Property{ f, Property::PX };
  90. }
  91. }
  92. if (p0.unit == Property::COLOUR && p1.unit == Property::COLOUR)
  93. {
  94. Colourf c0 = ColourToLinearSpace(p0.value.Get<Colourb>());
  95. Colourf c1 = ColourToLinearSpace(p1.value.Get<Colourb>());
  96. Colourf c = c0 * (1.0f - alpha) + c1 * alpha;
  97. return Property{ ColourFromLinearSpace(c), Property::COLOUR };
  98. }
  99. if (p0.unit == Property::TRANSFORM && p1.unit == Property::TRANSFORM)
  100. {
  101. using namespace Rocket::Core::Transforms;
  102. auto t0 = p0.value.Get<TransformRef>();
  103. auto t1 = p1.value.Get<TransformRef>();
  104. const auto& prim0 = t0->GetPrimitives();
  105. const auto& prim1 = t1->GetPrimitives();
  106. if (prim0.size() != prim1.size())
  107. {
  108. ROCKET_ERRORMSG("Transform primitives not of same size during interpolation. Were the transforms properly prepared for interpolation?");
  109. return Property{ t0, Property::TRANSFORM };
  110. }
  111. // Build the new, interpolating transform
  112. std::unique_ptr<Transform> t(new Transform);
  113. t->GetPrimitives().reserve(t0->GetPrimitives().size());
  114. for (size_t i = 0; i < prim0.size(); i++)
  115. {
  116. Primitive p = prim0[i];
  117. if (!p.InterpolateWith(prim1[i], alpha))
  118. {
  119. ROCKET_ERRORMSG("Transform primitives can not be interpolated. Were the transforms properly prepared for interpolation?");
  120. return Property{ t0, Property::TRANSFORM };
  121. }
  122. t->AddPrimitive(p);
  123. }
  124. return Property{ TransformRef(std::move(t)), Property::TRANSFORM };
  125. }
  126. return alpha < 0.5f ? p0 : p1;
  127. }
  128. enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 };
  129. static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element)
  130. {
  131. using namespace Transforms;
  132. // Insert or modify primitives such that the two transforms match exactly in both number of and types of primitives.
  133. // Based largely on https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  134. auto& prims0 = t0.GetPrimitives();
  135. auto& prims1 = t1.GetPrimitives();
  136. // Check for trivial case where they contain the same primitives
  137. if (prims0.size() == prims1.size())
  138. {
  139. PrepareTransformResult result = PrepareTransformResult::Unchanged;
  140. bool same_primitives = true;
  141. for (size_t i = 0; i < prims0.size(); i++)
  142. {
  143. auto p0_type = prims0[i].primitive.type;
  144. auto p1_type = prims1[i].primitive.type;
  145. if (p0_type != p1_type)
  146. {
  147. // They are not the same, but see if we can convert them to their more generic form
  148. if (!Primitive::TryConvertToMatchingGenericType(prims0[i], prims1[i]))
  149. {
  150. same_primitives = false;
  151. break;
  152. }
  153. if (prims0[i].primitive.type != p0_type)
  154. (int&)result |= (int)PrepareTransformResult::ChangedT0;
  155. if (prims1[i].primitive.type != p1_type)
  156. (int&)result |= (int)PrepareTransformResult::ChangedT1;
  157. }
  158. }
  159. if (same_primitives)
  160. return result;
  161. }
  162. if (prims0.size() != prims1.size())
  163. {
  164. // Try to match the smallest set of primitives to the larger set, set missing keys in the small set to identity.
  165. // Requirement: The small set must match types in the same order they appear in the big set.
  166. // Example: (letter indicates type, number represents values)
  167. // big: a0 b0 c0 b1
  168. // ^ ^
  169. // small: b2 b3
  170. // ^ ^
  171. // new small: a1 b2 c1 b3
  172. bool prims0_smallest = (prims0.size() < prims1.size());
  173. auto& small = (prims0_smallest ? prims0 : prims1);
  174. auto& big = (prims0_smallest ? prims1 : prims0);
  175. std::vector<size_t> matching_indices; // Indices into 'big' for matching types
  176. matching_indices.reserve(small.size() + 1);
  177. size_t i_big = 0;
  178. bool match_success = true;
  179. bool changed_big = false;
  180. // Iterate through the small set to see if its types fit into the big set
  181. for (size_t i_small = 0; i_small < small.size(); i_small++)
  182. {
  183. match_success = false;
  184. auto small_type = small[i_small].primitive.type;
  185. for (; i_big < big.size(); i_big++)
  186. {
  187. auto big_type = big[i_big].primitive.type;
  188. if (small_type == big_type)
  189. {
  190. // Exact match
  191. match_success = true;
  192. }
  193. else if (Primitive::TryConvertToMatchingGenericType(small[i_small], big[i_big]))
  194. {
  195. // They matched in their more generic form, one or both primitives converted
  196. match_success = true;
  197. if (big[i_big].primitive.type != big_type)
  198. changed_big = true;
  199. }
  200. if (match_success)
  201. {
  202. matching_indices.push_back(i_big);
  203. match_success = true;
  204. i_big += 1;
  205. break;
  206. }
  207. }
  208. if (!match_success)
  209. break;
  210. }
  211. if (match_success)
  212. {
  213. // Success, insert the missing primitives into the small set
  214. matching_indices.push_back(big.size()); // Needed to copy elements behind the last matching primitive
  215. small.reserve(big.size());
  216. size_t i0 = 0;
  217. for (size_t match_index : matching_indices)
  218. {
  219. for (size_t i = i0; i < match_index; i++)
  220. {
  221. Primitive p = big[i];
  222. p.SetIdentity();
  223. small.insert(small.begin() + i, p);
  224. }
  225. // Next value to copy is one-past the matching primitive
  226. i0 = match_index + 1;
  227. }
  228. // The small set has always been changed if we get here, but the big set is only changed
  229. // if one or more of its primitives were converted to a general form.
  230. if (changed_big)
  231. return PrepareTransformResult::ChangedT0andT1;
  232. return (prims0_smallest ? PrepareTransformResult::ChangedT0 : PrepareTransformResult::ChangedT1);
  233. }
  234. }
  235. // If we get here, things get tricky. Need to do full matrix interpolation.
  236. // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components.
  237. // Then, during update, interpolate these components and combine into a new transform matrix.
  238. if (!CombineAndDecompose(t0, element))
  239. return PrepareTransformResult::Invalid;
  240. if (!CombineAndDecompose(t1, element))
  241. return PrepareTransformResult::Invalid;
  242. return PrepareTransformResult::ChangedT0andT1;
  243. }
  244. static bool PrepareTransforms(std::vector<AnimationKey>& keys, Element& element, int start_index)
  245. {
  246. if (keys.size() < 2 || start_index < 1)
  247. return false;
  248. const int N = (int)keys.size();
  249. int count_iterations = -1;
  250. const int max_iterations = 3 * N;
  251. std::vector<bool> dirty_list(N + 1, false);
  252. dirty_list[start_index] = true;
  253. // For each pair of keys, match the transform primitives such that they can be interpolated during animation update
  254. for (int i = start_index; i < N && count_iterations < max_iterations; count_iterations++)
  255. {
  256. if (!dirty_list[i])
  257. {
  258. ++i;
  259. continue;
  260. }
  261. auto& prop0 = keys[i - 1].property;
  262. auto& prop1 = keys[i].property;
  263. if(prop0.unit != Property::TRANSFORM || prop1.unit != Property::TRANSFORM)
  264. return false;
  265. auto t0 = prop0.value.Get<TransformRef>();
  266. auto t1 = prop1.value.Get<TransformRef>();
  267. auto result = PrepareTransformPair(*t0, *t1, element);
  268. if (result == PrepareTransformResult::Invalid)
  269. return false;
  270. bool changed_t0 = ((int)result & (int)PrepareTransformResult::ChangedT0);
  271. bool changed_t1 = ((int)result & (int)PrepareTransformResult::ChangedT1);
  272. dirty_list[i] = false;
  273. dirty_list[i - 1] = dirty_list[i - 1] || changed_t0;
  274. dirty_list[i + 1] = dirty_list[i + 1] || changed_t1;
  275. if (changed_t0 && i > 1)
  276. --i;
  277. else
  278. ++i;
  279. }
  280. // Something has probably gone wrong if we exceeded max_iterations, possibly a bug in PrepareTransformPair()
  281. return (count_iterations < max_iterations);
  282. }
  283. ElementAnimation::ElementAnimation(PropertyId property_id, const Property& current_value, double start_world_time, float duration, int num_iterations, bool alternate_direction, bool is_transition)
  284. : property_id(property_id), duration(duration), num_iterations(num_iterations), alternate_direction(alternate_direction),
  285. last_update_world_time(start_world_time), time_since_iteration_start(0.0f), current_iteration(0), reverse_direction(false), animation_complete(false), is_transition(is_transition)
  286. {
  287. if (!current_value.definition)
  288. {
  289. Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').", current_value.ToString().c_str());
  290. }
  291. InternalAddKey(0.0f, current_value, Tween{});
  292. }
  293. bool ElementAnimation::InternalAddKey(float time, const Property& property, Tween tween)
  294. {
  295. int valid_properties = (Property::NUMBER_LENGTH_PERCENT | Property::ANGLE | Property::COLOUR | Property::TRANSFORM);
  296. if (!(property.unit & valid_properties))
  297. {
  298. Log::Message(Log::LT_WARNING, "Property '%s' is not a valid target for interpolation.", property.ToString().c_str());
  299. return false;
  300. }
  301. keys.emplace_back(time, property, tween);
  302. AnimationKey& key = keys.back();
  303. if (key.property.unit == Property::TRANSFORM)
  304. {
  305. if (!key.property.value.Get<TransformRef>())
  306. key.property.value.Reset(TransformRef(new Transform));
  307. }
  308. return true;
  309. }
  310. bool ElementAnimation::AddKey(float target_time, const Property & in_property, Element& element, Tween tween, bool extend_duration)
  311. {
  312. if (keys.empty())
  313. {
  314. Log::Message(Log::LT_WARNING, "Element animation was not initialized properly, can't add key.");
  315. return false;
  316. }
  317. if (!InternalAddKey(target_time, in_property, tween))
  318. {
  319. return false;
  320. }
  321. bool result = true;
  322. auto& property = keys.back().property;
  323. if (property.unit == Property::TRANSFORM)
  324. {
  325. bool must_decompose = false;
  326. Transform& transform = *property.value.Get<TransformRef>();
  327. for (auto& primitive : transform.GetPrimitives())
  328. {
  329. if (!primitive.PrepareForInterpolation(element))
  330. {
  331. must_decompose = true;
  332. break;
  333. }
  334. }
  335. if(must_decompose)
  336. result = CombineAndDecompose(transform, element);
  337. if (result)
  338. result = PrepareTransforms(keys, element, (int)keys.size() - 1);
  339. }
  340. if(result)
  341. {
  342. if(extend_duration)
  343. duration = target_time;
  344. }
  345. else
  346. {
  347. keys.pop_back();
  348. }
  349. return result;
  350. }
  351. float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_key1) const
  352. {
  353. float t = time_since_iteration_start;
  354. if (reverse_direction)
  355. t = duration - t;
  356. int key0 = -1;
  357. int key1 = -1;
  358. {
  359. for (int i = 0; i < (int)keys.size(); i++)
  360. {
  361. if (keys[i].time >= t)
  362. {
  363. key1 = i;
  364. break;
  365. }
  366. }
  367. if (key1 < 0) key1 = (int)keys.size() - 1;
  368. key0 = (key1 == 0 ? 0 : key1 - 1);
  369. }
  370. ROCKET_ASSERT(key0 >= 0 && key0 < (int)keys.size() && key1 >= 0 && key1 < (int)keys.size());
  371. float alpha = 0.0f;
  372. {
  373. const float t0 = keys[key0].time;
  374. const float t1 = keys[key1].time;
  375. const float eps = 1e-3f;
  376. if (t1 - t0 > eps)
  377. alpha = (t - t0) / (t1 - t0);
  378. alpha = Math::Clamp(alpha, 0.0f, 1.0f);
  379. }
  380. alpha = keys[key1].tween(alpha);
  381. if (out_key0) *out_key0 = key0;
  382. if (out_key1) *out_key1 = key1;
  383. return alpha;
  384. }
  385. Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& element)
  386. {
  387. ROCKET_ASSERT(keys.size() >= 2);
  388. float dt = float(world_time - last_update_world_time);
  389. if (animation_complete || dt <= 0.0f)
  390. return Property{};
  391. dt = Math::Min(dt, 0.1f);
  392. last_update_world_time = world_time;
  393. time_since_iteration_start += dt;
  394. if (time_since_iteration_start >= duration)
  395. {
  396. // Next iteration
  397. current_iteration += 1;
  398. if (num_iterations == -1 || (current_iteration >= 0 && current_iteration < num_iterations))
  399. {
  400. time_since_iteration_start -= duration;
  401. if (alternate_direction)
  402. reverse_direction = !reverse_direction;
  403. }
  404. else
  405. {
  406. animation_complete = true;
  407. time_since_iteration_start = duration;
  408. }
  409. }
  410. int key0 = -1;
  411. int key1 = -1;
  412. float alpha = GetInterpolationFactorAndKeys(&key0, &key1);
  413. Property result = InterpolateProperties(keys[key0].property, keys[key1].property, alpha, element, keys[0].property.definition);
  414. return result;
  415. }
  416. }
  417. }