AnimationSystem.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. #include "AnimationSystem.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include "WallpaperEngine/Logging/Log.h"
  5. using namespace WallpaperEngine::Scripting;
  6. namespace {
  7. int NextSystemId = 0;
  8. std::map<int, AnimationSystem*> Systems;
  9. int componentCount (DynamicValue::UnderlyingType type) {
  10. switch (type) {
  11. case DynamicValue::Float:
  12. return 1;
  13. case DynamicValue::Vec2:
  14. return 2;
  15. case DynamicValue::Vec3:
  16. return 3;
  17. case DynamicValue::Vec4:
  18. return 4;
  19. default:
  20. return 0;
  21. }
  22. }
  23. glm::vec4 readComponents (const DynamicValue& value) {
  24. switch (value.getType ()) {
  25. case DynamicValue::Float:
  26. return { value.getFloat (), 0.0f, 0.0f, 0.0f };
  27. case DynamicValue::Vec2:
  28. return { value.getVec2 (), 0.0f, 0.0f };
  29. case DynamicValue::Vec3:
  30. return { value.getVec3 (), 0.0f };
  31. case DynamicValue::Vec4:
  32. return value.getVec4 ();
  33. default:
  34. return glm::vec4 (0.0f);
  35. }
  36. }
  37. void writeComponents (DynamicValue& value, const glm::vec4& components) {
  38. const auto source = DynamicValue::UpdateSource::Script;
  39. switch (value.getType ()) {
  40. case DynamicValue::Float:
  41. value.update (components.x, source);
  42. break;
  43. case DynamicValue::Vec2:
  44. value.update (glm::vec2 (components), source);
  45. break;
  46. case DynamicValue::Vec3:
  47. value.update (glm::vec3 (components), source);
  48. break;
  49. case DynamicValue::Vec4:
  50. value.update (components, source);
  51. break;
  52. default:
  53. break;
  54. }
  55. }
  56. float cubicBezier (float p0, float p1, float p2, float p3, float t) {
  57. const float u = 1.0f - t;
  58. return u * u * u * p0 + 3.0f * u * u * t * p1 + 3.0f * u * t * t * p2 + t * t * t * p3;
  59. }
  60. } // namespace
  61. float WallpaperEngine::Scripting::sampleAnimationFrame (const std::vector<AnimationKeyframe>& keys, const int frame) {
  62. if (keys.empty ()) {
  63. return 0.0f;
  64. }
  65. if (static_cast<float> (frame) <= keys.front ().frame) {
  66. return keys.front ().value;
  67. }
  68. for (size_t i = 1; i < keys.size (); i++) {
  69. const auto& previous = keys[i - 1];
  70. const auto& current = keys[i];
  71. const int start = static_cast<int> (previous.frame);
  72. const int end = static_cast<int> (current.frame);
  73. if (frame < start || frame >= end) {
  74. continue;
  75. }
  76. if (start == frame || current.step) {
  77. return previous.value;
  78. }
  79. // handle x is in half segments. The curve parameter is found by halving steps from an integer
  80. // division guess, like the 0.01 frame tolerance and 1000 step limit of sub_1401A9BC0
  81. const float half = static_cast<float> (end - start) * 0.5f;
  82. const float x1 = half * previous.front.x + static_cast<float> (start);
  83. const float x2 = half * current.back.x + static_cast<float> (end);
  84. const float target = static_cast<float> (frame);
  85. float t = static_cast<float> ((frame - start) / (end - start));
  86. float step = 0.999f;
  87. for (int iteration = 0; iteration < 1000; iteration++) {
  88. const float x = cubicBezier (static_cast<float> (start), x1, x2, static_cast<float> (end), t);
  89. if (std::fabs (x - target) < 0.01f) {
  90. break;
  91. }
  92. step *= 0.5f;
  93. t = x <= target ? t + step : t - step;
  94. }
  95. t = std::clamp (t, 0.0f, 1.0f);
  96. return cubicBezier (
  97. previous.value, previous.value + previous.front.y, current.value + current.back.y, current.value, t
  98. );
  99. }
  100. return keys.back ().value;
  101. }
  102. float WallpaperEngine::Scripting::evaluateAnimationCurve (
  103. const std::vector<AnimationKeyframe>& keys, const float frame, const float fps, const int frameCount
  104. ) {
  105. if (keys.empty ()) {
  106. return 0.0f;
  107. }
  108. if (frameCount <= 0 || fps <= 0.0f) {
  109. return sampleAnimationFrame (keys, static_cast<int> (frame));
  110. }
  111. // whole frames get sampled and blended, the blend comes from the time in seconds (sub_140171440)
  112. const float frameTime = 1.0f / fps;
  113. const float seconds = frame * frameTime;
  114. const int whole = static_cast<int> (seconds / frameTime);
  115. const int first = std::clamp (whole, 0, frameCount - 1);
  116. const int second = std::min (first + 1, frameCount);
  117. const float blend = std::fmod (seconds, frameTime) / frameTime;
  118. return sampleAnimationFrame (keys, first) * (1.0f - blend) + sampleAnimationFrame (keys, second) * blend;
  119. }
  120. AnimationClock::AnimationClock (int id, DynamicValue& rootValue, std::shared_ptr<const PropertyAnimation> definition) :
  121. m_id (id), m_rootValue (&rootValue), m_definition (std::move (definition)) {
  122. m_playing = !m_definition->startPaused;
  123. }
  124. void AnimationClock::addBinding (DynamicValue& value, std::shared_ptr<const PropertyAnimation> data) {
  125. m_bindings.push_back (Binding { .value = &value, .data = std::move (data) });
  126. }
  127. void AnimationClock::stop () {
  128. m_playing = false;
  129. this->setFrame (0.0f);
  130. }
  131. void AnimationClock::setFrame (float frame) {
  132. m_frame = std::clamp (frame, 0.0f, std::max (m_definition->length, 0.0f));
  133. this->applyCurrentFrame ();
  134. }
  135. void AnimationClock::applyCurrentFrame () {
  136. for (auto& binding : m_bindings) {
  137. this->applyBinding (binding);
  138. }
  139. }
  140. void AnimationClock::applyBinding (Binding& binding) const {
  141. const int count = componentCount (binding.value->getType ());
  142. if (count == 0) {
  143. return;
  144. }
  145. const glm::vec4 current = readComponents (*binding.value);
  146. glm::vec4 target = current;
  147. for (int component = 0; component < count; component++) {
  148. const auto& keys = binding.data->curves[component];
  149. if (keys.empty ()) {
  150. continue;
  151. }
  152. const float sampled
  153. = evaluateAnimationCurve (keys, m_frame, m_definition->fps, static_cast<int> (m_definition->length));
  154. if (binding.data->relative) {
  155. // fold the offset in on top of whatever the value is now, so a script moving the base
  156. // value around keeps working
  157. target[component] = current[component] - binding.lastOffset[component] + sampled;
  158. binding.lastOffset[component] = sampled;
  159. } else {
  160. target[component] = sampled;
  161. }
  162. }
  163. if (target != current) {
  164. writeComponents (*binding.value, target);
  165. }
  166. }
  167. void AnimationClock::collectEvents (float from, float to, bool includeFrom, std::vector<FiredEvent>& out) const {
  168. const bool forward = to >= from;
  169. std::vector<const AnimationEvent*> hits;
  170. for (const auto& event : m_definition->events) {
  171. const bool inside = forward ? (includeFrom ? event.frame >= from : event.frame > from) && event.frame <= to
  172. : (includeFrom ? event.frame <= from : event.frame < from) && event.frame >= to;
  173. if (inside) {
  174. hits.push_back (&event);
  175. }
  176. }
  177. std::ranges::stable_sort (hits, [forward] (const AnimationEvent* a, const AnimationEvent* b) {
  178. return forward ? a->frame < b->frame : a->frame > b->frame;
  179. });
  180. for (const auto* hit : hits) {
  181. out.push_back (FiredEvent { .name = hit->name, .frame = hit->frame });
  182. }
  183. }
  184. std::vector<AnimationClock::FiredEvent> AnimationClock::tick (float deltaSeconds) {
  185. std::vector<FiredEvent> fired;
  186. const float length = m_definition->length;
  187. if (!m_playing || length <= 0.0f) {
  188. return fired;
  189. }
  190. const float step = deltaSeconds * m_definition->fps * m_rate * m_direction;
  191. if (step == 0.0f) {
  192. return fired;
  193. }
  194. float from = m_frame;
  195. float to = from + step;
  196. bool forward = step > 0.0f;
  197. bool includeFrom = false;
  198. // a long frame can cross the end several times; anything past this is just phase
  199. for (int wraps = 0; wraps < 4; wraps++) {
  200. const bool pastEnd = forward ? to >= length : to <= 0.0f;
  201. if (!pastEnd) {
  202. break;
  203. }
  204. const float edge = forward ? length : 0.0f;
  205. this->collectEvents (from, edge, includeFrom, fired);
  206. includeFrom = true;
  207. if (m_definition->mode == PropertyAnimation::Mode::Single) {
  208. m_frame = edge;
  209. m_playing = false;
  210. this->applyCurrentFrame ();
  211. return fired;
  212. }
  213. if (m_definition->mode == PropertyAnimation::Mode::Loop) {
  214. to = forward ? to - length : to + length;
  215. from = forward ? 0.0f : length;
  216. } else {
  217. to = forward ? 2.0f * length - to : -to;
  218. from = edge;
  219. forward = !forward;
  220. m_direction = -m_direction;
  221. }
  222. }
  223. to = std::clamp (to, 0.0f, length);
  224. this->collectEvents (from, to, includeFrom, fired);
  225. m_frame = to;
  226. this->applyCurrentFrame ();
  227. return fired;
  228. }
  229. AnimationSystem::AnimationSystem () : m_id (++NextSystemId) { Systems.emplace (m_id, this); }
  230. AnimationSystem::~AnimationSystem () { Systems.erase (m_id); }
  231. AnimationSystem* AnimationSystem::find (int id) {
  232. const auto it = Systems.find (id);
  233. return it == Systems.end () ? nullptr : it->second;
  234. }
  235. void AnimationSystem::add (const std::string& group, const std::string& key, DynamicValue& value) {
  236. if (value.getAnimation () == nullptr) {
  237. return;
  238. }
  239. m_pending.push_back (Entry { .group = group, .key = key, .value = &value });
  240. m_linked = false;
  241. }
  242. void AnimationSystem::remove (const DynamicValue& value) {
  243. std::erase_if (m_pending, [&value] (const Entry& entry) { return entry.value == &value; });
  244. }
  245. AnimationClock* AnimationSystem::clockOf (const DynamicValue& value) {
  246. if (!m_linked) {
  247. this->link ();
  248. }
  249. const auto it = m_byValue.find (&value);
  250. return it == m_byValue.end () ? nullptr : it->second;
  251. }
  252. AnimationClock* AnimationSystem::clock (int id) {
  253. for (const auto& clock : m_clocks) {
  254. if (clock->getId () == id) {
  255. return clock.get ();
  256. }
  257. }
  258. return nullptr;
  259. }
  260. void AnimationSystem::link () {
  261. m_linked = true;
  262. for (const auto& entry : m_pending) {
  263. m_groups[entry.group].emplace (entry.key, entry.value);
  264. }
  265. // follows parent links to the property that owns the playback state
  266. const auto resolveRoot = [this] (const Entry& entry) {
  267. DynamicValue* current = entry.value;
  268. for (int depth = 0; depth < 8; depth++) {
  269. const auto& parentKey = current->getAnimation ()->parent;
  270. if (!parentKey.has_value ()) {
  271. break;
  272. }
  273. const auto& siblings = m_groups[entry.group];
  274. const auto parent = siblings.find (*parentKey);
  275. if (parent == siblings.end () || parent->second == current || parent->second->getAnimation () == nullptr) {
  276. break;
  277. }
  278. current = parent->second;
  279. }
  280. return current;
  281. };
  282. static int nextClockId = 0;
  283. for (const auto& entry : m_pending) {
  284. DynamicValue* root = resolveRoot (entry);
  285. if (m_byValue.contains (root)) {
  286. continue;
  287. }
  288. auto clock = std::make_unique<AnimationClock> (++nextClockId, *root, root->getAnimation ());
  289. m_byValue.emplace (root, clock.get ());
  290. m_clocks.push_back (std::move (clock));
  291. }
  292. std::set<AnimationClock*> touched;
  293. for (const auto& entry : m_pending) {
  294. if (!m_bound.insert (entry.value).second) {
  295. continue;
  296. }
  297. auto* clock = m_byValue.at (resolveRoot (entry));
  298. clock->addBinding (*entry.value, entry.value->getAnimation ());
  299. m_byValue.emplace (entry.value, clock);
  300. touched.insert (clock);
  301. }
  302. // paused timelines still show their first frame, which is what hides collapsed UI at startup
  303. for (auto* clock : touched) {
  304. clock->applyCurrentFrame ();
  305. }
  306. m_pending.clear ();
  307. }
  308. void AnimationSystem::tick (float deltaSeconds) {
  309. if (!m_linked) {
  310. this->link ();
  311. }
  312. for (const auto& clock : m_clocks) {
  313. for (auto& event : clock->tick (deltaSeconds)) {
  314. m_events.push_back (
  315. PendingEvent { .clock = clock->getId (), .name = std::move (event.name), .frame = event.frame }
  316. );
  317. }
  318. }
  319. }
  320. std::vector<AnimationSystem::PendingEvent> AnimationSystem::takeEvents () {
  321. std::vector<PendingEvent> events;
  322. events.swap (m_events);
  323. return events;
  324. }