Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2012 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #define LOG_TAG "VelocityTracker" |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 18 | |
Yeabkal Wubshit | d9c4008 | 2023-07-21 19:11:52 -0700 | [diff] [blame^] | 19 | #include <android-base/logging.h> |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 20 | #include <inttypes.h> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 21 | #include <limits.h> |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 22 | #include <math.h> |
Yeabkal Wubshit | d9c4008 | 2023-07-21 19:11:52 -0700 | [diff] [blame^] | 23 | #include <array> |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 24 | #include <optional> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 25 | |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 26 | #include <input/PrintTools.h> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 27 | #include <input/VelocityTracker.h> |
| 28 | #include <utils/BitSet.h> |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 29 | #include <utils/Timers.h> |
| 30 | |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 31 | using std::literals::chrono_literals::operator""ms; |
| 32 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 33 | namespace android { |
| 34 | |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 35 | /** |
| 36 | * Log debug messages about velocity tracking. |
| 37 | * Enable this via "adb shell setprop log.tag.VelocityTrackerVelocity DEBUG" (requires restart) |
| 38 | */ |
| 39 | const bool DEBUG_VELOCITY = |
| 40 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Velocity", ANDROID_LOG_INFO); |
| 41 | |
| 42 | /** |
| 43 | * Log debug messages about the progress of the algorithm itself. |
| 44 | * Enable this via "adb shell setprop log.tag.VelocityTrackerStrategy DEBUG" (requires restart) |
| 45 | */ |
| 46 | const bool DEBUG_STRATEGY = |
| 47 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Strategy", ANDROID_LOG_INFO); |
| 48 | |
| 49 | /** |
| 50 | * Log debug messages about the 'impulse' strategy. |
| 51 | * Enable this via "adb shell setprop log.tag.VelocityTrackerImpulse DEBUG" (requires restart) |
| 52 | */ |
| 53 | const bool DEBUG_IMPULSE = |
| 54 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Impulse", ANDROID_LOG_INFO); |
| 55 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 56 | // Nanoseconds per milliseconds. |
| 57 | static const nsecs_t NANOS_PER_MS = 1000000; |
| 58 | |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 59 | // Seconds per nanosecond. |
| 60 | static const float SECONDS_PER_NANO = 1E-9; |
| 61 | |
Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 62 | // All axes supported for velocity tracking, mapped to their default strategies. |
| 63 | // Although other strategies are available for testing and comparison purposes, |
| 64 | // the default strategy is the one that applications will actually use. Be very careful |
| 65 | // when adjusting the default strategy because it can dramatically affect |
| 66 | // (often in a bad way) the user experience. |
| 67 | static const std::map<int32_t, VelocityTracker::Strategy> DEFAULT_STRATEGY_BY_AXIS = |
| 68 | {{AMOTION_EVENT_AXIS_X, VelocityTracker::Strategy::LSQ2}, |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 69 | {AMOTION_EVENT_AXIS_Y, VelocityTracker::Strategy::LSQ2}, |
| 70 | {AMOTION_EVENT_AXIS_SCROLL, VelocityTracker::Strategy::IMPULSE}}; |
Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 71 | |
| 72 | // Axes specifying location on a 2D plane (i.e. X and Y). |
| 73 | static const std::set<int32_t> PLANAR_AXES = {AMOTION_EVENT_AXIS_X, AMOTION_EVENT_AXIS_Y}; |
| 74 | |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 75 | // Axes whose motion values are differential values (i.e. deltas). |
| 76 | static const std::set<int32_t> DIFFERENTIAL_AXES = {AMOTION_EVENT_AXIS_SCROLL}; |
| 77 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 78 | // Threshold for determining that a pointer has stopped moving. |
| 79 | // Some input devices do not send ACTION_MOVE events in the case where a pointer has |
| 80 | // stopped. We need to detect this case so that we can accurately predict the |
| 81 | // velocity after the pointer starts moving again. |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 82 | static const std::chrono::duration ASSUME_POINTER_STOPPED_TIME = 40ms; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 83 | |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 84 | static std::string toString(std::chrono::nanoseconds t) { |
| 85 | std::stringstream stream; |
| 86 | stream.precision(1); |
| 87 | stream << std::fixed << std::chrono::duration<float, std::milli>(t).count() << " ms"; |
| 88 | return stream.str(); |
| 89 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 90 | |
| 91 | static float vectorDot(const float* a, const float* b, uint32_t m) { |
| 92 | float r = 0; |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 93 | for (size_t i = 0; i < m; i++) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 94 | r += *(a++) * *(b++); |
| 95 | } |
| 96 | return r; |
| 97 | } |
| 98 | |
| 99 | static float vectorNorm(const float* a, uint32_t m) { |
| 100 | float r = 0; |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 101 | for (size_t i = 0; i < m; i++) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 102 | float t = *(a++); |
| 103 | r += t * t; |
| 104 | } |
| 105 | return sqrtf(r); |
| 106 | } |
| 107 | |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 108 | static std::string vectorToString(const float* a, uint32_t m) { |
| 109 | std::string str; |
| 110 | str += "["; |
Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 111 | for (size_t i = 0; i < m; i++) { |
| 112 | if (i) { |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 113 | str += ","; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 114 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 115 | str += android::base::StringPrintf(" %f", *(a++)); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 116 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 117 | str += " ]"; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 118 | return str; |
| 119 | } |
| 120 | |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 121 | static std::string vectorToString(const std::vector<float>& v) { |
| 122 | return vectorToString(v.data(), v.size()); |
| 123 | } |
| 124 | |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 125 | static std::string matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) { |
| 126 | std::string str; |
| 127 | str = "["; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 128 | for (size_t i = 0; i < m; i++) { |
| 129 | if (i) { |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 130 | str += ","; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 131 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 132 | str += " ["; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 133 | for (size_t j = 0; j < n; j++) { |
| 134 | if (j) { |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 135 | str += ","; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 136 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 137 | str += android::base::StringPrintf(" %f", a[rowMajor ? i * n + j : j * m + i]); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 138 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 139 | str += " ]"; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 140 | } |
Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 141 | str += " ]"; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 142 | return str; |
| 143 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 144 | |
| 145 | |
| 146 | // --- VelocityTracker --- |
| 147 | |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 148 | VelocityTracker::VelocityTracker(const Strategy strategy) |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 149 | : mLastEventTime(0), mCurrentPointerIdBits(0), mOverrideStrategy(strategy) {} |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 150 | |
| 151 | VelocityTracker::~VelocityTracker() { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 152 | } |
| 153 | |
Yeabkal Wubshit | eca273c | 2022-10-05 19:06:40 -0700 | [diff] [blame] | 154 | bool VelocityTracker::isAxisSupported(int32_t axis) { |
| 155 | return DEFAULT_STRATEGY_BY_AXIS.find(axis) != DEFAULT_STRATEGY_BY_AXIS.end(); |
| 156 | } |
| 157 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 158 | void VelocityTracker::configureStrategy(int32_t axis) { |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 159 | const bool isDifferentialAxis = DIFFERENTIAL_AXES.find(axis) != DIFFERENTIAL_AXES.end(); |
| 160 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 161 | std::unique_ptr<VelocityTrackerStrategy> createdStrategy; |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 162 | if (mOverrideStrategy != VelocityTracker::Strategy::DEFAULT) { |
Harry Cutts | 82c791c | 2023-03-10 17:15:07 +0000 | [diff] [blame] | 163 | createdStrategy = createStrategy(mOverrideStrategy, /*deltaValues=*/isDifferentialAxis); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 164 | } else { |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 165 | createdStrategy = createStrategy(DEFAULT_STRATEGY_BY_AXIS.at(axis), |
Harry Cutts | 82c791c | 2023-03-10 17:15:07 +0000 | [diff] [blame] | 166 | /*deltaValues=*/isDifferentialAxis); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 167 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 168 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 169 | LOG_ALWAYS_FATAL_IF(createdStrategy == nullptr, |
| 170 | "Could not create velocity tracker strategy for axis '%" PRId32 "'!", axis); |
| 171 | mConfiguredStrategies[axis] = std::move(createdStrategy); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 172 | } |
| 173 | |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 174 | std::unique_ptr<VelocityTrackerStrategy> VelocityTracker::createStrategy( |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 175 | VelocityTracker::Strategy strategy, bool deltaValues) { |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 176 | switch (strategy) { |
| 177 | case VelocityTracker::Strategy::IMPULSE: |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 178 | ALOGI_IF(DEBUG_STRATEGY, "Initializing impulse strategy"); |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 179 | return std::make_unique<ImpulseVelocityTrackerStrategy>(deltaValues); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 180 | |
| 181 | case VelocityTracker::Strategy::LSQ1: |
| 182 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(1); |
| 183 | |
| 184 | case VelocityTracker::Strategy::LSQ2: |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 185 | ALOGI_IF(DEBUG_STRATEGY && !DEBUG_IMPULSE, "Initializing lsq2 strategy"); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 186 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(2); |
| 187 | |
| 188 | case VelocityTracker::Strategy::LSQ3: |
| 189 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(3); |
| 190 | |
| 191 | case VelocityTracker::Strategy::WLSQ2_DELTA: |
| 192 | return std::make_unique< |
| 193 | LeastSquaresVelocityTrackerStrategy>(2, |
| 194 | LeastSquaresVelocityTrackerStrategy:: |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 195 | Weighting::DELTA); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 196 | case VelocityTracker::Strategy::WLSQ2_CENTRAL: |
| 197 | return std::make_unique< |
| 198 | LeastSquaresVelocityTrackerStrategy>(2, |
| 199 | LeastSquaresVelocityTrackerStrategy:: |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 200 | Weighting::CENTRAL); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 201 | case VelocityTracker::Strategy::WLSQ2_RECENT: |
| 202 | return std::make_unique< |
| 203 | LeastSquaresVelocityTrackerStrategy>(2, |
| 204 | LeastSquaresVelocityTrackerStrategy:: |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 205 | Weighting::RECENT); |
Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 206 | |
| 207 | case VelocityTracker::Strategy::INT1: |
| 208 | return std::make_unique<IntegratingVelocityTrackerStrategy>(1); |
| 209 | |
| 210 | case VelocityTracker::Strategy::INT2: |
| 211 | return std::make_unique<IntegratingVelocityTrackerStrategy>(2); |
| 212 | |
| 213 | case VelocityTracker::Strategy::LEGACY: |
| 214 | return std::make_unique<LegacyVelocityTrackerStrategy>(); |
| 215 | |
| 216 | default: |
| 217 | break; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 218 | } |
Yi Kong | 5bed83b | 2018-07-17 12:53:47 -0700 | [diff] [blame] | 219 | return nullptr; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 220 | } |
| 221 | |
| 222 | void VelocityTracker::clear() { |
| 223 | mCurrentPointerIdBits.clear(); |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 224 | mActivePointerId = std::nullopt; |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 225 | mConfiguredStrategies.clear(); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 226 | } |
| 227 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 228 | void VelocityTracker::clearPointer(int32_t pointerId) { |
| 229 | mCurrentPointerIdBits.clearBit(pointerId); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 230 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 231 | if (mActivePointerId && *mActivePointerId == pointerId) { |
| 232 | // The active pointer id is being removed. Mark it invalid and try to find a new one |
| 233 | // from the remaining pointers. |
| 234 | mActivePointerId = std::nullopt; |
| 235 | if (!mCurrentPointerIdBits.isEmpty()) { |
| 236 | mActivePointerId = mCurrentPointerIdBits.firstMarkedBit(); |
| 237 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 238 | } |
| 239 | |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 240 | for (const auto& [_, strategy] : mConfiguredStrategies) { |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 241 | strategy->clearPointer(pointerId); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 242 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 243 | } |
| 244 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 245 | void VelocityTracker::addMovement(nsecs_t eventTime, int32_t pointerId, int32_t axis, |
| 246 | float position) { |
Yeabkal Wubshit | d9c4008 | 2023-07-21 19:11:52 -0700 | [diff] [blame^] | 247 | if (pointerId < 0 || pointerId > MAX_POINTER_ID) { |
| 248 | LOG(FATAL) << "Invalid pointer ID " << pointerId << " for axis " |
| 249 | << MotionEvent::getLabel(axis); |
| 250 | } |
| 251 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 252 | if (mCurrentPointerIdBits.hasBit(pointerId) && |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 253 | std::chrono::nanoseconds(eventTime - mLastEventTime) > ASSUME_POINTER_STOPPED_TIME) { |
| 254 | ALOGD_IF(DEBUG_VELOCITY, "VelocityTracker: stopped for %s, clearing state.", |
| 255 | toString(std::chrono::nanoseconds(eventTime - mLastEventTime)).c_str()); |
| 256 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 257 | // We have not received any movements for too long. Assume that all pointers |
| 258 | // have stopped. |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 259 | mConfiguredStrategies.clear(); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 260 | } |
| 261 | mLastEventTime = eventTime; |
| 262 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 263 | mCurrentPointerIdBits.markBit(pointerId); |
| 264 | if (!mActivePointerId) { |
| 265 | // Let this be the new active pointer if no active pointer is currently set |
| 266 | mActivePointerId = pointerId; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 267 | } |
| 268 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 269 | if (mConfiguredStrategies.find(axis) == mConfiguredStrategies.end()) { |
| 270 | configureStrategy(axis); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 271 | } |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 272 | mConfiguredStrategies[axis]->addMovement(eventTime, pointerId, position); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 273 | |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 274 | if (DEBUG_VELOCITY) { |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 275 | ALOGD("VelocityTracker: addMovement eventTime=%" PRId64 ", pointerId=%" PRId32 |
| 276 | ", activePointerId=%s", |
| 277 | eventTime, pointerId, toString(mActivePointerId).c_str()); |
| 278 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 279 | ALOGD(" %d: axis=%d, position=%0.3f, velocity=%s", pointerId, axis, position, |
| 280 | toString(getVelocity(axis, pointerId)).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 281 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 282 | } |
| 283 | |
| 284 | void VelocityTracker::addMovement(const MotionEvent* event) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 285 | // Stores data about which axes to process based on the incoming motion event. |
| 286 | std::set<int32_t> axesToProcess; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 287 | int32_t actionMasked = event->getActionMasked(); |
| 288 | |
| 289 | switch (actionMasked) { |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 290 | case AMOTION_EVENT_ACTION_DOWN: |
| 291 | case AMOTION_EVENT_ACTION_HOVER_ENTER: |
| 292 | // Clear all pointers on down before adding the new movement. |
| 293 | clear(); |
| 294 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); |
| 295 | break; |
| 296 | case AMOTION_EVENT_ACTION_POINTER_DOWN: { |
| 297 | // Start a new movement trace for a pointer that just went down. |
| 298 | // We do this on down instead of on up because the client may want to query the |
| 299 | // final velocity for a pointer that just went up. |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 300 | clearPointer(event->getPointerId(event->getActionIndex())); |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 301 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); |
| 302 | break; |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 303 | } |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 304 | case AMOTION_EVENT_ACTION_MOVE: |
| 305 | case AMOTION_EVENT_ACTION_HOVER_MOVE: |
| 306 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); |
| 307 | break; |
| 308 | case AMOTION_EVENT_ACTION_POINTER_UP: |
| 309 | case AMOTION_EVENT_ACTION_UP: { |
| 310 | std::chrono::nanoseconds delaySinceLastEvent(event->getEventTime() - mLastEventTime); |
| 311 | if (delaySinceLastEvent > ASSUME_POINTER_STOPPED_TIME) { |
| 312 | ALOGD_IF(DEBUG_VELOCITY, |
| 313 | "VelocityTracker: stopped for %s, clearing state upon pointer liftoff.", |
| 314 | toString(delaySinceLastEvent).c_str()); |
| 315 | // We have not received any movements for too long. Assume that all pointers |
| 316 | // have stopped. |
| 317 | for (int32_t axis : PLANAR_AXES) { |
| 318 | mConfiguredStrategies.erase(axis); |
| 319 | } |
| 320 | } |
| 321 | // These actions because they do not convey any new information about |
| 322 | // pointer movement. We also want to preserve the last known velocity of the pointers. |
| 323 | // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position |
| 324 | // of the pointers that went up. ACTION_POINTER_UP does include the new position of |
| 325 | // pointers that remained down but we will also receive an ACTION_MOVE with this |
| 326 | // information if any of them actually moved. Since we don't know how many pointers |
| 327 | // will be going up at once it makes sense to just wait for the following ACTION_MOVE |
| 328 | // before adding the movement. |
| 329 | return; |
| 330 | } |
| 331 | case AMOTION_EVENT_ACTION_SCROLL: |
| 332 | axesToProcess.insert(AMOTION_EVENT_AXIS_SCROLL); |
| 333 | break; |
| 334 | default: |
| 335 | // Ignore all other actions. |
| 336 | return; |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 337 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 338 | |
Siarhei Vishniakou | c36d21e | 2023-01-17 09:59:38 -0800 | [diff] [blame] | 339 | const size_t historySize = event->getHistorySize(); |
Siarhei Vishniakou | 69e4d0f | 2020-09-14 19:53:29 -0500 | [diff] [blame] | 340 | for (size_t h = 0; h <= historySize; h++) { |
Siarhei Vishniakou | c36d21e | 2023-01-17 09:59:38 -0800 | [diff] [blame] | 341 | const nsecs_t eventTime = event->getHistoricalEventTime(h); |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 342 | for (size_t i = 0; i < event->getPointerCount(); i++) { |
Siarhei Vishniakou | c36d21e | 2023-01-17 09:59:38 -0800 | [diff] [blame] | 343 | if (event->isResampled(i, h)) { |
| 344 | continue; // skip resampled samples |
| 345 | } |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 346 | const int32_t pointerId = event->getPointerId(i); |
| 347 | for (int32_t axis : axesToProcess) { |
| 348 | const float position = event->getHistoricalAxisValue(axis, i, h); |
| 349 | addMovement(eventTime, pointerId, axis, position); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 350 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 351 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 352 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 353 | } |
| 354 | |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 355 | std::optional<float> VelocityTracker::getVelocity(int32_t axis, int32_t pointerId) const { |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 356 | const auto& it = mConfiguredStrategies.find(axis); |
| 357 | if (it != mConfiguredStrategies.end()) { |
| 358 | return it->second->getVelocity(pointerId); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 359 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 360 | return {}; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 361 | } |
| 362 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 363 | VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units, |
| 364 | float maxVelocity) { |
| 365 | ComputedVelocity computedVelocity; |
Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 366 | for (const auto& [axis, _] : mConfiguredStrategies) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 367 | BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits); |
| 368 | while (!copyIdBits.isEmpty()) { |
| 369 | uint32_t id = copyIdBits.clearFirstMarkedBit(); |
| 370 | std::optional<float> velocity = getVelocity(axis, id); |
| 371 | if (velocity) { |
| 372 | float adjustedVelocity = |
| 373 | std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity); |
| 374 | computedVelocity.addVelocity(axis, id, adjustedVelocity); |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | return computedVelocity; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 379 | } |
| 380 | |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 381 | AccumulatingVelocityTrackerStrategy::AccumulatingVelocityTrackerStrategy( |
| 382 | nsecs_t horizonNanos, bool maintainHorizonDuringAdd) |
| 383 | : mHorizonNanos(horizonNanos), mMaintainHorizonDuringAdd(maintainHorizonDuringAdd) {} |
| 384 | |
Yeabkal Wubshit | a0e573c | 2023-03-02 21:08:14 -0800 | [diff] [blame] | 385 | void AccumulatingVelocityTrackerStrategy::clearPointer(int32_t pointerId) { |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 386 | mMovements.erase(pointerId); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 387 | } |
| 388 | |
Yeabkal Wubshit | a0e573c | 2023-03-02 21:08:14 -0800 | [diff] [blame] | 389 | void AccumulatingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId, |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 390 | float position) { |
Yeabkal Wubshit | 540dc07 | 2023-03-09 17:11:39 +0000 | [diff] [blame] | 391 | auto [ringBufferIt, _] = mMovements.try_emplace(pointerId, HISTORY_SIZE); |
| 392 | RingBuffer<Movement>& movements = ringBufferIt->second; |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 393 | const size_t size = movements.size(); |
| 394 | |
| 395 | if (size != 0 && movements[size - 1].eventTime == eventTime) { |
Siarhei Vishniakou | 346ac6a | 2019-04-10 09:58:05 -0700 | [diff] [blame] | 396 | // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates |
| 397 | // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include |
| 398 | // the new pointer. If the eventtimes for both events are identical, just update the data |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 399 | // for this time (i.e. pop out the last element, and insert the updated movement). |
Siarhei Vishniakou | 346ac6a | 2019-04-10 09:58:05 -0700 | [diff] [blame] | 400 | // We only compare against the last value, as it is likely that addMovement is called |
| 401 | // in chronological order as events occur. |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 402 | movements.popBack(); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 403 | } |
| 404 | |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 405 | movements.pushBack({eventTime, position}); |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 406 | |
| 407 | // Clear movements that do not fall within `mHorizonNanos` of the latest movement. |
| 408 | // Note that, if in the future we decide to use more movements (i.e. increase HISTORY_SIZE), |
| 409 | // we can consider making this step binary-search based, which will give us some improvement. |
| 410 | if (mMaintainHorizonDuringAdd) { |
| 411 | while (eventTime - movements[0].eventTime > mHorizonNanos) { |
| 412 | movements.popFront(); |
| 413 | } |
| 414 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 415 | } |
| 416 | |
Yeabkal Wubshit | a0e573c | 2023-03-02 21:08:14 -0800 | [diff] [blame] | 417 | // --- LeastSquaresVelocityTrackerStrategy --- |
| 418 | |
| 419 | LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree, |
| 420 | Weighting weighting) |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 421 | : AccumulatingVelocityTrackerStrategy(HORIZON /*horizonNanos*/, |
Yeabkal Wubshit | fa806e4 | 2023-03-06 18:34:07 -0800 | [diff] [blame] | 422 | true /*maintainHorizonDuringAdd*/), |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 423 | mDegree(degree), |
| 424 | mWeighting(weighting) {} |
Yeabkal Wubshit | a0e573c | 2023-03-02 21:08:14 -0800 | [diff] [blame] | 425 | |
| 426 | LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {} |
| 427 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 428 | /** |
| 429 | * Solves a linear least squares problem to obtain a N degree polynomial that fits |
| 430 | * the specified input data as nearly as possible. |
| 431 | * |
| 432 | * Returns true if a solution is found, false otherwise. |
| 433 | * |
| 434 | * The input consists of two vectors of data points X and Y with indices 0..m-1 |
| 435 | * along with a weight vector W of the same size. |
| 436 | * |
| 437 | * The output is a vector B with indices 0..n that describes a polynomial |
| 438 | * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i] |
| 439 | * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized. |
| 440 | * |
| 441 | * Accordingly, the weight vector W should be initialized by the caller with the |
| 442 | * reciprocal square root of the variance of the error in each input data point. |
| 443 | * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]). |
| 444 | * The weights express the relative importance of each data point. If the weights are |
| 445 | * all 1, then the data points are considered to be of equal importance when fitting |
| 446 | * the polynomial. It is a good idea to choose weights that diminish the importance |
| 447 | * of data points that may have higher than usual error margins. |
| 448 | * |
| 449 | * Errors among data points are assumed to be independent. W is represented here |
| 450 | * as a vector although in the literature it is typically taken to be a diagonal matrix. |
| 451 | * |
| 452 | * That is to say, the function that generated the input data can be approximated |
| 453 | * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n. |
| 454 | * |
| 455 | * The coefficient of determination (R^2) is also returned to describe the goodness |
| 456 | * of fit of the model for the given data. It is a value between 0 and 1, where 1 |
| 457 | * indicates perfect correspondence. |
| 458 | * |
| 459 | * This function first expands the X vector to a m by n matrix A such that |
| 460 | * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then |
| 461 | * multiplies it by w[i]./ |
| 462 | * |
| 463 | * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q |
| 464 | * and an m by n upper triangular matrix R. Because R is upper triangular (lower |
| 465 | * part is all zeroes), we can simplify the decomposition into an m by n matrix |
| 466 | * Q1 and a n by n matrix R1 such that A = Q1 R1. |
| 467 | * |
| 468 | * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y) |
| 469 | * to find B. |
| 470 | * |
| 471 | * For efficiency, we lay out A and Q column-wise in memory because we frequently |
| 472 | * operate on the column vectors. Conversely, we lay out R row-wise. |
| 473 | * |
| 474 | * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares |
| 475 | * http://en.wikipedia.org/wiki/Gram-Schmidt |
| 476 | */ |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 477 | static std::optional<float> solveLeastSquares(const std::vector<float>& x, |
| 478 | const std::vector<float>& y, |
| 479 | const std::vector<float>& w, uint32_t n) { |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 480 | const size_t m = x.size(); |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 481 | |
| 482 | ALOGD_IF(DEBUG_STRATEGY, "solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n), |
| 483 | vectorToString(x).c_str(), vectorToString(y).c_str(), vectorToString(w).c_str()); |
| 484 | |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 485 | LOG_ALWAYS_FATAL_IF(m != y.size() || m != w.size(), "Mismatched vector sizes"); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 486 | |
| 487 | // Expand the X vector to a matrix A, pre-multiplied by the weights. |
| 488 | float a[n][m]; // column-major order |
| 489 | for (uint32_t h = 0; h < m; h++) { |
| 490 | a[0][h] = w[h]; |
| 491 | for (uint32_t i = 1; i < n; i++) { |
| 492 | a[i][h] = a[i - 1][h] * x[h]; |
| 493 | } |
| 494 | } |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 495 | |
| 496 | ALOGD_IF(DEBUG_STRATEGY, " - a=%s", |
Harry Cutts | 82c791c | 2023-03-10 17:15:07 +0000 | [diff] [blame] | 497 | matrixToString(&a[0][0], m, n, /*rowMajor=*/false).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 498 | |
| 499 | // Apply the Gram-Schmidt process to A to obtain its QR decomposition. |
| 500 | float q[n][m]; // orthonormal basis, column-major order |
| 501 | float r[n][n]; // upper triangular matrix, row-major order |
| 502 | for (uint32_t j = 0; j < n; j++) { |
| 503 | for (uint32_t h = 0; h < m; h++) { |
| 504 | q[j][h] = a[j][h]; |
| 505 | } |
| 506 | for (uint32_t i = 0; i < j; i++) { |
| 507 | float dot = vectorDot(&q[j][0], &q[i][0], m); |
| 508 | for (uint32_t h = 0; h < m; h++) { |
| 509 | q[j][h] -= dot * q[i][h]; |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | float norm = vectorNorm(&q[j][0], m); |
| 514 | if (norm < 0.000001f) { |
| 515 | // vectors are linearly dependent or zero so no solution |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 516 | ALOGD_IF(DEBUG_STRATEGY, " - no solution, norm=%f", norm); |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 517 | return {}; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 518 | } |
| 519 | |
| 520 | float invNorm = 1.0f / norm; |
| 521 | for (uint32_t h = 0; h < m; h++) { |
| 522 | q[j][h] *= invNorm; |
| 523 | } |
| 524 | for (uint32_t i = 0; i < n; i++) { |
| 525 | r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m); |
| 526 | } |
| 527 | } |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 528 | if (DEBUG_STRATEGY) { |
Harry Cutts | 82c791c | 2023-03-10 17:15:07 +0000 | [diff] [blame] | 529 | ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, /*rowMajor=*/false).c_str()); |
| 530 | ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, /*rowMajor=*/true).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 531 | |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 532 | // calculate QR, if we factored A correctly then QR should equal A |
| 533 | float qr[n][m]; |
| 534 | for (uint32_t h = 0; h < m; h++) { |
| 535 | for (uint32_t i = 0; i < n; i++) { |
| 536 | qr[i][h] = 0; |
| 537 | for (uint32_t j = 0; j < n; j++) { |
| 538 | qr[i][h] += q[j][h] * r[j][i]; |
| 539 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 540 | } |
| 541 | } |
Harry Cutts | 82c791c | 2023-03-10 17:15:07 +0000 | [diff] [blame] | 542 | ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, /*rowMajor=*/false).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 543 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 544 | |
| 545 | // Solve R B = Qt W Y to find B. This is easy because R is upper triangular. |
| 546 | // We just work from bottom-right to top-left calculating B's coefficients. |
| 547 | float wy[m]; |
| 548 | for (uint32_t h = 0; h < m; h++) { |
| 549 | wy[h] = y[h] * w[h]; |
| 550 | } |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 551 | std::array<float, VelocityTracker::MAX_DEGREE + 1> outB; |
Dan Austin | 389ddba | 2015-09-22 14:32:03 -0700 | [diff] [blame] | 552 | for (uint32_t i = n; i != 0; ) { |
| 553 | i--; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 554 | outB[i] = vectorDot(&q[i][0], wy, m); |
| 555 | for (uint32_t j = n - 1; j > i; j--) { |
| 556 | outB[i] -= r[i][j] * outB[j]; |
| 557 | } |
| 558 | outB[i] /= r[i][i]; |
| 559 | } |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 560 | |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 561 | ALOGD_IF(DEBUG_STRATEGY, " - b=%s", vectorToString(outB.data(), n).c_str()); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 562 | |
| 563 | // Calculate the coefficient of determination as 1 - (SSerr / SStot) where |
| 564 | // SSerr is the residual sum of squares (variance of the error), |
| 565 | // and SStot is the total sum of squares (variance of the data) where each |
| 566 | // has been weighted. |
| 567 | float ymean = 0; |
| 568 | for (uint32_t h = 0; h < m; h++) { |
| 569 | ymean += y[h]; |
| 570 | } |
| 571 | ymean /= m; |
| 572 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 573 | if (DEBUG_STRATEGY) { |
| 574 | float sserr = 0; |
| 575 | float sstot = 0; |
| 576 | for (uint32_t h = 0; h < m; h++) { |
| 577 | float err = y[h] - outB[0]; |
| 578 | float term = 1; |
| 579 | for (uint32_t i = 1; i < n; i++) { |
| 580 | term *= x[h]; |
| 581 | err -= term * outB[i]; |
| 582 | } |
| 583 | sserr += w[h] * w[h] * err * err; |
| 584 | float var = y[h] - ymean; |
| 585 | sstot += w[h] * w[h] * var * var; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 586 | } |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 587 | ALOGD(" - sserr=%f", sserr); |
| 588 | ALOGD(" - sstot=%f", sstot); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 589 | } |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 590 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 591 | return outB[1]; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 592 | } |
| 593 | |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 594 | /* |
| 595 | * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to |
| 596 | * the default implementation |
| 597 | */ |
Yeabkal Wubshit | fa806e4 | 2023-03-06 18:34:07 -0800 | [diff] [blame] | 598 | std::optional<float> LeastSquaresVelocityTrackerStrategy::solveUnweightedLeastSquaresDeg2( |
| 599 | const RingBuffer<Movement>& movements) const { |
| 600 | // Solving y = a*x^2 + b*x + c, where |
| 601 | // - "x" is age (i.e. duration since latest movement) of the movemnets |
| 602 | // - "y" is positions of the movements. |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 603 | float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0; |
| 604 | |
Yeabkal Wubshit | fa806e4 | 2023-03-06 18:34:07 -0800 | [diff] [blame] | 605 | const size_t count = movements.size(); |
| 606 | const Movement& newestMovement = movements[count - 1]; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 607 | for (size_t i = 0; i < count; i++) { |
Yeabkal Wubshit | fa806e4 | 2023-03-06 18:34:07 -0800 | [diff] [blame] | 608 | const Movement& movement = movements[i]; |
| 609 | nsecs_t age = newestMovement.eventTime - movement.eventTime; |
| 610 | float xi = -age * SECONDS_PER_NANO; |
| 611 | float yi = movement.position; |
| 612 | |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 613 | float xi2 = xi*xi; |
| 614 | float xi3 = xi2*xi; |
| 615 | float xi4 = xi3*xi; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 616 | float xiyi = xi*yi; |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 617 | float xi2yi = xi2*yi; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 618 | |
| 619 | sxi += xi; |
| 620 | sxi2 += xi2; |
| 621 | sxiyi += xiyi; |
| 622 | sxi2yi += xi2yi; |
| 623 | syi += yi; |
| 624 | sxi3 += xi3; |
| 625 | sxi4 += xi4; |
| 626 | } |
| 627 | |
| 628 | float Sxx = sxi2 - sxi*sxi / count; |
| 629 | float Sxy = sxiyi - sxi*syi / count; |
| 630 | float Sxx2 = sxi3 - sxi*sxi2 / count; |
| 631 | float Sx2y = sxi2yi - sxi2*syi / count; |
| 632 | float Sx2x2 = sxi4 - sxi2*sxi2 / count; |
| 633 | |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 634 | float denominator = Sxx*Sx2x2 - Sxx2*Sxx2; |
| 635 | if (denominator == 0) { |
| 636 | ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2); |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 637 | return std::nullopt; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 638 | } |
Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 639 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 640 | return (Sxy * Sx2x2 - Sx2y * Sxx2) / denominator; |
Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 641 | } |
| 642 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 643 | std::optional<float> LeastSquaresVelocityTrackerStrategy::getVelocity(int32_t pointerId) const { |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 644 | const auto movementIt = mMovements.find(pointerId); |
| 645 | if (movementIt == mMovements.end()) { |
| 646 | return std::nullopt; // no data |
| 647 | } |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 648 | |
| 649 | const RingBuffer<Movement>& movements = movementIt->second; |
| 650 | const size_t size = movements.size(); |
| 651 | if (size == 0) { |
| 652 | return std::nullopt; // no data |
| 653 | } |
| 654 | |
Yeabkal Wubshit | fa806e4 | 2023-03-06 18:34:07 -0800 | [diff] [blame] | 655 | uint32_t degree = mDegree; |
| 656 | if (degree > size - 1) { |
| 657 | degree = size - 1; |
| 658 | } |
| 659 | |
| 660 | if (degree <= 0) { |
| 661 | return std::nullopt; |
| 662 | } |
| 663 | |
| 664 | if (degree == 2 && mWeighting == Weighting::NONE) { |
| 665 | // Optimize unweighted, quadratic polynomial fit |
| 666 | return solveUnweightedLeastSquaresDeg2(movements); |
| 667 | } |
| 668 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 669 | // Iterate over movement samples in reverse time order and collect samples. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 670 | std::vector<float> positions; |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 671 | std::vector<float> w; |
| 672 | std::vector<float> time; |
| 673 | |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 674 | const Movement& newestMovement = movements[size - 1]; |
| 675 | for (ssize_t i = size - 1; i >= 0; i--) { |
| 676 | const Movement& movement = movements[i]; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 677 | nsecs_t age = newestMovement.eventTime - movement.eventTime; |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 678 | positions.push_back(movement.position); |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 679 | w.push_back(chooseWeight(pointerId, i)); |
Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 680 | time.push_back(-age * 0.000000001f); |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 681 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 682 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 683 | // General case for an Nth degree polynomial fit |
| 684 | return solveLeastSquares(time, positions, w, degree + 1); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 685 | } |
| 686 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 687 | float LeastSquaresVelocityTrackerStrategy::chooseWeight(int32_t pointerId, uint32_t index) const { |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 688 | const RingBuffer<Movement>& movements = mMovements.at(pointerId); |
| 689 | const size_t size = movements.size(); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 690 | switch (mWeighting) { |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 691 | case Weighting::DELTA: { |
| 692 | // Weight points based on how much time elapsed between them and the next |
| 693 | // point so that points that "cover" a shorter time span are weighed less. |
| 694 | // delta 0ms: 0.5 |
| 695 | // delta 10ms: 1.0 |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 696 | if (index == size - 1) { |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 697 | return 1.0f; |
| 698 | } |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 699 | float deltaMillis = |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 700 | (movements[index + 1].eventTime - movements[index].eventTime) * 0.000001f; |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 701 | if (deltaMillis < 0) { |
| 702 | return 0.5f; |
| 703 | } |
| 704 | if (deltaMillis < 10) { |
| 705 | return 0.5f + deltaMillis * 0.05; |
| 706 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 707 | return 1.0f; |
| 708 | } |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 709 | |
| 710 | case Weighting::CENTRAL: { |
| 711 | // Weight points based on their age, weighing very recent and very old points less. |
| 712 | // age 0ms: 0.5 |
| 713 | // age 10ms: 1.0 |
| 714 | // age 50ms: 1.0 |
| 715 | // age 60ms: 0.5 |
| 716 | float ageMillis = |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 717 | (movements[size - 1].eventTime - movements[index].eventTime) * 0.000001f; |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 718 | if (ageMillis < 0) { |
| 719 | return 0.5f; |
| 720 | } |
| 721 | if (ageMillis < 10) { |
| 722 | return 0.5f + ageMillis * 0.05; |
| 723 | } |
| 724 | if (ageMillis < 50) { |
| 725 | return 1.0f; |
| 726 | } |
| 727 | if (ageMillis < 60) { |
| 728 | return 0.5f + (60 - ageMillis) * 0.05; |
| 729 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 730 | return 0.5f; |
| 731 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 732 | |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 733 | case Weighting::RECENT: { |
| 734 | // Weight points based on their age, weighing older points less. |
| 735 | // age 0ms: 1.0 |
| 736 | // age 50ms: 1.0 |
| 737 | // age 100ms: 0.5 |
| 738 | float ageMillis = |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 739 | (movements[size - 1].eventTime - movements[index].eventTime) * 0.000001f; |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 740 | if (ageMillis < 50) { |
| 741 | return 1.0f; |
| 742 | } |
| 743 | if (ageMillis < 100) { |
| 744 | return 0.5f + (100 - ageMillis) * 0.01f; |
| 745 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 746 | return 0.5f; |
| 747 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 748 | |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 749 | case Weighting::NONE: |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 750 | return 1.0f; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 751 | } |
| 752 | } |
| 753 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 754 | // --- IntegratingVelocityTrackerStrategy --- |
| 755 | |
| 756 | IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) : |
| 757 | mDegree(degree) { |
| 758 | } |
| 759 | |
| 760 | IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() { |
| 761 | } |
| 762 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 763 | void IntegratingVelocityTrackerStrategy::clearPointer(int32_t pointerId) { |
| 764 | mPointerIdBits.clearBit(pointerId); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 765 | } |
| 766 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 767 | void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId, |
| 768 | float position) { |
| 769 | State& state = mPointerState[pointerId]; |
| 770 | if (mPointerIdBits.hasBit(pointerId)) { |
| 771 | updateState(state, eventTime, position); |
| 772 | } else { |
| 773 | initState(state, eventTime, position); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 774 | } |
| 775 | |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 776 | mPointerIdBits.markBit(pointerId); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 777 | } |
| 778 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 779 | std::optional<float> IntegratingVelocityTrackerStrategy::getVelocity(int32_t pointerId) const { |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 780 | if (mPointerIdBits.hasBit(pointerId)) { |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 781 | return mPointerState[pointerId].vel; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 782 | } |
| 783 | |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 784 | return std::nullopt; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 785 | } |
| 786 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 787 | void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime, |
| 788 | float pos) const { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 789 | state.updateTime = eventTime; |
| 790 | state.degree = 0; |
| 791 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 792 | state.pos = pos; |
| 793 | state.accel = 0; |
| 794 | state.vel = 0; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 795 | } |
| 796 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 797 | void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime, |
| 798 | float pos) const { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 799 | const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS; |
| 800 | const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds |
| 801 | |
| 802 | if (eventTime <= state.updateTime + MIN_TIME_DELTA) { |
| 803 | return; |
| 804 | } |
| 805 | |
| 806 | float dt = (eventTime - state.updateTime) * 0.000000001f; |
| 807 | state.updateTime = eventTime; |
| 808 | |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 809 | float vel = (pos - state.pos) / dt; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 810 | if (state.degree == 0) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 811 | state.vel = vel; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 812 | state.degree = 1; |
| 813 | } else { |
| 814 | float alpha = dt / (FILTER_TIME_CONSTANT + dt); |
| 815 | if (mDegree == 1) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 816 | state.vel += (vel - state.vel) * alpha; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 817 | } else { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 818 | float accel = (vel - state.vel) / dt; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 819 | if (state.degree == 1) { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 820 | state.accel = accel; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 821 | state.degree = 2; |
| 822 | } else { |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 823 | state.accel += (accel - state.accel) * alpha; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 824 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 825 | state.vel += (state.accel * dt) * alpha; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 826 | } |
| 827 | } |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 828 | state.pos = pos; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 829 | } |
| 830 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 831 | // --- LegacyVelocityTrackerStrategy --- |
| 832 | |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 833 | LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() |
| 834 | : AccumulatingVelocityTrackerStrategy(HORIZON /*horizonNanos*/, |
| 835 | false /*maintainHorizonDuringAdd*/) {} |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 836 | |
| 837 | LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() { |
| 838 | } |
| 839 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 840 | std::optional<float> LegacyVelocityTrackerStrategy::getVelocity(int32_t pointerId) const { |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 841 | const auto movementIt = mMovements.find(pointerId); |
| 842 | if (movementIt == mMovements.end()) { |
Siarhei Vishniakou | 657a173 | 2023-01-12 11:58:52 -0800 | [diff] [blame] | 843 | return std::nullopt; // no data |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 844 | } |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 845 | |
| 846 | const RingBuffer<Movement>& movements = movementIt->second; |
| 847 | const size_t size = movements.size(); |
| 848 | if (size == 0) { |
| 849 | return std::nullopt; // no data |
| 850 | } |
| 851 | |
| 852 | const Movement& newestMovement = movements[size - 1]; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 853 | |
| 854 | // Find the oldest sample that contains the pointer and that is not older than HORIZON. |
| 855 | nsecs_t minTime = newestMovement.eventTime - HORIZON; |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 856 | uint32_t oldestIndex = size - 1; |
| 857 | for (ssize_t i = size - 1; i >= 0; i--) { |
| 858 | const Movement& nextOldestMovement = movements[i]; |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 859 | if (nextOldestMovement.eventTime < minTime) { |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 860 | break; |
| 861 | } |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 862 | oldestIndex = i; |
| 863 | } |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 864 | |
| 865 | // Calculate an exponentially weighted moving average of the velocity estimate |
| 866 | // at different points in time measured relative to the oldest sample. |
| 867 | // This is essentially an IIR filter. Newer samples are weighted more heavily |
| 868 | // than older samples. Samples at equal time points are weighted more or less |
| 869 | // equally. |
| 870 | // |
| 871 | // One tricky problem is that the sample data may be poorly conditioned. |
| 872 | // Sometimes samples arrive very close together in time which can cause us to |
| 873 | // overestimate the velocity at that time point. Most samples might be measured |
| 874 | // 16ms apart but some consecutive samples could be only 0.5sm apart because |
| 875 | // the hardware or driver reports them irregularly or in bursts. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 876 | float accumV = 0; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 877 | uint32_t samplesUsed = 0; |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 878 | const Movement& oldestMovement = movements[oldestIndex]; |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 879 | float oldestPosition = oldestMovement.position; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 880 | nsecs_t lastDuration = 0; |
| 881 | |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 882 | for (size_t i = oldestIndex; i < size; i++) { |
| 883 | const Movement& movement = movements[i]; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 884 | nsecs_t duration = movement.eventTime - oldestMovement.eventTime; |
| 885 | |
| 886 | // If the duration between samples is small, we may significantly overestimate |
| 887 | // the velocity. Consequently, we impose a minimum duration constraint on the |
| 888 | // samples that we include in the calculation. |
| 889 | if (duration >= MIN_DURATION) { |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 890 | float position = movement.position; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 891 | float scale = 1000000000.0f / duration; // one over time delta in seconds |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 892 | float v = (position - oldestPosition) * scale; |
| 893 | accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration); |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 894 | lastDuration = duration; |
| 895 | samplesUsed += 1; |
| 896 | } |
| 897 | } |
| 898 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 899 | if (samplesUsed) { |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 900 | return accumV; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 901 | } |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 902 | return std::nullopt; |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 903 | } |
| 904 | |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 905 | // --- ImpulseVelocityTrackerStrategy --- |
| 906 | |
Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 907 | ImpulseVelocityTrackerStrategy::ImpulseVelocityTrackerStrategy(bool deltaValues) |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 908 | : AccumulatingVelocityTrackerStrategy(HORIZON /*horizonNanos*/, |
| 909 | true /*maintainHorizonDuringAdd*/), |
| 910 | mDeltaValues(deltaValues) {} |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 911 | |
| 912 | ImpulseVelocityTrackerStrategy::~ImpulseVelocityTrackerStrategy() { |
| 913 | } |
| 914 | |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 915 | /** |
| 916 | * Calculate the total impulse provided to the screen and the resulting velocity. |
| 917 | * |
| 918 | * The touchscreen is modeled as a physical object. |
| 919 | * Initial condition is discussed below, but for now suppose that v(t=0) = 0 |
| 920 | * |
| 921 | * The kinetic energy of the object at the release is E=0.5*m*v^2 |
| 922 | * Then vfinal = sqrt(2E/m). The goal is to calculate E. |
| 923 | * |
| 924 | * The kinetic energy at the release is equal to the total work done on the object by the finger. |
| 925 | * The total work W is the sum of all dW along the path. |
| 926 | * |
| 927 | * dW = F*dx, where dx is the piece of path traveled. |
| 928 | * Force is change of momentum over time, F = dp/dt = m dv/dt. |
| 929 | * Then substituting: |
| 930 | * dW = m (dv/dt) * dx = m * v * dv |
| 931 | * |
| 932 | * Summing along the path, we get: |
| 933 | * W = sum(dW) = sum(m * v * dv) = m * sum(v * dv) |
| 934 | * Since the mass stays constant, the equation for final velocity is: |
| 935 | * vfinal = sqrt(2*sum(v * dv)) |
| 936 | * |
| 937 | * Here, |
| 938 | * dv : change of velocity = (v[i+1]-v[i]) |
| 939 | * dx : change of distance = (x[i+1]-x[i]) |
| 940 | * dt : change of time = (t[i+1]-t[i]) |
| 941 | * v : instantaneous velocity = dx/dt |
| 942 | * |
| 943 | * The final formula is: |
| 944 | * vfinal = sqrt(2) * sqrt(sum((v[i]-v[i-1])*|v[i]|)) for all i |
| 945 | * The absolute value is needed to properly account for the sign. If the velocity over a |
| 946 | * particular segment descreases, then this indicates braking, which means that negative |
| 947 | * work was done. So for two positive, but decreasing, velocities, this contribution would be |
| 948 | * negative and will cause a smaller final velocity. |
| 949 | * |
| 950 | * Initial condition |
| 951 | * There are two ways to deal with initial condition: |
| 952 | * 1) Assume that v(0) = 0, which would mean that the screen is initially at rest. |
| 953 | * This is not entirely accurate. We are only taking the past X ms of touch data, where X is |
| 954 | * currently equal to 100. However, a touch event that created a fling probably lasted for longer |
| 955 | * than that, which would mean that the user has already been interacting with the touchscreen |
| 956 | * and it has probably already been moving. |
| 957 | * 2) Assume that the touchscreen has already been moving at a certain velocity, calculate this |
| 958 | * initial velocity and the equivalent energy, and start with this initial energy. |
| 959 | * Consider an example where we have the following data, consisting of 3 points: |
| 960 | * time: t0, t1, t2 |
| 961 | * x : x0, x1, x2 |
| 962 | * v : 0 , v1, v2 |
| 963 | * Here is what will happen in each of these scenarios: |
| 964 | * 1) By directly applying the formula above with the v(0) = 0 boundary condition, we will get |
| 965 | * vfinal = sqrt(2*(|v1|*(v1-v0) + |v2|*(v2-v1))). This can be simplified since v0=0 |
| 966 | * vfinal = sqrt(2*(|v1|*v1 + |v2|*(v2-v1))) = sqrt(2*(v1^2 + |v2|*(v2 - v1))) |
| 967 | * since velocity is a real number |
| 968 | * 2) If we treat the screen as already moving, then it must already have an energy (per mass) |
| 969 | * equal to 1/2*v1^2. Then the initial energy should be 1/2*v1*2, and only the second segment |
| 970 | * will contribute to the total kinetic energy (since we can effectively consider that v0=v1). |
| 971 | * This will give the following expression for the final velocity: |
| 972 | * vfinal = sqrt(2*(1/2*v1^2 + |v2|*(v2-v1))) |
| 973 | * This analysis can be generalized to an arbitrary number of samples. |
| 974 | * |
| 975 | * |
| 976 | * Comparing the two equations above, we see that the only mathematical difference |
| 977 | * is the factor of 1/2 in front of the first velocity term. |
| 978 | * This boundary condition would allow for the "proper" calculation of the case when all of the |
| 979 | * samples are equally spaced in time and distance, which should suggest a constant velocity. |
| 980 | * |
| 981 | * Note that approach 2) is sensitive to the proper ordering of the data in time, since |
| 982 | * the boundary condition must be applied to the oldest sample to be accurate. |
| 983 | */ |
Siarhei Vishniakou | 97b5e18 | 2017-09-01 13:52:33 -0700 | [diff] [blame] | 984 | static float kineticEnergyToVelocity(float work) { |
| 985 | static constexpr float sqrt2 = 1.41421356237; |
| 986 | return (work < 0 ? -1.0 : 1.0) * sqrtf(fabsf(work)) * sqrt2; |
| 987 | } |
| 988 | |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 989 | std::optional<float> ImpulseVelocityTrackerStrategy::getVelocity(int32_t pointerId) const { |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 990 | const auto movementIt = mMovements.find(pointerId); |
| 991 | if (movementIt == mMovements.end()) { |
| 992 | return std::nullopt; // no data |
| 993 | } |
| 994 | |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 995 | const RingBuffer<Movement>& movements = movementIt->second; |
| 996 | const size_t size = movements.size(); |
| 997 | if (size == 0) { |
| 998 | return std::nullopt; // no data |
| 999 | } |
| 1000 | |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 1001 | float work = 0; |
| 1002 | for (size_t i = 0; i < size - 1; i++) { |
| 1003 | const Movement& mvt = movements[i]; |
| 1004 | const Movement& nextMvt = movements[i + 1]; |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1005 | |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 1006 | float vprev = kineticEnergyToVelocity(work); |
| 1007 | float delta = mDeltaValues ? nextMvt.position : nextMvt.position - mvt.position; |
| 1008 | float vcurr = delta / (SECONDS_PER_NANO * (nextMvt.eventTime - mvt.eventTime)); |
| 1009 | work += (vcurr - vprev) * fabsf(vcurr); |
| 1010 | |
| 1011 | if (i == 0) { |
| 1012 | work *= 0.5; // initial condition, case 2) above |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1013 | } |
Yeabkal Wubshit | 64f090f | 2023-03-03 17:35:11 -0800 | [diff] [blame] | 1014 | } |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1015 | |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 1016 | const float velocity = kineticEnergyToVelocity(work); |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 1017 | ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", velocity); |
Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 1018 | |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1019 | if (DEBUG_IMPULSE) { |
| 1020 | // TODO(b/134179997): delete this block once the switch to 'impulse' is complete. |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1021 | // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons. |
| 1022 | // X axis chosen arbitrarily for velocity comparisons. |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1023 | VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2); |
Yeabkal Wubshit | 4a678b2 | 2023-02-23 17:03:40 -0800 | [diff] [blame] | 1024 | for (size_t i = 0; i < size; i++) { |
| 1025 | const Movement& mvt = movements[i]; |
| 1026 | lsq2.addMovement(mvt.eventTime, pointerId, AMOTION_EVENT_AXIS_X, mvt.position); |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1027 | } |
Siarhei Vishniakou | 8d23203 | 2023-01-11 08:17:21 -0800 | [diff] [blame] | 1028 | std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId); |
Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1029 | if (v) { |
| 1030 | ALOGD("lsq2 velocity: %.1f", *v); |
Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1031 | } else { |
| 1032 | ALOGD("lsq2 velocity: could not compute velocity"); |
| 1033 | } |
Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 1034 | } |
Yeabkal Wubshit | 9b4443f | 2023-02-23 23:35:07 -0800 | [diff] [blame] | 1035 | return velocity; |
Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1036 | } |
| 1037 | |
Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1038 | } // namespace android |