blob: a88aa485fc80589aa1981642d45beb9ca6a0fd75 [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001/*
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 Brown5912f952013-07-01 19:10:31 -070018
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -070019#include <array>
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070020#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070021#include <limits.h>
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070022#include <math.h>
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -070023#include <optional>
Jeff Brown5912f952013-07-01 19:10:31 -070024
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -070025#include <android-base/stringprintf.h>
Siarhei Vishniakou657a1732023-01-12 11:58:52 -080026#include <input/PrintTools.h>
Jeff Brown5912f952013-07-01 19:10:31 -070027#include <input/VelocityTracker.h>
28#include <utils/BitSet.h>
Jeff Brown5912f952013-07-01 19:10:31 -070029#include <utils/Timers.h>
30
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +000031using std::literals::chrono_literals::operator""ms;
32
Jeff Brown5912f952013-07-01 19:10:31 -070033namespace android {
34
Siarhei Vishniakou276467b2022-03-17 09:43:28 -070035/**
36 * Log debug messages about velocity tracking.
37 * Enable this via "adb shell setprop log.tag.VelocityTrackerVelocity DEBUG" (requires restart)
38 */
39const 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 */
46const 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 */
53const bool DEBUG_IMPULSE =
54 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Impulse", ANDROID_LOG_INFO);
55
Jeff Brown5912f952013-07-01 19:10:31 -070056// Nanoseconds per milliseconds.
57static const nsecs_t NANOS_PER_MS = 1000000;
58
Yeabkal Wubshit67b3ab02022-09-16 00:18:17 -070059// All axes supported for velocity tracking, mapped to their default strategies.
60// Although other strategies are available for testing and comparison purposes,
61// the default strategy is the one that applications will actually use. Be very careful
62// when adjusting the default strategy because it can dramatically affect
63// (often in a bad way) the user experience.
64static const std::map<int32_t, VelocityTracker::Strategy> DEFAULT_STRATEGY_BY_AXIS =
65 {{AMOTION_EVENT_AXIS_X, VelocityTracker::Strategy::LSQ2},
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -070066 {AMOTION_EVENT_AXIS_Y, VelocityTracker::Strategy::LSQ2},
67 {AMOTION_EVENT_AXIS_SCROLL, VelocityTracker::Strategy::IMPULSE}};
Yeabkal Wubshit67b3ab02022-09-16 00:18:17 -070068
69// Axes specifying location on a 2D plane (i.e. X and Y).
70static const std::set<int32_t> PLANAR_AXES = {AMOTION_EVENT_AXIS_X, AMOTION_EVENT_AXIS_Y};
71
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -070072// Axes whose motion values are differential values (i.e. deltas).
73static const std::set<int32_t> DIFFERENTIAL_AXES = {AMOTION_EVENT_AXIS_SCROLL};
74
Jeff Brown5912f952013-07-01 19:10:31 -070075// Threshold for determining that a pointer has stopped moving.
76// Some input devices do not send ACTION_MOVE events in the case where a pointer has
77// stopped. We need to detect this case so that we can accurately predict the
78// velocity after the pointer starts moving again.
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +000079static const std::chrono::duration ASSUME_POINTER_STOPPED_TIME = 40ms;
Jeff Brown5912f952013-07-01 19:10:31 -070080
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +000081static std::string toString(std::chrono::nanoseconds t) {
82 std::stringstream stream;
83 stream.precision(1);
84 stream << std::fixed << std::chrono::duration<float, std::milli>(t).count() << " ms";
85 return stream.str();
86}
Jeff Brown5912f952013-07-01 19:10:31 -070087
88static float vectorDot(const float* a, const float* b, uint32_t m) {
89 float r = 0;
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070090 for (size_t i = 0; i < m; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -070091 r += *(a++) * *(b++);
92 }
93 return r;
94}
95
96static float vectorNorm(const float* a, uint32_t m) {
97 float r = 0;
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -070098 for (size_t i = 0; i < m; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -070099 float t = *(a++);
100 r += t * t;
101 }
102 return sqrtf(r);
103}
104
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700105static std::string vectorToString(const float* a, uint32_t m) {
106 std::string str;
107 str += "[";
Siarhei Vishniakou7b9d1892017-07-05 18:58:41 -0700108 for (size_t i = 0; i < m; i++) {
109 if (i) {
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700110 str += ",";
Jeff Brown5912f952013-07-01 19:10:31 -0700111 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700112 str += android::base::StringPrintf(" %f", *(a++));
Jeff Brown5912f952013-07-01 19:10:31 -0700113 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700114 str += " ]";
Jeff Brown5912f952013-07-01 19:10:31 -0700115 return str;
116}
117
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700118static std::string vectorToString(const std::vector<float>& v) {
119 return vectorToString(v.data(), v.size());
120}
121
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700122static std::string matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) {
123 std::string str;
124 str = "[";
Jeff Brown5912f952013-07-01 19:10:31 -0700125 for (size_t i = 0; i < m; i++) {
126 if (i) {
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700127 str += ",";
Jeff Brown5912f952013-07-01 19:10:31 -0700128 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700129 str += " [";
Jeff Brown5912f952013-07-01 19:10:31 -0700130 for (size_t j = 0; j < n; j++) {
131 if (j) {
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700132 str += ",";
Jeff Brown5912f952013-07-01 19:10:31 -0700133 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700134 str += android::base::StringPrintf(" %f", a[rowMajor ? i * n + j : j * m + i]);
Jeff Brown5912f952013-07-01 19:10:31 -0700135 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700136 str += " ]";
Jeff Brown5912f952013-07-01 19:10:31 -0700137 }
Siarhei Vishniakouec2727e2017-07-06 10:22:03 -0700138 str += " ]";
Jeff Brown5912f952013-07-01 19:10:31 -0700139 return str;
140}
Jeff Brown5912f952013-07-01 19:10:31 -0700141
142
143// --- VelocityTracker ---
144
Chris Yef8591482020-04-17 11:49:17 -0700145VelocityTracker::VelocityTracker(const Strategy strategy)
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800146 : mLastEventTime(0), mCurrentPointerIdBits(0), mOverrideStrategy(strategy) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700147
148VelocityTracker::~VelocityTracker() {
Jeff Brown5912f952013-07-01 19:10:31 -0700149}
150
Yeabkal Wubshiteca273c2022-10-05 19:06:40 -0700151bool VelocityTracker::isAxisSupported(int32_t axis) {
152 return DEFAULT_STRATEGY_BY_AXIS.find(axis) != DEFAULT_STRATEGY_BY_AXIS.end();
153}
154
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700155void VelocityTracker::configureStrategy(int32_t axis) {
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700156 const bool isDifferentialAxis = DIFFERENTIAL_AXES.find(axis) != DIFFERENTIAL_AXES.end();
157
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000158 std::unique_ptr<VelocityTrackerStrategy> createdStrategy;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700159 if (mOverrideStrategy != VelocityTracker::Strategy::DEFAULT) {
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700160 createdStrategy = createStrategy(mOverrideStrategy, isDifferentialAxis /* deltaValues */);
Chris Yef8591482020-04-17 11:49:17 -0700161 } else {
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700162 createdStrategy = createStrategy(DEFAULT_STRATEGY_BY_AXIS.at(axis),
163 isDifferentialAxis /* deltaValues */);
Chris Yef8591482020-04-17 11:49:17 -0700164 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000165
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700166 LOG_ALWAYS_FATAL_IF(createdStrategy == nullptr,
167 "Could not create velocity tracker strategy for axis '%" PRId32 "'!", axis);
168 mConfiguredStrategies[axis] = std::move(createdStrategy);
Jeff Brown5912f952013-07-01 19:10:31 -0700169}
170
Chris Yef8591482020-04-17 11:49:17 -0700171std::unique_ptr<VelocityTrackerStrategy> VelocityTracker::createStrategy(
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700172 VelocityTracker::Strategy strategy, bool deltaValues) {
Chris Yef8591482020-04-17 11:49:17 -0700173 switch (strategy) {
174 case VelocityTracker::Strategy::IMPULSE:
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000175 ALOGI_IF(DEBUG_STRATEGY, "Initializing impulse strategy");
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700176 return std::make_unique<ImpulseVelocityTrackerStrategy>(deltaValues);
Chris Yef8591482020-04-17 11:49:17 -0700177
178 case VelocityTracker::Strategy::LSQ1:
179 return std::make_unique<LeastSquaresVelocityTrackerStrategy>(1);
180
181 case VelocityTracker::Strategy::LSQ2:
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000182 ALOGI_IF(DEBUG_STRATEGY && !DEBUG_IMPULSE, "Initializing lsq2 strategy");
Chris Yef8591482020-04-17 11:49:17 -0700183 return std::make_unique<LeastSquaresVelocityTrackerStrategy>(2);
184
185 case VelocityTracker::Strategy::LSQ3:
186 return std::make_unique<LeastSquaresVelocityTrackerStrategy>(3);
187
188 case VelocityTracker::Strategy::WLSQ2_DELTA:
189 return std::make_unique<
190 LeastSquaresVelocityTrackerStrategy>(2,
191 LeastSquaresVelocityTrackerStrategy::
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800192 Weighting::DELTA);
Chris Yef8591482020-04-17 11:49:17 -0700193 case VelocityTracker::Strategy::WLSQ2_CENTRAL:
194 return std::make_unique<
195 LeastSquaresVelocityTrackerStrategy>(2,
196 LeastSquaresVelocityTrackerStrategy::
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800197 Weighting::CENTRAL);
Chris Yef8591482020-04-17 11:49:17 -0700198 case VelocityTracker::Strategy::WLSQ2_RECENT:
199 return std::make_unique<
200 LeastSquaresVelocityTrackerStrategy>(2,
201 LeastSquaresVelocityTrackerStrategy::
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800202 Weighting::RECENT);
Chris Yef8591482020-04-17 11:49:17 -0700203
204 case VelocityTracker::Strategy::INT1:
205 return std::make_unique<IntegratingVelocityTrackerStrategy>(1);
206
207 case VelocityTracker::Strategy::INT2:
208 return std::make_unique<IntegratingVelocityTrackerStrategy>(2);
209
210 case VelocityTracker::Strategy::LEGACY:
211 return std::make_unique<LegacyVelocityTrackerStrategy>();
212
213 default:
214 break;
Jeff Brown5912f952013-07-01 19:10:31 -0700215 }
Yi Kong5bed83b2018-07-17 12:53:47 -0700216 return nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700217}
218
219void VelocityTracker::clear() {
220 mCurrentPointerIdBits.clear();
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800221 mActivePointerId = std::nullopt;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700222 mConfiguredStrategies.clear();
Jeff Brown5912f952013-07-01 19:10:31 -0700223}
224
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800225void VelocityTracker::clearPointer(int32_t pointerId) {
226 mCurrentPointerIdBits.clearBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700227
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800228 if (mActivePointerId && *mActivePointerId == pointerId) {
229 // The active pointer id is being removed. Mark it invalid and try to find a new one
230 // from the remaining pointers.
231 mActivePointerId = std::nullopt;
232 if (!mCurrentPointerIdBits.isEmpty()) {
233 mActivePointerId = mCurrentPointerIdBits.firstMarkedBit();
234 }
Jeff Brown5912f952013-07-01 19:10:31 -0700235 }
236
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700237 for (const auto& [_, strategy] : mConfiguredStrategies) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800238 strategy->clearPointer(pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000239 }
Jeff Brown5912f952013-07-01 19:10:31 -0700240}
241
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800242void VelocityTracker::addMovement(nsecs_t eventTime, int32_t pointerId, int32_t axis,
243 float position) {
244 if (mCurrentPointerIdBits.hasBit(pointerId) &&
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000245 std::chrono::nanoseconds(eventTime - mLastEventTime) > ASSUME_POINTER_STOPPED_TIME) {
246 ALOGD_IF(DEBUG_VELOCITY, "VelocityTracker: stopped for %s, clearing state.",
247 toString(std::chrono::nanoseconds(eventTime - mLastEventTime)).c_str());
248
Jeff Brown5912f952013-07-01 19:10:31 -0700249 // We have not received any movements for too long. Assume that all pointers
250 // have stopped.
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700251 mConfiguredStrategies.clear();
Jeff Brown5912f952013-07-01 19:10:31 -0700252 }
253 mLastEventTime = eventTime;
254
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800255 mCurrentPointerIdBits.markBit(pointerId);
256 if (!mActivePointerId) {
257 // Let this be the new active pointer if no active pointer is currently set
258 mActivePointerId = pointerId;
Jeff Brown5912f952013-07-01 19:10:31 -0700259 }
260
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800261 if (mConfiguredStrategies.find(axis) == mConfiguredStrategies.end()) {
262 configureStrategy(axis);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000263 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800264 mConfiguredStrategies[axis]->addMovement(eventTime, pointerId, position);
Jeff Brown5912f952013-07-01 19:10:31 -0700265
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700266 if (DEBUG_VELOCITY) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800267 ALOGD("VelocityTracker: addMovement eventTime=%" PRId64 ", pointerId=%" PRId32
268 ", activePointerId=%s",
269 eventTime, pointerId, toString(mActivePointerId).c_str());
270
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800271 ALOGD(" %d: axis=%d, position=%0.3f, velocity=%s", pointerId, axis, position,
272 toString(getVelocity(axis, pointerId)).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700273 }
Jeff Brown5912f952013-07-01 19:10:31 -0700274}
275
276void VelocityTracker::addMovement(const MotionEvent* event) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000277 // Stores data about which axes to process based on the incoming motion event.
278 std::set<int32_t> axesToProcess;
Jeff Brown5912f952013-07-01 19:10:31 -0700279 int32_t actionMasked = event->getActionMasked();
280
281 switch (actionMasked) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800282 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();
286 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
287 break;
288 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
289 // Start a new movement trace for a pointer that just went down.
290 // We do this on down instead of on up because the client may want to query the
291 // final velocity for a pointer that just went up.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800292 clearPointer(event->getPointerId(event->getActionIndex()));
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800293 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
294 break;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000295 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800296 case AMOTION_EVENT_ACTION_MOVE:
297 case AMOTION_EVENT_ACTION_HOVER_MOVE:
298 axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end());
299 break;
300 case AMOTION_EVENT_ACTION_POINTER_UP:
301 case AMOTION_EVENT_ACTION_UP: {
302 std::chrono::nanoseconds delaySinceLastEvent(event->getEventTime() - mLastEventTime);
303 if (delaySinceLastEvent > ASSUME_POINTER_STOPPED_TIME) {
304 ALOGD_IF(DEBUG_VELOCITY,
305 "VelocityTracker: stopped for %s, clearing state upon pointer liftoff.",
306 toString(delaySinceLastEvent).c_str());
307 // We have not received any movements for too long. Assume that all pointers
308 // have stopped.
309 for (int32_t axis : PLANAR_AXES) {
310 mConfiguredStrategies.erase(axis);
311 }
312 }
313 // These actions because they do not convey any new information about
314 // pointer movement. We also want to preserve the last known velocity of the pointers.
315 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
316 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
317 // pointers that remained down but we will also receive an ACTION_MOVE with this
318 // information if any of them actually moved. Since we don't know how many pointers
319 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
320 // before adding the movement.
321 return;
322 }
323 case AMOTION_EVENT_ACTION_SCROLL:
324 axesToProcess.insert(AMOTION_EVENT_AXIS_SCROLL);
325 break;
326 default:
327 // Ignore all other actions.
328 return;
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000329 }
Jeff Brown5912f952013-07-01 19:10:31 -0700330
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800331 const size_t historySize = event->getHistorySize();
Siarhei Vishniakou69e4d0f2020-09-14 19:53:29 -0500332 for (size_t h = 0; h <= historySize; h++) {
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800333 const nsecs_t eventTime = event->getHistoricalEventTime(h);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800334 for (size_t i = 0; i < event->getPointerCount(); i++) {
Siarhei Vishniakouc36d21e2023-01-17 09:59:38 -0800335 if (event->isResampled(i, h)) {
336 continue; // skip resampled samples
337 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800338 const int32_t pointerId = event->getPointerId(i);
339 for (int32_t axis : axesToProcess) {
340 const float position = event->getHistoricalAxisValue(axis, i, h);
341 addMovement(eventTime, pointerId, axis, position);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000342 }
Jeff Brown5912f952013-07-01 19:10:31 -0700343 }
Jeff Brown5912f952013-07-01 19:10:31 -0700344 }
Jeff Brown5912f952013-07-01 19:10:31 -0700345}
346
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800347std::optional<float> VelocityTracker::getVelocity(int32_t axis, int32_t pointerId) const {
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800348 const auto& it = mConfiguredStrategies.find(axis);
349 if (it != mConfiguredStrategies.end()) {
350 return it->second->getVelocity(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700351 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000352 return {};
Jeff Brown5912f952013-07-01 19:10:31 -0700353}
354
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000355VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units,
356 float maxVelocity) {
357 ComputedVelocity computedVelocity;
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700358 for (const auto& [axis, _] : mConfiguredStrategies) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000359 BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits);
360 while (!copyIdBits.isEmpty()) {
361 uint32_t id = copyIdBits.clearFirstMarkedBit();
362 std::optional<float> velocity = getVelocity(axis, id);
363 if (velocity) {
364 float adjustedVelocity =
365 std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity);
366 computedVelocity.addVelocity(axis, id, adjustedVelocity);
367 }
368 }
369 }
370 return computedVelocity;
Jeff Brown5912f952013-07-01 19:10:31 -0700371}
372
Jeff Brown5912f952013-07-01 19:10:31 -0700373// --- LeastSquaresVelocityTrackerStrategy ---
374
Yeabkal Wubshit47ff7082022-09-10 23:09:15 -0700375LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree,
376 Weighting weighting)
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800377 : mDegree(degree), mWeighting(weighting) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700378
379LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {
380}
381
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800382void LeastSquaresVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
383 mIndex.erase(pointerId);
384 mMovements.erase(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700385}
386
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800387void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
388 float position) {
389 // If data for this pointer already exists, we have a valid entry at the position of
390 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
391 // to the next position in the circular buffer and write the new Movement there. Otherwise,
392 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
393 // for this pointer and write to the first position.
394 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
395 auto [indexIt, _] = mIndex.insert({pointerId, 0});
396 size_t& index = indexIt->second;
397 if (!inserted && movementIt->second[index].eventTime != eventTime) {
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700398 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
399 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
400 // the new pointer. If the eventtimes for both events are identical, just update the data
401 // for this time.
402 // We only compare against the last value, as it is likely that addMovement is called
403 // in chronological order as events occur.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800404 index++;
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700405 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800406 if (index == HISTORY_SIZE) {
407 index = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700408 }
409
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800410 Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700411 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800412 movement.position = position;
Jeff Brown5912f952013-07-01 19:10:31 -0700413}
414
415/**
416 * Solves a linear least squares problem to obtain a N degree polynomial that fits
417 * the specified input data as nearly as possible.
418 *
419 * Returns true if a solution is found, false otherwise.
420 *
421 * The input consists of two vectors of data points X and Y with indices 0..m-1
422 * along with a weight vector W of the same size.
423 *
424 * The output is a vector B with indices 0..n that describes a polynomial
425 * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i]
426 * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized.
427 *
428 * Accordingly, the weight vector W should be initialized by the caller with the
429 * reciprocal square root of the variance of the error in each input data point.
430 * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]).
431 * The weights express the relative importance of each data point. If the weights are
432 * all 1, then the data points are considered to be of equal importance when fitting
433 * the polynomial. It is a good idea to choose weights that diminish the importance
434 * of data points that may have higher than usual error margins.
435 *
436 * Errors among data points are assumed to be independent. W is represented here
437 * as a vector although in the literature it is typically taken to be a diagonal matrix.
438 *
439 * That is to say, the function that generated the input data can be approximated
440 * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
441 *
442 * The coefficient of determination (R^2) is also returned to describe the goodness
443 * of fit of the model for the given data. It is a value between 0 and 1, where 1
444 * indicates perfect correspondence.
445 *
446 * This function first expands the X vector to a m by n matrix A such that
447 * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then
448 * multiplies it by w[i]./
449 *
450 * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
451 * and an m by n upper triangular matrix R. Because R is upper triangular (lower
452 * part is all zeroes), we can simplify the decomposition into an m by n matrix
453 * Q1 and a n by n matrix R1 such that A = Q1 R1.
454 *
455 * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y)
456 * to find B.
457 *
458 * For efficiency, we lay out A and Q column-wise in memory because we frequently
459 * operate on the column vectors. Conversely, we lay out R row-wise.
460 *
461 * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
462 * http://en.wikipedia.org/wiki/Gram-Schmidt
463 */
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800464static std::optional<float> solveLeastSquares(const std::vector<float>& x,
465 const std::vector<float>& y,
466 const std::vector<float>& w, uint32_t n) {
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500467 const size_t m = x.size();
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000468
469 ALOGD_IF(DEBUG_STRATEGY, "solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n),
470 vectorToString(x).c_str(), vectorToString(y).c_str(), vectorToString(w).c_str());
471
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500472 LOG_ALWAYS_FATAL_IF(m != y.size() || m != w.size(), "Mismatched vector sizes");
Jeff Brown5912f952013-07-01 19:10:31 -0700473
474 // Expand the X vector to a matrix A, pre-multiplied by the weights.
475 float a[n][m]; // column-major order
476 for (uint32_t h = 0; h < m; h++) {
477 a[0][h] = w[h];
478 for (uint32_t i = 1; i < n; i++) {
479 a[i][h] = a[i - 1][h] * x[h];
480 }
481 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000482
483 ALOGD_IF(DEBUG_STRATEGY, " - a=%s",
484 matrixToString(&a[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700485
486 // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
487 float q[n][m]; // orthonormal basis, column-major order
488 float r[n][n]; // upper triangular matrix, row-major order
489 for (uint32_t j = 0; j < n; j++) {
490 for (uint32_t h = 0; h < m; h++) {
491 q[j][h] = a[j][h];
492 }
493 for (uint32_t i = 0; i < j; i++) {
494 float dot = vectorDot(&q[j][0], &q[i][0], m);
495 for (uint32_t h = 0; h < m; h++) {
496 q[j][h] -= dot * q[i][h];
497 }
498 }
499
500 float norm = vectorNorm(&q[j][0], m);
501 if (norm < 0.000001f) {
502 // vectors are linearly dependent or zero so no solution
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000503 ALOGD_IF(DEBUG_STRATEGY, " - no solution, norm=%f", norm);
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800504 return {};
Jeff Brown5912f952013-07-01 19:10:31 -0700505 }
506
507 float invNorm = 1.0f / norm;
508 for (uint32_t h = 0; h < m; h++) {
509 q[j][h] *= invNorm;
510 }
511 for (uint32_t i = 0; i < n; i++) {
512 r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
513 }
514 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700515 if (DEBUG_STRATEGY) {
516 ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).c_str());
517 ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700518
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700519 // calculate QR, if we factored A correctly then QR should equal A
520 float qr[n][m];
521 for (uint32_t h = 0; h < m; h++) {
522 for (uint32_t i = 0; i < n; i++) {
523 qr[i][h] = 0;
524 for (uint32_t j = 0; j < n; j++) {
525 qr[i][h] += q[j][h] * r[j][i];
526 }
Jeff Brown5912f952013-07-01 19:10:31 -0700527 }
528 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -0700529 ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700530 }
Jeff Brown5912f952013-07-01 19:10:31 -0700531
532 // Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
533 // We just work from bottom-right to top-left calculating B's coefficients.
534 float wy[m];
535 for (uint32_t h = 0; h < m; h++) {
536 wy[h] = y[h] * w[h];
537 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800538 std::array<float, VelocityTracker::MAX_DEGREE + 1> outB;
Dan Austin389ddba2015-09-22 14:32:03 -0700539 for (uint32_t i = n; i != 0; ) {
540 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700541 outB[i] = vectorDot(&q[i][0], wy, m);
542 for (uint32_t j = n - 1; j > i; j--) {
543 outB[i] -= r[i][j] * outB[j];
544 }
545 outB[i] /= r[i][i];
546 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000547
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800548 ALOGD_IF(DEBUG_STRATEGY, " - b=%s", vectorToString(outB.data(), n).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700549
550 // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
551 // SSerr is the residual sum of squares (variance of the error),
552 // and SStot is the total sum of squares (variance of the data) where each
553 // has been weighted.
554 float ymean = 0;
555 for (uint32_t h = 0; h < m; h++) {
556 ymean += y[h];
557 }
558 ymean /= m;
559
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800560 if (DEBUG_STRATEGY) {
561 float sserr = 0;
562 float sstot = 0;
563 for (uint32_t h = 0; h < m; h++) {
564 float err = y[h] - outB[0];
565 float term = 1;
566 for (uint32_t i = 1; i < n; i++) {
567 term *= x[h];
568 err -= term * outB[i];
569 }
570 sserr += w[h] * w[h] * err * err;
571 float var = y[h] - ymean;
572 sstot += w[h] * w[h] * var * var;
Jeff Brown5912f952013-07-01 19:10:31 -0700573 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800574 ALOGD(" - sserr=%f", sserr);
575 ALOGD(" - sstot=%f", sstot);
Jeff Brown5912f952013-07-01 19:10:31 -0700576 }
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +0000577
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800578 return outB[1];
Jeff Brown5912f952013-07-01 19:10:31 -0700579}
580
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100581/*
582 * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to
583 * the default implementation
584 */
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800585static std::optional<float> solveUnweightedLeastSquaresDeg2(const std::vector<float>& x,
586 const std::vector<float>& y) {
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500587 const size_t count = x.size();
588 LOG_ALWAYS_FATAL_IF(count != y.size(), "Mismatching array sizes");
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700589 // Solving y = a*x^2 + b*x + c
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100590 float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0;
591
592 for (size_t i = 0; i < count; i++) {
593 float xi = x[i];
594 float yi = y[i];
595 float xi2 = xi*xi;
596 float xi3 = xi2*xi;
597 float xi4 = xi3*xi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100598 float xiyi = xi*yi;
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700599 float xi2yi = xi2*yi;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100600
601 sxi += xi;
602 sxi2 += xi2;
603 sxiyi += xiyi;
604 sxi2yi += xi2yi;
605 syi += yi;
606 sxi3 += xi3;
607 sxi4 += xi4;
608 }
609
610 float Sxx = sxi2 - sxi*sxi / count;
611 float Sxy = sxiyi - sxi*syi / count;
612 float Sxx2 = sxi3 - sxi*sxi2 / count;
613 float Sx2y = sxi2yi - sxi2*syi / count;
614 float Sx2x2 = sxi4 - sxi2*sxi2 / count;
615
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100616 float denominator = Sxx*Sx2x2 - Sxx2*Sxx2;
617 if (denominator == 0) {
618 ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2);
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700619 return std::nullopt;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100620 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700621
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800622 return (Sxy * Sx2x2 - Sx2y * Sxx2) / denominator;
Siarhei Vishniakou489d38e2017-06-16 17:16:25 +0100623}
624
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800625std::optional<float> LeastSquaresVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800626 const auto movementIt = mMovements.find(pointerId);
627 if (movementIt == mMovements.end()) {
628 return std::nullopt; // no data
629 }
Jeff Brown5912f952013-07-01 19:10:31 -0700630 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000631 std::vector<float> positions;
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500632 std::vector<float> w;
633 std::vector<float> time;
634
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800635 uint32_t index = mIndex.at(pointerId);
636 const Movement& newestMovement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700637 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800638 const Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700639
640 nsecs_t age = newestMovement.eventTime - movement.eventTime;
641 if (age > HORIZON) {
642 break;
643 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800644 if (movement.eventTime == 0 && index != 0) {
645 // All eventTime's are initialized to 0. In this fixed-width circular buffer, it's
646 // possible that not all entries are valid. We use a time=0 as a signal for those
647 // uninitialized values. If we encounter a time of 0 in a position
648 // that's > 0, it means that we hit the block where the data wasn't initialized.
649 // We still don't know whether the value at index=0, with eventTime=0 is valid.
650 // However, that's only possible when the value is by itself. So there's no hard in
651 // processing it anyways, since the velocity for a single point is zero, and this
652 // situation will only be encountered in artificial circumstances (in tests).
653 // In practice, time will never be 0.
654 break;
655 }
656 positions.push_back(movement.position);
657 w.push_back(chooseWeight(pointerId, index));
Siarhei Vishniakou81e8b162020-09-14 22:10:11 -0500658 time.push_back(-age * 0.000000001f);
Jeff Brown5912f952013-07-01 19:10:31 -0700659 index = (index == 0 ? HISTORY_SIZE : index) - 1;
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000660 } while (positions.size() < HISTORY_SIZE);
Jeff Brown5912f952013-07-01 19:10:31 -0700661
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000662 const size_t m = positions.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700663 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800664 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700665 }
666
667 // Calculate a least squares polynomial fit.
668 uint32_t degree = mDegree;
669 if (degree > m - 1) {
670 degree = m - 1;
671 }
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700672
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800673 if (degree <= 0) {
674 return std::nullopt;
675 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800676 if (degree == 2 && mWeighting == Weighting::NONE) {
Siarhei Vishniakoue96bc7a2018-09-06 10:19:16 -0700677 // Optimize unweighted, quadratic polynomial fit
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800678 return solveUnweightedLeastSquaresDeg2(time, positions);
Jeff Brown5912f952013-07-01 19:10:31 -0700679 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800680 // General case for an Nth degree polynomial fit
681 return solveLeastSquares(time, positions, w, degree + 1);
Jeff Brown5912f952013-07-01 19:10:31 -0700682}
683
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800684float LeastSquaresVelocityTrackerStrategy::chooseWeight(int32_t pointerId, uint32_t index) const {
685 const std::array<Movement, HISTORY_SIZE>& movements = mMovements.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700686 switch (mWeighting) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800687 case Weighting::DELTA: {
688 // Weight points based on how much time elapsed between them and the next
689 // point so that points that "cover" a shorter time span are weighed less.
690 // delta 0ms: 0.5
691 // delta 10ms: 1.0
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800692 if (index == mIndex.at(pointerId)) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800693 return 1.0f;
694 }
695 uint32_t nextIndex = (index + 1) % HISTORY_SIZE;
696 float deltaMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800697 (movements[nextIndex].eventTime - movements[index].eventTime) * 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800698 if (deltaMillis < 0) {
699 return 0.5f;
700 }
701 if (deltaMillis < 10) {
702 return 0.5f + deltaMillis * 0.05;
703 }
Jeff Brown5912f952013-07-01 19:10:31 -0700704 return 1.0f;
705 }
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800706
707 case Weighting::CENTRAL: {
708 // Weight points based on their age, weighing very recent and very old points less.
709 // age 0ms: 0.5
710 // age 10ms: 1.0
711 // age 50ms: 1.0
712 // age 60ms: 0.5
713 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800714 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
715 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800716 if (ageMillis < 0) {
717 return 0.5f;
718 }
719 if (ageMillis < 10) {
720 return 0.5f + ageMillis * 0.05;
721 }
722 if (ageMillis < 50) {
723 return 1.0f;
724 }
725 if (ageMillis < 60) {
726 return 0.5f + (60 - ageMillis) * 0.05;
727 }
Jeff Brown5912f952013-07-01 19:10:31 -0700728 return 0.5f;
729 }
Jeff Brown5912f952013-07-01 19:10:31 -0700730
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800731 case Weighting::RECENT: {
732 // Weight points based on their age, weighing older points less.
733 // age 0ms: 1.0
734 // age 50ms: 1.0
735 // age 100ms: 0.5
736 float ageMillis =
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800737 (movements[mIndex.at(pointerId)].eventTime - movements[index].eventTime) *
738 0.000001f;
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800739 if (ageMillis < 50) {
740 return 1.0f;
741 }
742 if (ageMillis < 100) {
743 return 0.5f + (100 - ageMillis) * 0.01f;
744 }
Jeff Brown5912f952013-07-01 19:10:31 -0700745 return 0.5f;
746 }
Jeff Brown5912f952013-07-01 19:10:31 -0700747
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800748 case Weighting::NONE:
Jeff Brown5912f952013-07-01 19:10:31 -0700749 return 1.0f;
Jeff Brown5912f952013-07-01 19:10:31 -0700750 }
751}
752
Jeff Brown5912f952013-07-01 19:10:31 -0700753// --- IntegratingVelocityTrackerStrategy ---
754
755IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) :
756 mDegree(degree) {
757}
758
759IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() {
760}
761
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800762void IntegratingVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
763 mPointerIdBits.clearBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700764}
765
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800766void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
767 float position) {
768 State& state = mPointerState[pointerId];
769 if (mPointerIdBits.hasBit(pointerId)) {
770 updateState(state, eventTime, position);
771 } else {
772 initState(state, eventTime, position);
Jeff Brown5912f952013-07-01 19:10:31 -0700773 }
774
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800775 mPointerIdBits.markBit(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700776}
777
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800778std::optional<float> IntegratingVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800779 if (mPointerIdBits.hasBit(pointerId)) {
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800780 return mPointerState[pointerId].vel;
Jeff Brown5912f952013-07-01 19:10:31 -0700781 }
782
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800783 return std::nullopt;
Jeff Brown5912f952013-07-01 19:10:31 -0700784}
785
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000786void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime,
787 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700788 state.updateTime = eventTime;
789 state.degree = 0;
790
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000791 state.pos = pos;
792 state.accel = 0;
793 state.vel = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700794}
795
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000796void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime,
797 float pos) const {
Jeff Brown5912f952013-07-01 19:10:31 -0700798 const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS;
799 const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds
800
801 if (eventTime <= state.updateTime + MIN_TIME_DELTA) {
802 return;
803 }
804
805 float dt = (eventTime - state.updateTime) * 0.000000001f;
806 state.updateTime = eventTime;
807
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000808 float vel = (pos - state.pos) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700809 if (state.degree == 0) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000810 state.vel = vel;
Jeff Brown5912f952013-07-01 19:10:31 -0700811 state.degree = 1;
812 } else {
813 float alpha = dt / (FILTER_TIME_CONSTANT + dt);
814 if (mDegree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000815 state.vel += (vel - state.vel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700816 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000817 float accel = (vel - state.vel) / dt;
Jeff Brown5912f952013-07-01 19:10:31 -0700818 if (state.degree == 1) {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000819 state.accel = accel;
Jeff Brown5912f952013-07-01 19:10:31 -0700820 state.degree = 2;
821 } else {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000822 state.accel += (accel - state.accel) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700823 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000824 state.vel += (state.accel * dt) * alpha;
Jeff Brown5912f952013-07-01 19:10:31 -0700825 }
826 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000827 state.pos = pos;
Jeff Brown5912f952013-07-01 19:10:31 -0700828}
829
Jeff Brown5912f952013-07-01 19:10:31 -0700830// --- LegacyVelocityTrackerStrategy ---
831
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800832LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() {}
Jeff Brown5912f952013-07-01 19:10:31 -0700833
834LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() {
835}
836
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800837void LegacyVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
838 mIndex.erase(pointerId);
839 mMovements.erase(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700840}
841
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800842void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
843 float position) {
844 // If data for this pointer already exists, we have a valid entry at the position of
845 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
846 // to the next position in the circular buffer and write the new Movement there. Otherwise,
847 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
848 // for this pointer and write to the first position.
849 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
850 auto [indexIt, _] = mIndex.insert({pointerId, 0});
851 size_t& index = indexIt->second;
852 if (!inserted && movementIt->second[index].eventTime != eventTime) {
853 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
854 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
855 // the new pointer. If the eventtimes for both events are identical, just update the data
856 // for this time.
857 // We only compare against the last value, as it is likely that addMovement is called
858 // in chronological order as events occur.
859 index++;
860 }
861 if (index == HISTORY_SIZE) {
862 index = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700863 }
864
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800865 Movement& movement = movementIt->second[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700866 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800867 movement.position = position;
Jeff Brown5912f952013-07-01 19:10:31 -0700868}
869
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800870std::optional<float> LegacyVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800871 const auto movementIt = mMovements.find(pointerId);
872 if (movementIt == mMovements.end()) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -0800873 return std::nullopt; // no data
Jeff Brown5912f952013-07-01 19:10:31 -0700874 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800875 const Movement& newestMovement = movementIt->second[mIndex.at(pointerId)];
Jeff Brown5912f952013-07-01 19:10:31 -0700876
877 // Find the oldest sample that contains the pointer and that is not older than HORIZON.
878 nsecs_t minTime = newestMovement.eventTime - HORIZON;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800879 uint32_t oldestIndex = mIndex.at(pointerId);
Jeff Brown5912f952013-07-01 19:10:31 -0700880 uint32_t numTouches = 1;
881 do {
882 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800883 const Movement& nextOldestMovement = mMovements.at(pointerId)[nextOldestIndex];
884 if (nextOldestMovement.eventTime < minTime) {
Jeff Brown5912f952013-07-01 19:10:31 -0700885 break;
886 }
887 oldestIndex = nextOldestIndex;
888 } while (++numTouches < HISTORY_SIZE);
889
890 // Calculate an exponentially weighted moving average of the velocity estimate
891 // at different points in time measured relative to the oldest sample.
892 // This is essentially an IIR filter. Newer samples are weighted more heavily
893 // than older samples. Samples at equal time points are weighted more or less
894 // equally.
895 //
896 // One tricky problem is that the sample data may be poorly conditioned.
897 // Sometimes samples arrive very close together in time which can cause us to
898 // overestimate the velocity at that time point. Most samples might be measured
899 // 16ms apart but some consecutive samples could be only 0.5sm apart because
900 // the hardware or driver reports them irregularly or in bursts.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000901 float accumV = 0;
Jeff Brown5912f952013-07-01 19:10:31 -0700902 uint32_t index = oldestIndex;
903 uint32_t samplesUsed = 0;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800904 const Movement& oldestMovement = mMovements.at(pointerId)[oldestIndex];
905 float oldestPosition = oldestMovement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700906 nsecs_t lastDuration = 0;
907
908 while (numTouches-- > 1) {
909 if (++index == HISTORY_SIZE) {
910 index = 0;
911 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800912 const Movement& movement = mMovements.at(pointerId)[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700913 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
914
915 // If the duration between samples is small, we may significantly overestimate
916 // the velocity. Consequently, we impose a minimum duration constraint on the
917 // samples that we include in the calculation.
918 if (duration >= MIN_DURATION) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800919 float position = movement.position;
Jeff Brown5912f952013-07-01 19:10:31 -0700920 float scale = 1000000000.0f / duration; // one over time delta in seconds
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +0000921 float v = (position - oldestPosition) * scale;
922 accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration);
Jeff Brown5912f952013-07-01 19:10:31 -0700923 lastDuration = duration;
924 samplesUsed += 1;
925 }
926 }
927
Jeff Brown5912f952013-07-01 19:10:31 -0700928 if (samplesUsed) {
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800929 return accumV;
Jeff Brown5912f952013-07-01 19:10:31 -0700930 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -0800931 return std::nullopt;
Jeff Brown5912f952013-07-01 19:10:31 -0700932}
933
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100934// --- ImpulseVelocityTrackerStrategy ---
935
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -0700936ImpulseVelocityTrackerStrategy::ImpulseVelocityTrackerStrategy(bool deltaValues)
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800937 : mDeltaValues(deltaValues) {}
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100938
939ImpulseVelocityTrackerStrategy::~ImpulseVelocityTrackerStrategy() {
940}
941
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800942void ImpulseVelocityTrackerStrategy::clearPointer(int32_t pointerId) {
943 mIndex.erase(pointerId);
944 mMovements.erase(pointerId);
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100945}
946
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800947void ImpulseVelocityTrackerStrategy::addMovement(nsecs_t eventTime, int32_t pointerId,
948 float position) {
949 // If data for this pointer already exists, we have a valid entry at the position of
950 // mIndex[pointerId] and mMovements[pointerId]. In that case, we need to advance the index
951 // to the next position in the circular buffer and write the new Movement there. Otherwise,
952 // if this is a first movement for this pointer, we initialize the maps mIndex and mMovements
953 // for this pointer and write to the first position.
954 auto [movementIt, inserted] = mMovements.insert({pointerId, {}});
955 auto [indexIt, _] = mIndex.insert({pointerId, 0});
956 size_t& index = indexIt->second;
957 if (!inserted && movementIt->second[index].eventTime != eventTime) {
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700958 // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
959 // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
960 // the new pointer. If the eventtimes for both events are identical, just update the data
961 // for this time.
962 // We only compare against the last value, as it is likely that addMovement is called
963 // in chronological order as events occur.
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800964 index++;
Siarhei Vishniakou346ac6a2019-04-10 09:58:05 -0700965 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800966 if (index == HISTORY_SIZE) {
967 index = 0;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100968 }
969
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800970 Movement& movement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100971 movement.eventTime = eventTime;
Siarhei Vishniakou8d232032023-01-11 08:17:21 -0800972 movement.position = position;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +0100973}
974
975/**
976 * Calculate the total impulse provided to the screen and the resulting velocity.
977 *
978 * The touchscreen is modeled as a physical object.
979 * Initial condition is discussed below, but for now suppose that v(t=0) = 0
980 *
981 * The kinetic energy of the object at the release is E=0.5*m*v^2
982 * Then vfinal = sqrt(2E/m). The goal is to calculate E.
983 *
984 * The kinetic energy at the release is equal to the total work done on the object by the finger.
985 * The total work W is the sum of all dW along the path.
986 *
987 * dW = F*dx, where dx is the piece of path traveled.
988 * Force is change of momentum over time, F = dp/dt = m dv/dt.
989 * Then substituting:
990 * dW = m (dv/dt) * dx = m * v * dv
991 *
992 * Summing along the path, we get:
993 * W = sum(dW) = sum(m * v * dv) = m * sum(v * dv)
994 * Since the mass stays constant, the equation for final velocity is:
995 * vfinal = sqrt(2*sum(v * dv))
996 *
997 * Here,
998 * dv : change of velocity = (v[i+1]-v[i])
999 * dx : change of distance = (x[i+1]-x[i])
1000 * dt : change of time = (t[i+1]-t[i])
1001 * v : instantaneous velocity = dx/dt
1002 *
1003 * The final formula is:
1004 * vfinal = sqrt(2) * sqrt(sum((v[i]-v[i-1])*|v[i]|)) for all i
1005 * The absolute value is needed to properly account for the sign. If the velocity over a
1006 * particular segment descreases, then this indicates braking, which means that negative
1007 * work was done. So for two positive, but decreasing, velocities, this contribution would be
1008 * negative and will cause a smaller final velocity.
1009 *
1010 * Initial condition
1011 * There are two ways to deal with initial condition:
1012 * 1) Assume that v(0) = 0, which would mean that the screen is initially at rest.
1013 * This is not entirely accurate. We are only taking the past X ms of touch data, where X is
1014 * currently equal to 100. However, a touch event that created a fling probably lasted for longer
1015 * than that, which would mean that the user has already been interacting with the touchscreen
1016 * and it has probably already been moving.
1017 * 2) Assume that the touchscreen has already been moving at a certain velocity, calculate this
1018 * initial velocity and the equivalent energy, and start with this initial energy.
1019 * Consider an example where we have the following data, consisting of 3 points:
1020 * time: t0, t1, t2
1021 * x : x0, x1, x2
1022 * v : 0 , v1, v2
1023 * Here is what will happen in each of these scenarios:
1024 * 1) By directly applying the formula above with the v(0) = 0 boundary condition, we will get
1025 * vfinal = sqrt(2*(|v1|*(v1-v0) + |v2|*(v2-v1))). This can be simplified since v0=0
1026 * vfinal = sqrt(2*(|v1|*v1 + |v2|*(v2-v1))) = sqrt(2*(v1^2 + |v2|*(v2 - v1)))
1027 * since velocity is a real number
1028 * 2) If we treat the screen as already moving, then it must already have an energy (per mass)
1029 * equal to 1/2*v1^2. Then the initial energy should be 1/2*v1*2, and only the second segment
1030 * will contribute to the total kinetic energy (since we can effectively consider that v0=v1).
1031 * This will give the following expression for the final velocity:
1032 * vfinal = sqrt(2*(1/2*v1^2 + |v2|*(v2-v1)))
1033 * This analysis can be generalized to an arbitrary number of samples.
1034 *
1035 *
1036 * Comparing the two equations above, we see that the only mathematical difference
1037 * is the factor of 1/2 in front of the first velocity term.
1038 * This boundary condition would allow for the "proper" calculation of the case when all of the
1039 * samples are equally spaced in time and distance, which should suggest a constant velocity.
1040 *
1041 * Note that approach 2) is sensitive to the proper ordering of the data in time, since
1042 * the boundary condition must be applied to the oldest sample to be accurate.
1043 */
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001044static float kineticEnergyToVelocity(float work) {
1045 static constexpr float sqrt2 = 1.41421356237;
1046 return (work < 0 ? -1.0 : 1.0) * sqrtf(fabsf(work)) * sqrt2;
1047}
1048
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001049static float calculateImpulseVelocity(const nsecs_t* t, const float* x, size_t count,
1050 bool deltaValues) {
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001051 // The input should be in reversed time order (most recent sample at index i=0)
1052 // t[i] is in nanoseconds, but due to FP arithmetic, convert to seconds inside this function
Siarhei Vishniakou6de8f5e2018-03-02 18:48:15 -08001053 static constexpr float SECONDS_PER_NANO = 1E-9;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001054
1055 if (count < 2) {
1056 return 0; // if 0 or 1 points, velocity is zero
1057 }
1058 if (t[1] > t[0]) { // Algorithm will still work, but not perfectly
1059 ALOGE("Samples provided to calculateImpulseVelocity in the wrong order");
1060 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001061
1062 // If the data values are delta values, we do not have to calculate deltas here.
1063 // We can use the delta values directly, along with the calculated time deltas.
1064 // Since the data value input is in reversed time order:
1065 // [a] for non-delta inputs, instantenous velocity = (x[i] - x[i-1])/(t[i] - t[i-1])
1066 // [b] for delta inputs, instantenous velocity = -x[i-1]/(t[i] - t[i - 1])
1067 // e.g., let the non-delta values are: V = [2, 3, 7], the equivalent deltas are D = [2, 1, 4].
1068 // Since the input is in reversed time order, the input values for this function would be
1069 // V'=[7, 3, 2] and D'=[4, 1, 2] for the non-delta and delta values, respectively.
1070 //
1071 // The equivalent of {(V'[2] - V'[1]) = 2 - 3 = -1} would be {-D'[1] = -1}
1072 // Similarly, the equivalent of {(V'[1] - V'[0]) = 3 - 7 = -4} would be {-D'[0] = -4}
1073
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001074 if (count == 2) { // if 2 points, basic linear calculation
1075 if (t[1] == t[0]) {
1076 ALOGE("Events have identical time stamps t=%" PRId64 ", setting velocity = 0", t[0]);
1077 return 0;
1078 }
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001079 const float deltaX = deltaValues ? -x[0] : x[1] - x[0];
1080 return deltaX / (SECONDS_PER_NANO * (t[1] - t[0]));
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001081 }
1082 // Guaranteed to have at least 3 points here
1083 float work = 0;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001084 for (size_t i = count - 1; i > 0 ; i--) { // start with the oldest sample and go forward in time
1085 if (t[i] == t[i-1]) {
1086 ALOGE("Events have identical time stamps t=%" PRId64 ", skipping sample", t[i]);
1087 continue;
1088 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001089 float vprev = kineticEnergyToVelocity(work); // v[i-1]
Yeabkal Wubshit0bb5e592022-09-14 01:22:28 -07001090 const float deltaX = deltaValues ? -x[i-1] : x[i] - x[i-1];
1091 float vcurr = deltaX / (SECONDS_PER_NANO * (t[i] - t[i-1])); // v[i]
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001092 work += (vcurr - vprev) * fabsf(vcurr);
1093 if (i == count - 1) {
1094 work *= 0.5; // initial condition, case 2) above
1095 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001096 }
Siarhei Vishniakou97b5e182017-09-01 13:52:33 -07001097 return kineticEnergyToVelocity(work);
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001098}
1099
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -08001100std::optional<float> ImpulseVelocityTrackerStrategy::getVelocity(int32_t pointerId) const {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001101 const auto movementIt = mMovements.find(pointerId);
1102 if (movementIt == mMovements.end()) {
1103 return std::nullopt; // no data
1104 }
1105
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001106 // Iterate over movement samples in reverse time order and collect samples.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001107 float positions[HISTORY_SIZE];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001108 nsecs_t time[HISTORY_SIZE];
1109 size_t m = 0; // number of points that will be used for fitting
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001110 size_t index = mIndex.at(pointerId);
1111 const Movement& newestMovement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001112 do {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001113 const Movement& movement = movementIt->second[index];
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001114
1115 nsecs_t age = newestMovement.eventTime - movement.eventTime;
1116 if (age > HORIZON) {
1117 break;
1118 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001119 if (movement.eventTime == 0 && index != 0) {
1120 // All eventTime's are initialized to 0. If we encounter a time of 0 in a position
1121 // that's >0, it means that we hit the block where the data wasn't initialized.
1122 // It's also possible that the sample at 0 would be invalid, but there's no harm in
1123 // processing it, since it would be just a single point, and will only be encountered
1124 // in artificial circumstances (in tests).
1125 break;
1126 }
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001127
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001128 positions[m] = movement.position;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001129 time[m] = movement.eventTime;
1130 index = (index == 0 ? HISTORY_SIZE : index) - 1;
1131 } while (++m < HISTORY_SIZE);
1132
1133 if (m == 0) {
Siarhei Vishniakou657a1732023-01-12 11:58:52 -08001134 return std::nullopt; // no data
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001135 }
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001136
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -08001137 const float velocity = calculateImpulseVelocity(time, positions, m, mDeltaValues);
1138 ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", velocity);
Siarhei Vishniakou9f26fc32022-06-17 22:13:57 +00001139
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001140 if (DEBUG_IMPULSE) {
1141 // TODO(b/134179997): delete this block once the switch to 'impulse' is complete.
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001142 // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons.
1143 // X axis chosen arbitrarily for velocity comparisons.
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001144 VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001145 for (ssize_t i = m - 1; i >= 0; i--) {
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001146 lsq2.addMovement(time[i], pointerId, AMOTION_EVENT_AXIS_X, positions[i]);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001147 }
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08001148 std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00001149 if (v) {
1150 ALOGD("lsq2 velocity: %.1f", *v);
Siarhei Vishniakou276467b2022-03-17 09:43:28 -07001151 } else {
1152 ALOGD("lsq2 velocity: could not compute velocity");
1153 }
Siarhei Vishniakoue37bcec2021-09-28 14:24:32 -07001154 }
Yeabkal Wubshit9b4443f2023-02-23 23:35:07 -08001155 return velocity;
Siarhei Vishniakou00a4ea92017-06-08 21:43:20 +01001156}
1157
Jeff Brown5912f952013-07-01 19:10:31 -07001158} // namespace android