ScrollController.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  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 "ScrollController.h"
  29. #include "../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../Include/RmlUi/Core/Core.h"
  31. #include "../../Include/RmlUi/Core/Element.h"
  32. #include "../../Include/RmlUi/Core/SystemInterface.h"
  33. namespace Rml {
  34. static constexpr float AUTOSCROLL_SPEED_FACTOR = 0.09f;
  35. static constexpr float AUTOSCROLL_DEADZONE = 10.0f; // [dp]
  36. static constexpr float SMOOTHSCROLL_WINDOW_SIZE = 50.f; // The window where smoothing is applied, as a distance from scroll start and end. [dp]
  37. static constexpr float SMOOTHSCROLL_MAX_VELOCITY = 10'000.f; // [dp/s]
  38. static constexpr float SMOOTHSCROLL_VELOCITY_CONSTANT = 800.f; // [dp/s]
  39. static constexpr float SMOOTHSCROLL_VELOCITY_SQUARE_FACTOR = 0.05f;
  40. // Clamp the delta time to some reasonable FPS range, to avoid large steps in case of stuttering or freezing.
  41. static constexpr float DELTA_TIME_CLAMP_LOW = 1.f / 500.f; // [s]
  42. static constexpr float DELTA_TIME_CLAMP_HIGH = 1.f / 15.f; // [s]
  43. // Determines the autoscroll velocity based on the distance from the scroll-start mouse position. [px/s]
  44. static Vector2f CalculateAutoscrollVelocity(Vector2f target_delta, float dp_ratio)
  45. {
  46. target_delta = target_delta / dp_ratio;
  47. target_delta = {
  48. Math::Absolute(target_delta.x) < AUTOSCROLL_DEADZONE ? 0.f : target_delta.x,
  49. Math::Absolute(target_delta.y) < AUTOSCROLL_DEADZONE ? 0.f : target_delta.y,
  50. };
  51. // We use a signed square model for the velocity, which seems to work quite well. This is mostly about feeling and tuning.
  52. return AUTOSCROLL_SPEED_FACTOR * target_delta * Math::Absolute(target_delta);
  53. }
  54. // Determines the smoothscroll velocity based on the distance to the target, and the distance scrolled so far. [px/s]
  55. static Vector2f CalculateSmoothscrollVelocity(Vector2f target_delta, Vector2f scrolled_distance, float dp_ratio)
  56. {
  57. scrolled_distance = Math::Absolute(scrolled_distance) / dp_ratio;
  58. target_delta = target_delta / dp_ratio;
  59. const Vector2f target_delta_abs = Math::Absolute(target_delta);
  60. Vector2f target_delta_signum = {
  61. target_delta.x > 0.f ? 1.f : (target_delta.x < 0.f ? -1.f : 0.f),
  62. target_delta.y > 0.f ? 1.f : (target_delta.y < 0.f ? -1.f : 0.f),
  63. };
  64. // The window provides velocity smoothing near the start and end of the scroll.
  65. const Tween tween(Tween::Exponential, Tween::Out);
  66. const Vector2f alpha_in = Math::Min(scrolled_distance / SMOOTHSCROLL_WINDOW_SIZE, Vector2f(1.f));
  67. const Vector2f alpha_out = Math::Min(target_delta_abs / SMOOTHSCROLL_WINDOW_SIZE, Vector2f(1.f));
  68. const Vector2f smooth_window = {
  69. 0.2f + 0.8f * tween(alpha_in.x) * tween(alpha_out.x),
  70. 0.2f + 0.8f * tween(alpha_in.y) * tween(alpha_out.y),
  71. };
  72. const Vector2f velocity_constant = Vector2f(SMOOTHSCROLL_VELOCITY_CONSTANT);
  73. const Vector2f velocity_square = SMOOTHSCROLL_VELOCITY_SQUARE_FACTOR * target_delta_abs * target_delta_abs;
  74. // Short scrolls are dominated by the smoothed constant velocity, while the square term is added for quick longer scrolls.
  75. return dp_ratio * target_delta_signum * smooth_window * Math::Min(velocity_constant + velocity_square, Vector2f(SMOOTHSCROLL_MAX_VELOCITY));
  76. }
  77. void ScrollController::ActivateAutoscroll(Element* in_target, Vector2i start_position)
  78. {
  79. Reset();
  80. if (!in_target)
  81. return;
  82. target = in_target;
  83. mode = Mode::Autoscroll;
  84. autoscroll_start_position = start_position;
  85. UpdateTime();
  86. }
  87. void ScrollController::ActivateSmoothscroll(Element* in_target, Vector2f delta_distance, ScrollBehavior scroll_behavior)
  88. {
  89. Reset();
  90. if (!in_target)
  91. return;
  92. target = in_target;
  93. // Do instant scroll if preferred.
  94. if (smoothscroll_prefer_instant && scroll_behavior != ScrollBehavior::Smooth)
  95. {
  96. PerformScrollOnTarget(delta_distance);
  97. target = nullptr;
  98. return;
  99. }
  100. mode = Mode::Smoothscroll;
  101. UpdateTime();
  102. IncrementSmoothscrollTarget(delta_distance);
  103. // If the target is scrolled to its edge already, simply cancel the smoothscroll operation.
  104. if (HasSmoothscrollReachedTarget())
  105. Reset();
  106. }
  107. bool ScrollController::Update(Vector2i mouse_position, float dp_ratio)
  108. {
  109. if (mode == Mode::Autoscroll)
  110. UpdateAutoscroll(mouse_position, dp_ratio);
  111. else if (mode == Mode::Smoothscroll)
  112. UpdateSmoothscroll(dp_ratio);
  113. return mode != Mode::None;
  114. }
  115. void ScrollController::UpdateAutoscroll(Vector2i mouse_position, float dp_ratio)
  116. {
  117. RMLUI_ASSERT(mode == Mode::Autoscroll && target);
  118. const float dt = UpdateTime();
  119. const Vector2f scroll_delta = Vector2f(mouse_position - autoscroll_start_position);
  120. const Vector2f scroll_velocity = CalculateAutoscrollVelocity(scroll_delta, dp_ratio);
  121. autoscroll_accumulated_length += scroll_velocity * dt;
  122. // Only submit the integer part of the scroll length, accumulate and store fractional parts to enable sub-pixel-per-frame scrolling speeds.
  123. Vector2f scroll_length_integral = autoscroll_accumulated_length;
  124. autoscroll_accumulated_length.x = Math::DecomposeFractionalIntegral(autoscroll_accumulated_length.x, &scroll_length_integral.x);
  125. autoscroll_accumulated_length.y = Math::DecomposeFractionalIntegral(autoscroll_accumulated_length.y, &scroll_length_integral.y);
  126. if (scroll_velocity != Vector2f(0.f))
  127. autoscroll_moved = true;
  128. PerformScrollOnTarget(scroll_length_integral);
  129. }
  130. void ScrollController::UpdateSmoothscroll(float dp_ratio)
  131. {
  132. RMLUI_ASSERT(mode == Mode::Smoothscroll && target);
  133. const Vector2f target_delta = Vector2f(smoothscroll_target_distance - smoothscroll_scrolled_distance);
  134. const Vector2f velocity = CalculateSmoothscrollVelocity(target_delta, smoothscroll_scrolled_distance, dp_ratio);
  135. const float dt = UpdateTime();
  136. Vector2f scroll_distance = (smoothscroll_speed_factor * velocity * dt).Round();
  137. for (int i = 0; i < 2; i++)
  138. {
  139. // Ensure minimum scroll speed of 1px/frame, and clamp the distance to the target in case of overshooting
  140. // integration. As opposed to autoscroll, we don't care about fractional speeds here since we want to be fast.
  141. if (target_delta[i] > 0.f)
  142. scroll_distance[i] = Math::Min(Math::Max(scroll_distance[i], 1.f), target_delta[i]);
  143. else if (target_delta[i] < 0.f)
  144. scroll_distance[i] = Math::Max(Math::Min(scroll_distance[i], -1.f), target_delta[i]);
  145. else
  146. scroll_distance[i] = 0.f;
  147. }
  148. #if 0
  149. // Useful debugging output for velocity model tuning.
  150. Log::Message(Log::LT_INFO, "Scroll y0 %8.2f y1 %8.2f v %8.2f d %8.2f", smoothscroll_scrolled_distance.y, target_delta.y, velocity.y,
  151. scroll_distance.y);
  152. #endif
  153. smoothscroll_scrolled_distance += scroll_distance;
  154. PerformScrollOnTarget(scroll_distance);
  155. if (HasSmoothscrollReachedTarget())
  156. Reset();
  157. }
  158. bool ScrollController::HasSmoothscrollReachedTarget() const
  159. {
  160. constexpr float epsilon = 0.1f;
  161. return (smoothscroll_target_distance - smoothscroll_scrolled_distance).SquaredMagnitude() < epsilon;
  162. }
  163. void ScrollController::PerformScrollOnTarget(Vector2f delta_distance)
  164. {
  165. RMLUI_ASSERT(target);
  166. auto overflow_is_scrollable = [](Style::Overflow overflow) { return overflow == Style::Overflow::Auto || overflow == Style::Overflow::Scroll; };
  167. auto& computed_values = target->GetComputedValues();
  168. if (delta_distance.x != 0.f && overflow_is_scrollable(computed_values.overflow_x()))
  169. target->SetScrollLeft(target->GetScrollLeft() + delta_distance.x);
  170. if (delta_distance.y != 0.f && overflow_is_scrollable(computed_values.overflow_y()))
  171. target->SetScrollTop(target->GetScrollTop() + delta_distance.y);
  172. }
  173. void ScrollController::IncrementSmoothscrollTarget(Vector2f delta_distance)
  174. {
  175. auto OppositeDirection = [](float a, float b) { return (a < 0.f && b > 0.f) || (a > 0.f && b < 0.f); };
  176. Vector2f delta = smoothscroll_target_distance - smoothscroll_scrolled_distance;
  177. // Reset movement state if we start scrolling in the opposite direction.
  178. for (int i = 0; i < 2; i++)
  179. {
  180. if (OppositeDirection(delta_distance[i], delta[i]))
  181. {
  182. smoothscroll_target_distance[i] = 0.f;
  183. smoothscroll_scrolled_distance[i] = 0.f;
  184. }
  185. }
  186. // Clamp the delta distance to the scrollable area.
  187. const Vector2f scroll_offset = {target->GetScrollLeft(), target->GetScrollTop()};
  188. const Vector2f max_offset = {target->GetScrollWidth() - target->GetClientWidth(), target->GetScrollHeight() - target->GetClientHeight()};
  189. const Vector2f target_offset = scroll_offset + smoothscroll_target_distance - smoothscroll_scrolled_distance;
  190. const Vector2f clamped_delta = Math::Clamp(delta_distance + target_offset, Vector2f(0.f), max_offset) - target_offset;
  191. smoothscroll_target_distance += clamped_delta;
  192. }
  193. void ScrollController::Reset()
  194. {
  195. mode = Mode::None;
  196. target = nullptr;
  197. autoscroll_start_position = Vector2i{};
  198. autoscroll_accumulated_length = Vector2f{};
  199. autoscroll_moved = false;
  200. smoothscroll_target_distance = Vector2f{};
  201. smoothscroll_scrolled_distance = Vector2f{};
  202. // Keep smoothscroll configuration parameters.
  203. }
  204. void ScrollController::SetDefaultScrollBehavior(ScrollBehavior scroll_behavior, float speed_factor)
  205. {
  206. smoothscroll_prefer_instant = (scroll_behavior == ScrollBehavior::Instant);
  207. smoothscroll_speed_factor = speed_factor;
  208. }
  209. String ScrollController::GetAutoscrollCursor(Vector2i mouse_position, float dp_ratio) const
  210. {
  211. RMLUI_ASSERT(mode == Mode::Autoscroll);
  212. const Vector2f scroll_delta = Vector2f(mouse_position - autoscroll_start_position);
  213. const Vector2f scroll_velocity = CalculateAutoscrollVelocity(scroll_delta, dp_ratio);
  214. if (scroll_velocity == Vector2f(0.f))
  215. return "rmlui-scroll-idle";
  216. String result = "rmlui-scroll";
  217. if (scroll_velocity.y > 0.f)
  218. result += "-up";
  219. else if (scroll_velocity.y < 0.f)
  220. result += "-down";
  221. if (scroll_velocity.x > 0.f)
  222. result += "-right";
  223. else if (scroll_velocity.x < 0.f)
  224. result += "-left";
  225. return result;
  226. }
  227. bool ScrollController::HasAutoscrollMoved() const
  228. {
  229. return mode == Mode::Autoscroll && autoscroll_moved;
  230. }
  231. float ScrollController::UpdateTime()
  232. {
  233. const double previous_tick = previous_update_time;
  234. previous_update_time = GetSystemInterface()->GetElapsedTime();
  235. const float dt = float(previous_update_time - previous_tick);
  236. return Math::Clamp(dt, DELTA_TIME_CLAMP_LOW, DELTA_TIME_CLAMP_HIGH);
  237. }
  238. } // namespace Rml