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