diff options
Diffstat (limited to 'native/jni/src')
-rw-r--r-- | native/jni/src/additional_proximity_chars.h | 4 | ||||
-rw-r--r-- | native/jni/src/defines.h | 2 | ||||
-rw-r--r-- | native/jni/src/geometry_utils.h | 58 | ||||
-rw-r--r-- | native/jni/src/proximity_info.cpp | 111 | ||||
-rw-r--r-- | native/jni/src/proximity_info.h | 29 | ||||
-rw-r--r-- | native/jni/src/proximity_info_state.cpp | 286 | ||||
-rw-r--r-- | native/jni/src/proximity_info_state.h | 19 | ||||
-rw-r--r-- | native/jni/src/proximity_info_state_utils.h | 319 | ||||
-rw-r--r-- | native/jni/src/proximity_info_utils.h | 247 |
9 files changed, 625 insertions, 450 deletions
diff --git a/native/jni/src/additional_proximity_chars.h b/native/jni/src/additional_proximity_chars.h index 21eb0bf8d..a88fd6cea 100644 --- a/native/jni/src/additional_proximity_chars.h +++ b/native/jni/src/additional_proximity_chars.h @@ -45,7 +45,7 @@ class AdditionalProximityChars { } public: - static int getAdditionalCharsSize(const char *localeStr, const int c) { + static int getAdditionalCharsSize(const char *const localeStr, const int c) { if (!isEnLocale(localeStr)) { return 0; } @@ -65,7 +65,7 @@ class AdditionalProximityChars { } } - static const int *getAdditionalChars(const char *localeStr, const int c) { + static const int *getAdditionalChars(const char *const localeStr, const int c) { if (!isEnLocale(localeStr)) { return 0; } diff --git a/native/jni/src/defines.h b/native/jni/src/defines.h index 4d5a2b261..f5f527831 100644 --- a/native/jni/src/defines.h +++ b/native/jni/src/defines.h @@ -392,6 +392,8 @@ static inline void prof_out(void) { template<typename T> inline T min(T a, T b) { return a < b ? a : b; } template<typename T> inline T max(T a, T b) { return a > b ? a : b; } +#define M_PI_F 3.14159265f + #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) // The ratio of neutral area radius to sweet spot radius. diff --git a/native/jni/src/geometry_utils.h b/native/jni/src/geometry_utils.h index 4bff80f15..4cbb127e8 100644 --- a/native/jni/src/geometry_utils.h +++ b/native/jni/src/geometry_utils.h @@ -21,7 +21,6 @@ #include "defines.h" -#define M_PI_F 3.14159265f #define ROUND_FLOAT_10000(f) ((f) < 1000.0f && (f) > 0.001f) \ ? (floorf((f) * 10000.0f) / 10000.0f) : (f) @@ -29,15 +28,6 @@ namespace latinime { static inline float SQUARE_FLOAT(const float x) { return x * x; } -static inline float getSquaredDistanceFloat(const float x1, const float y1, const float x2, - const float y2) { - return SQUARE_FLOAT(x1 - x2) + SQUARE_FLOAT(y1 - y2); -} - -static AK_FORCE_INLINE int getDistanceInt(const int x1, const int y1, const int x2, const int y2) { - return static_cast<int>(hypotf(static_cast<float>(x1 - x2), static_cast<float>(y1 - y2))); -} - static AK_FORCE_INLINE float getAngle(const int x1, const int y1, const int x2, const int y2) { const int dx = x1 - x2; const int dy = y1 - y2; @@ -55,51 +45,9 @@ static AK_FORCE_INLINE float getAngleDiff(const float a1, const float a2) { return diff; } -static inline float pointToLineSegSquaredDistanceFloat(const float x, const float y, const float x1, - const float y1, const float x2, const float y2, const bool extend) { - const float ray1x = x - x1; - const float ray1y = y - y1; - const float ray2x = x2 - x1; - const float ray2y = y2 - y1; - - const float dotProduct = ray1x * ray2x + ray1y * ray2y; - const float lineLengthSqr = SQUARE_FLOAT(ray2x) + SQUARE_FLOAT(ray2y); - const float projectionLengthSqr = dotProduct / lineLengthSqr; - - float projectionX; - float projectionY; - if (!extend && projectionLengthSqr < 0.0f) { - projectionX = x1; - projectionY = y1; - } else if (!extend && projectionLengthSqr > 1.0f) { - projectionX = x2; - projectionY = y2; - } else { - projectionX = x1 + projectionLengthSqr * ray2x; - projectionY = y1 + projectionLengthSqr * ray2y; - } - return getSquaredDistanceFloat(x, y, projectionX, projectionY); +static AK_FORCE_INLINE int getDistanceInt(const int x1, const int y1, const int x2, + const int y2) { + return static_cast<int>(hypotf(static_cast<float>(x1 - x2), static_cast<float>(y1 - y2))); } - -// Normal distribution N(u, sigma^2). -struct NormalDistribution { - public: - NormalDistribution(const float u, const float sigma) - : mU(u), mSigma(sigma), - mPreComputedNonExpPart(1.0f / sqrtf(2.0f * M_PI_F * SQUARE_FLOAT(sigma))), - mPreComputedExponentPart(-1.0f / (2.0f * SQUARE_FLOAT(sigma))) {} - - float getProbabilityDensity(const float x) const { - const float shiftedX = x - mU; - return mPreComputedNonExpPart * expf(mPreComputedExponentPart * SQUARE_FLOAT(shiftedX)); - } - -private: - DISALLOW_IMPLICIT_CONSTRUCTORS(NormalDistribution); - const float mU; // mean value - const float mSigma; // standard deviation - const float mPreComputedNonExpPart; // = 1 / sqrt(2 * PI * sigma^2) - const float mPreComputedExponentPart; // = -1 / (2 * sigma^2) -}; // struct NormalDistribution } // namespace latinime #endif // LATINIME_GEOMETRY_UTILS_H diff --git a/native/jni/src/proximity_info.cpp b/native/jni/src/proximity_info.cpp index 9b99554d6..c563b0796 100644 --- a/native/jni/src/proximity_info.cpp +++ b/native/jni/src/proximity_info.cpp @@ -94,11 +94,6 @@ ProximityInfo::~ProximityInfo() { delete[] mProximityCharsArray; } -inline int ProximityInfo::getStartIndexFromCoordinates(const int x, const int y) const { - return ((y / CELL_HEIGHT) * GRID_WIDTH + (x / CELL_WIDTH)) - * MAX_PROXIMITY_CHARS_SIZE; -} - bool ProximityInfo::hasSpaceProximity(const int x, const int y) const { if (x < 0 || y < 0) { if (DEBUG_DICT) { @@ -109,7 +104,8 @@ bool ProximityInfo::hasSpaceProximity(const int x, const int y) const { return false; } - const int startIndex = getStartIndexFromCoordinates(x, y); + const int startIndex = ProximityInfoUtils::getStartIndexFromCoordinates( + MAX_PROXIMITY_CHARS_SIZE, x, y, CELL_HEIGHT, CELL_WIDTH, GRID_WIDTH); if (DEBUG_PROXIMITY_INFO) { AKLOGI("hasSpaceProximity: index %d, %d, %d", startIndex, x, y); } @@ -144,101 +140,8 @@ float ProximityInfo::getNormalizedSquaredDistanceFromCenterFloatG( const float touchX = static_cast<float>(x); const float touchY = static_cast<float>(y); const float keyWidth = static_cast<float>(getMostCommonKeyWidth()); - return getSquaredDistanceFloat(centerX, centerY, touchX, touchY) / SQUARE_FLOAT(keyWidth); -} - -int ProximityInfo::squaredDistanceToEdge(const int keyId, const int x, const int y) const { - if (keyId < 0) return true; // NOT_A_ID is -1, but return whenever < 0 just in case - const int left = mKeyXCoordinates[keyId]; - const int top = mKeyYCoordinates[keyId]; - const int right = left + mKeyWidths[keyId]; - const int bottom = top + mKeyHeights[keyId]; - const int edgeX = x < left ? left : (x > right ? right : x); - const int edgeY = y < top ? top : (y > bottom ? bottom : y); - const int dx = x - edgeX; - const int dy = y - edgeY; - return dx * dx + dy * dy; -} - -void ProximityInfo::calculateNearbyKeyCodes( - const int x, const int y, const int primaryKey, int *inputCodes) const { - int *proximityCharsArray = mProximityCharsArray; - int insertPos = 0; - inputCodes[insertPos++] = primaryKey; - const int startIndex = getStartIndexFromCoordinates(x, y); - if (startIndex >= 0) { - for (int i = 0; i < MAX_PROXIMITY_CHARS_SIZE; ++i) { - const int c = proximityCharsArray[startIndex + i]; - if (c < KEYCODE_SPACE || c == primaryKey) { - continue; - } - const int keyIndex = getKeyIndexOf(c); - const bool onKey = isOnKey(keyIndex, x, y); - const int distance = squaredDistanceToEdge(keyIndex, x, y); - if (onKey || distance < MOST_COMMON_KEY_WIDTH_SQUARE) { - inputCodes[insertPos++] = c; - if (insertPos >= MAX_PROXIMITY_CHARS_SIZE) { - if (DEBUG_DICT) { - ASSERT(false); - } - return; - } - } - } - const int additionalProximitySize = - AdditionalProximityChars::getAdditionalCharsSize(mLocaleStr, primaryKey); - if (additionalProximitySize > 0) { - inputCodes[insertPos++] = ADDITIONAL_PROXIMITY_CHAR_DELIMITER_CODE; - if (insertPos >= MAX_PROXIMITY_CHARS_SIZE) { - if (DEBUG_DICT) { - ASSERT(false); - } - return; - } - - const int *additionalProximityChars = - AdditionalProximityChars::getAdditionalChars(mLocaleStr, primaryKey); - for (int j = 0; j < additionalProximitySize; ++j) { - const int ac = additionalProximityChars[j]; - int k = 0; - for (; k < insertPos; ++k) { - if (ac == inputCodes[k]) { - break; - } - } - if (k < insertPos) { - continue; - } - inputCodes[insertPos++] = ac; - if (insertPos >= MAX_PROXIMITY_CHARS_SIZE) { - if (DEBUG_DICT) { - ASSERT(false); - } - return; - } - } - } - } - // Add a delimiter for the proximity characters - for (int i = insertPos; i < MAX_PROXIMITY_CHARS_SIZE; ++i) { - inputCodes[i] = NOT_A_CODE_POINT; - } -} - -int ProximityInfo::getKeyIndexOf(const int c) const { - if (KEY_COUNT == 0) { - // We do not have the coordinate data - return NOT_AN_INDEX; - } - if (c == NOT_A_CODE_POINT) { - return NOT_AN_INDEX; - } - const int lowerCode = toLowerCase(c); - hash_map_compat<int, int>::const_iterator mapPos = mCodeToKeyMap.find(lowerCode); - if (mapPos != mCodeToKeyMap.end()) { - return mapPos->second; - } - return NOT_AN_INDEX; + return ProximityInfoUtils::getSquaredDistanceFloat(centerX, centerY, touchX, touchY) + / SQUARE_FLOAT(keyWidth); } int ProximityInfo::getCodePointOf(const int keyIndex) const { @@ -269,11 +172,13 @@ void ProximityInfo::initializeG() { } int ProximityInfo::getKeyCenterXOfCodePointG(int charCode) const { - return getKeyCenterXOfKeyIdG(getKeyIndexOf(charCode)); + return getKeyCenterXOfKeyIdG( + ProximityInfoUtils::getKeyIndexOf(KEY_COUNT, charCode, &mCodeToKeyMap)); } int ProximityInfo::getKeyCenterYOfCodePointG(int charCode) const { - return getKeyCenterYOfKeyIdG(getKeyIndexOf(charCode)); + return getKeyCenterYOfKeyIdG( + ProximityInfoUtils::getKeyIndexOf(KEY_COUNT, charCode, &mCodeToKeyMap)); } int ProximityInfo::getKeyCenterXOfKeyIdG(int keyId) const { diff --git a/native/jni/src/proximity_info.h b/native/jni/src/proximity_info.h index d00228359..cd0bc32cc 100644 --- a/native/jni/src/proximity_info.h +++ b/native/jni/src/proximity_info.h @@ -20,6 +20,7 @@ #include "defines.h" #include "hash_map_compat.h" #include "jni.h" +#include "proximity_info_utils.h" namespace latinime { @@ -40,7 +41,6 @@ class ProximityInfo { float getNormalizedSquaredDistanceFromCenterFloatG( const int keyId, const int x, const int y) const; bool sameAsTyped(const unsigned short *word, int length) const; - int getKeyIndexOf(const int c) const; int getCodePointOf(const int keyIndex) const; bool hasSweetSpotData(const int keyIndex) const { // When there are no calibration data for a key, @@ -71,10 +71,6 @@ class ProximityInfo { return MOST_COMMON_KEY_WIDTH_SQUARE; } - const char *getLocaleStr() const { - return mLocaleStr; - } - int getKeyCount() const { return KEY_COUNT; } @@ -109,23 +105,26 @@ class ProximityInfo { int getKeyCenterYOfKeyIdG(int keyId) const; int getKeyKeyDistanceG(int keyId0, int keyId1) const; + void initializeProximities(const int *const inputCodes, const int *const inputXCoordinates, + const int *const inputYCoordinates, const int inputSize, int *allInputCodes) const { + ProximityInfoUtils::initializeProximities(inputCodes, inputXCoordinates, inputYCoordinates, + inputSize, mKeyXCoordinates, mKeyYCoordinates, mKeyWidths, mKeyHeights, + mProximityCharsArray, MAX_PROXIMITY_CHARS_SIZE, CELL_HEIGHT, CELL_WIDTH, + GRID_WIDTH, MOST_COMMON_KEY_WIDTH, KEY_COUNT, mLocaleStr, &mCodeToKeyMap, + allInputCodes); + } + + int getKeyIndexOf(const int c) const { + return ProximityInfoUtils::getKeyIndexOf(KEY_COUNT, c, &mCodeToKeyMap); + } + private: DISALLOW_IMPLICIT_CONSTRUCTORS(ProximityInfo); static const float NOT_A_DISTANCE_FLOAT; - int getStartIndexFromCoordinates(const int x, const int y) const; void initializeG(); float calculateNormalizedSquaredDistance(const int keyIndex, const int inputIndex) const; bool hasInputCoordinates() const; - int squaredDistanceToEdge(const int keyId, const int x, const int y) const; - bool isOnKey(const int keyId, const int x, const int y) const { - if (keyId < 0) return true; // NOT_A_ID is -1, but return whenever < 0 just in case - const int left = mKeyXCoordinates[keyId]; - const int top = mKeyYCoordinates[keyId]; - const int right = left + mKeyWidths[keyId] + 1; - const int bottom = top + mKeyHeights[keyId]; - return left < right && top < bottom && x >= left && x < right && y >= top && y < bottom; - } const int MAX_PROXIMITY_CHARS_SIZE; const int GRID_WIDTH; diff --git a/native/jni/src/proximity_info_state.cpp b/native/jni/src/proximity_info_state.cpp index aa029297e..31b6e4baf 100644 --- a/native/jni/src/proximity_info_state.cpp +++ b/native/jni/src/proximity_info_state.cpp @@ -23,6 +23,7 @@ #include "geometry_utils.h" #include "proximity_info.h" #include "proximity_info_state.h" +#include "proximity_info_state_utils.h" namespace latinime { @@ -46,40 +47,17 @@ void ProximityInfoState::initInputParams(const int pointerId, const float maxPoi mProximityInfo = proximityInfo; mHasTouchPositionCorrectionData = proximityInfo->hasTouchPositionCorrectionData(); mMostCommonKeyWidthSquare = proximityInfo->getMostCommonKeyWidthSquare(); - mLocaleStr = proximityInfo->getLocaleStr(); mKeyCount = proximityInfo->getKeyCount(); mCellHeight = proximityInfo->getCellHeight(); mCellWidth = proximityInfo->getCellWidth(); mGridHeight = proximityInfo->getGridWidth(); mGridWidth = proximityInfo->getGridHeight(); - memset(mInputCodes, 0, sizeof(mInputCodes)); + memset(mInputProximities, 0, sizeof(mInputProximities)); if (!isGeometric && pointerId == 0) { - // Initialize - // - mInputCodes - // - mNormalizedSquaredDistances - // TODO: Merge - for (int i = 0; i < inputSize; ++i) { - const int primaryKey = inputCodes[i]; - const int x = xCoordinates[i]; - const int y = yCoordinates[i]; - int *proximities = &mInputCodes[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL]; - mProximityInfo->calculateNearbyKeyCodes(x, y, primaryKey, proximities); - } - - if (DEBUG_PROXIMITY_CHARS) { - for (int i = 0; i < inputSize; ++i) { - AKLOGI("---"); - for (int j = 0; j < MAX_PROXIMITY_CHARS_SIZE_INTERNAL; ++j) { - int icc = mInputCodes[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL + j]; - int icfjc = inputCodes[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL + j]; - icc += 0; - icfjc += 0; - AKLOGI("--- (%d)%c,%c", i, icc, icfjc); AKLOGI("--- A<%d>,B<%d>", icc, icfjc); - } - } - } + mProximityInfo->initializeProximities(inputCodes, xCoordinates, yCoordinates, + inputSize, mInputProximities); } /////////////////////// @@ -116,82 +94,11 @@ void ProximityInfoState::initInputParams(const int pointerId, const float maxPoi mSampledInputSize = 0; if (xCoordinates && yCoordinates) { - if (DEBUG_SAMPLING_POINTS) { - if (isGeometric) { - for (int i = 0; i < inputSize; ++i) { - AKLOGI("(%d) x %d, y %d, time %d", - i, xCoordinates[i], yCoordinates[i], times[i]); - } - } - } -#ifdef DO_ASSERT_TEST - if (times) { - for (int i = 0; i < inputSize; ++i) { - if (i > 0) { - ASSERT(times[i] >= times[i - 1]); - } - } - } -#endif - const bool proximityOnly = !isGeometric && (xCoordinates[0] < 0 || yCoordinates[0] < 0); - int lastInputIndex = pushTouchPointStartIndex; - for (int i = lastInputIndex; i < inputSize; ++i) { - const int pid = pointerIds ? pointerIds[i] : 0; - if (pointerId == pid) { - lastInputIndex = i; - } - } - if (DEBUG_GEO_FULL) { - AKLOGI("Init ProximityInfoState: last input index = %d", lastInputIndex); - } - // Working space to save near keys distances for current, prev and prevprev input point. - NearKeysDistanceMap nearKeysDistances[3]; - // These pointers are swapped for each inputs points. - NearKeysDistanceMap *currentNearKeysDistances = &nearKeysDistances[0]; - NearKeysDistanceMap *prevNearKeysDistances = &nearKeysDistances[1]; - NearKeysDistanceMap *prevPrevNearKeysDistances = &nearKeysDistances[2]; - // "sumAngle" is accumulated by each angle of input points. And when "sumAngle" exceeds - // the threshold we save that point, reset sumAngle. This aims to keep the figure of - // the curve. - float sumAngle = 0.0f; - - for (int i = pushTouchPointStartIndex; i <= lastInputIndex; ++i) { - // Assuming pointerId == 0 if pointerIds is null. - const int pid = pointerIds ? pointerIds[i] : 0; - if (DEBUG_GEO_FULL) { - AKLOGI("Init ProximityInfoState: (%d)PID = %d", i, pid); - } - if (pointerId == pid) { - const int c = isGeometric ? NOT_A_COORDINATE : getPrimaryCodePointAt(i); - const int x = proximityOnly ? NOT_A_COORDINATE : xCoordinates[i]; - const int y = proximityOnly ? NOT_A_COORDINATE : yCoordinates[i]; - const int time = times ? times[i] : -1; - - if (i > 1) { - const float prevAngle = getAngle(xCoordinates[i - 2], yCoordinates[i - 2], - xCoordinates[i - 1], yCoordinates[i - 1]); - const float currentAngle = - getAngle(xCoordinates[i - 1], yCoordinates[i - 1], x, y); - sumAngle += getAngleDiff(prevAngle, currentAngle); - } - - if (pushTouchPoint(i, c, x, y, time, isGeometric /* do sampling */, - i == lastInputIndex, sumAngle, currentNearKeysDistances, - prevNearKeysDistances, prevPrevNearKeysDistances)) { - // Previous point information was popped. - NearKeysDistanceMap *tmp = prevNearKeysDistances; - prevNearKeysDistances = currentNearKeysDistances; - currentNearKeysDistances = tmp; - } else { - NearKeysDistanceMap *tmp = prevPrevNearKeysDistances; - prevPrevNearKeysDistances = prevNearKeysDistances; - prevNearKeysDistances = currentNearKeysDistances; - currentNearKeysDistances = tmp; - sumAngle = 0.0f; - } - } - } - mSampledInputSize = mSampledInputXs.size(); + mSampledInputSize = ProximityInfoStateUtils::updateTouchPoints( + mProximityInfo->getMostCommonKeyWidth(), mProximityInfo, mMaxPointToKeyLength, + mInputProximities, xCoordinates, yCoordinates, times, pointerIds, inputSize, + isGeometric, pointerId, pushTouchPointStartIndex, + &mSampledInputXs, &mSampledInputYs, &mTimes, &mLengthCache, &mInputIndice); } if (mSampledInputSize > 0 && isGeometric) { @@ -497,163 +404,6 @@ bool ProximityInfoState::checkAndReturnIsContinuationPossible(const int inputSiz return true; } -// Calculating point to key distance for all near keys and returning the distance between -// the given point and the nearest key position. -float ProximityInfoState::updateNearKeysDistances(const int x, const int y, - NearKeysDistanceMap *const currentNearKeysDistances) { - static const float NEAR_KEY_THRESHOLD = 2.0f; - - currentNearKeysDistances->clear(); - const int keyCount = mProximityInfo->getKeyCount(); - float nearestKeyDistance = mMaxPointToKeyLength; - for (int k = 0; k < keyCount; ++k) { - const float dist = mProximityInfo->getNormalizedSquaredDistanceFromCenterFloatG(k, x, y); - if (dist < NEAR_KEY_THRESHOLD) { - currentNearKeysDistances->insert(std::pair<int, float>(k, dist)); - } - if (nearestKeyDistance > dist) { - nearestKeyDistance = dist; - } - } - return nearestKeyDistance; -} - -// Check if previous point is at local minimum position to near keys. -bool ProximityInfoState::isPrevLocalMin(const NearKeysDistanceMap *const currentNearKeysDistances, - const NearKeysDistanceMap *const prevNearKeysDistances, - const NearKeysDistanceMap *const prevPrevNearKeysDistances) const { - static const float MARGIN = 0.01f; - - for (NearKeysDistanceMap::const_iterator it = prevNearKeysDistances->begin(); - it != prevNearKeysDistances->end(); ++it) { - NearKeysDistanceMap::const_iterator itPP = prevPrevNearKeysDistances->find(it->first); - NearKeysDistanceMap::const_iterator itC = currentNearKeysDistances->find(it->first); - if ((itPP == prevPrevNearKeysDistances->end() || itPP->second > it->second + MARGIN) - && (itC == currentNearKeysDistances->end() || itC->second > it->second + MARGIN)) { - return true; - } - } - return false; -} - -// Calculating a point score that indicates usefulness of the point. -float ProximityInfoState::getPointScore( - const int x, const int y, const int time, const bool lastPoint, const float nearest, - const float sumAngle, const NearKeysDistanceMap *const currentNearKeysDistances, - const NearKeysDistanceMap *const prevNearKeysDistances, - const NearKeysDistanceMap *const prevPrevNearKeysDistances) const { - static const int DISTANCE_BASE_SCALE = 100; - static const float NEAR_KEY_THRESHOLD = 0.6f; - static const int CORNER_CHECK_DISTANCE_THRESHOLD_SCALE = 25; - static const float NOT_LOCALMIN_DISTANCE_SCORE = -1.0f; - static const float LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE = 1.0f; - static const float CORNER_ANGLE_THRESHOLD = M_PI_F * 2.0f / 3.0f; - static const float CORNER_SUM_ANGLE_THRESHOLD = M_PI_F / 4.0f; - static const float CORNER_SCORE = 1.0f; - - const size_t size = mSampledInputXs.size(); - // If there is only one point, add this point. Besides, if the previous point's distance map - // is empty, we re-compute nearby keys distances from the current point. - // Note that the current point is the first point in the incremental input that needs to - // be re-computed. - if (size <= 1 || prevNearKeysDistances->empty()) { - return 0.0f; - } - - const int baseSampleRate = mProximityInfo->getMostCommonKeyWidth(); - const int distPrev = getDistanceInt(mSampledInputXs.back(), mSampledInputYs.back(), - mSampledInputXs[size - 2], mSampledInputYs[size - 2]) * DISTANCE_BASE_SCALE; - float score = 0.0f; - - // Location - if (!isPrevLocalMin(currentNearKeysDistances, prevNearKeysDistances, - prevPrevNearKeysDistances)) { - score += NOT_LOCALMIN_DISTANCE_SCORE; - } else if (nearest < NEAR_KEY_THRESHOLD) { - // Promote points nearby keys - score += LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE; - } - // Angle - const float angle1 = getAngle(x, y, mSampledInputXs.back(), mSampledInputYs.back()); - const float angle2 = getAngle(mSampledInputXs.back(), mSampledInputYs.back(), - mSampledInputXs[size - 2], mSampledInputYs[size - 2]); - const float angleDiff = getAngleDiff(angle1, angle2); - - // Save corner - if (distPrev > baseSampleRate * CORNER_CHECK_DISTANCE_THRESHOLD_SCALE - && (sumAngle > CORNER_SUM_ANGLE_THRESHOLD || angleDiff > CORNER_ANGLE_THRESHOLD)) { - score += CORNER_SCORE; - } - return score; -} - -// Sampling touch point and pushing information to vectors. -// Returning if previous point is popped or not. -bool ProximityInfoState::pushTouchPoint(const int inputIndex, const int nodeCodePoint, int x, int y, - const int time, const bool sample, const bool isLastPoint, const float sumAngle, - NearKeysDistanceMap *const currentNearKeysDistances, - const NearKeysDistanceMap *const prevNearKeysDistances, - const NearKeysDistanceMap *const prevPrevNearKeysDistances) { - static const int LAST_POINT_SKIP_DISTANCE_SCALE = 4; - - size_t size = mSampledInputXs.size(); - bool popped = false; - if (nodeCodePoint < 0 && sample) { - const float nearest = updateNearKeysDistances(x, y, currentNearKeysDistances); - const float score = getPointScore(x, y, time, isLastPoint, nearest, sumAngle, - currentNearKeysDistances, prevNearKeysDistances, prevPrevNearKeysDistances); - if (score < 0) { - // Pop previous point because it would be useless. - popInputData(); - size = mSampledInputXs.size(); - popped = true; - } else { - popped = false; - } - // Check if the last point should be skipped. - if (isLastPoint && size > 0) { - if (getDistanceInt(x, y, mSampledInputXs.back(), mSampledInputYs.back()) - * LAST_POINT_SKIP_DISTANCE_SCALE < mProximityInfo->getMostCommonKeyWidth()) { - // This point is not used because it's too close to the previous point. - if (DEBUG_GEO_FULL) { - AKLOGI("p0: size = %zd, x = %d, y = %d, lx = %d, ly = %d, dist = %d, " - "width = %d", size, x, y, mSampledInputXs.back(), mSampledInputYs.back(), - getDistanceInt(x, y, mSampledInputXs.back(), mSampledInputYs.back()), - mProximityInfo->getMostCommonKeyWidth() - / LAST_POINT_SKIP_DISTANCE_SCALE); - } - return popped; - } - } - } - - if (nodeCodePoint >= 0 && (x < 0 || y < 0)) { - const int keyId = mProximityInfo->getKeyIndexOf(nodeCodePoint); - if (keyId >= 0) { - x = mProximityInfo->getKeyCenterXOfKeyIdG(keyId); - y = mProximityInfo->getKeyCenterYOfKeyIdG(keyId); - } - } - - // Pushing point information. - if (size > 0) { - mLengthCache.push_back( - mLengthCache.back() + getDistanceInt( - x, y, mSampledInputXs.back(), mSampledInputYs.back())); - } else { - mLengthCache.push_back(0); - } - mSampledInputXs.push_back(x); - mSampledInputYs.push_back(y); - mTimes.push_back(time); - mInputIndice.push_back(inputIndex); - if (DEBUG_GEO_FULL) { - AKLOGI("pushTouchPoint: x = %03d, y = %03d, time = %d, index = %d, popped ? %01d", - x, y, time, inputIndex, popped); - } - return popped; -} - float ProximityInfoState::calculateNormalizedSquaredDistance( const int keyIndex, const int inputIndex) const { if (keyIndex == NOT_AN_INDEX) { @@ -826,11 +576,8 @@ bool ProximityInfoState::isKeyInSerchKeysAfterIndex(const int index, const int k } void ProximityInfoState::popInputData() { - mSampledInputXs.pop_back(); - mSampledInputYs.pop_back(); - mTimes.pop_back(); - mLengthCache.pop_back(); - mInputIndice.pop_back(); + ProximityInfoStateUtils::popInputData(&mSampledInputXs, &mSampledInputYs, &mTimes, + &mLengthCache, &mInputIndice); } float ProximityInfoState::getDirection(const int index0, const int index1) const { @@ -889,7 +636,8 @@ float ProximityInfoState::getLineToKeyDistance( const int keyX = mProximityInfo->getKeyCenterXOfKeyIdG(keyId); const int keyY = mProximityInfo->getKeyCenterYOfKeyIdG(keyId); - return pointToLineSegSquaredDistanceFloat(keyX, keyY, x0, y0, x1, y1, extend); + return ProximityInfoUtils::pointToLineSegSquaredDistanceFloat( + keyX, keyY, x0, y0, x1, y1, extend); } // Updates probabilities of aligning to some keys and skipping. @@ -1008,7 +756,8 @@ void ProximityInfoState::updateAlignPointProbabilities(const int start) { MAX_SPEEDxNEAREST_RATE_FOR_STANDERD_DIVIATION); const float sigma = speedxAngleRate + speedxNearestKeyDistanceRate + MIN_STANDERD_DIVIATION; - NormalDistribution distribution(CENTER_VALUE_OF_NORMALIZED_DISTRIBUTION, sigma); + ProximityInfoUtils::NormalDistribution + distribution(CENTER_VALUE_OF_NORMALIZED_DISTRIBUTION, sigma); static const float PREV_DISTANCE_WEIGHT = 0.5f; static const float NEXT_DISTANCE_WEIGHT = 0.6f; // Summing up probability densities of all near keys. @@ -1207,6 +956,11 @@ float ProximityInfoState::getMostProbableString(int *const codePointBuf) const { return sumLogProbability; } +bool ProximityInfoState::hasSpaceProximity(const int index) const { + ASSERT(0 <= index && index < mSampledInputSize); + return mProximityInfo->hasSpaceProximity(getInputX(index), getInputY(index)); +} + // Returns a probability of mapping index to keyIndex. float ProximityInfoState::getProbability(const int index, const int keyIndex) const { ASSERT(0 <= index && index < mSampledInputSize); diff --git a/native/jni/src/proximity_info_state.h b/native/jni/src/proximity_info_state.h index d747bae2a..0f0eb7d39 100644 --- a/native/jni/src/proximity_info_state.h +++ b/native/jni/src/proximity_info_state.h @@ -19,12 +19,12 @@ #include <bitset> #include <cstring> // for memset() -#include <string> #include <vector> #include "char_utils.h" #include "defines.h" #include "hash_map_compat.h" +#include "proximity_info_state_utils.h" namespace latinime { @@ -55,13 +55,13 @@ class ProximityInfoState { ///////////////////////////////////////// AK_FORCE_INLINE ProximityInfoState() : mProximityInfo(0), mMaxPointToKeyLength(0.0f), mAverageSpeed(0.0f), - mHasTouchPositionCorrectionData(false), mMostCommonKeyWidthSquare(0), mLocaleStr(), + mHasTouchPositionCorrectionData(false), mMostCommonKeyWidthSquare(0), mKeyCount(0), mCellHeight(0), mCellWidth(0), mGridHeight(0), mGridWidth(0), mIsContinuationPossible(false), mSampledInputXs(), mSampledInputYs(), mTimes(), mInputIndice(), mLengthCache(), mBeelineSpeedPercentiles(), mDistanceCache_G(), mSpeedRates(), mDirections(), mCharProbabilities(), mNearKeysVector(), mSearchKeysVector(), mTouchPositionCorrectionEnabled(false), mSampledInputSize(0) { - memset(mInputCodes, 0, sizeof(mInputCodes)); + memset(mInputProximities, 0, sizeof(mInputProximities)); memset(mNormalizedSquaredDistances, 0, sizeof(mNormalizedSquaredDistances)); memset(mPrimaryInputWord, 0, sizeof(mPrimaryInputWord)); } @@ -117,12 +117,12 @@ class ProximityInfoState { if (length != mSampledInputSize) { return false; } - const int *inputCodes = mInputCodes; + const int *inputProximities = mInputProximities; while (length--) { - if (*inputCodes != *word) { + if (*inputProximities != *word) { return false; } - inputCodes += MAX_PROXIMITY_CHARS_SIZE_INTERNAL; + inputProximities += MAX_PROXIMITY_CHARS_SIZE_INTERNAL; word++; } return true; @@ -146,6 +146,8 @@ class ProximityInfoState { return mSampledInputYs[index]; } + bool hasSpaceProximity(const int index) const; + int getLengthCache(const int index) const { return mLengthCache[index]; } @@ -229,7 +231,7 @@ class ProximityInfoState { } inline const int *getProximityCodePointsAt(const int index) const { - return mInputCodes + (index * MAX_PROXIMITY_CHARS_SIZE_INTERNAL); + return ProximityInfoStateUtils::getProximityCodePointsAt(mInputProximities, index); } float updateNearKeysDistances(const int x, const int y, @@ -260,7 +262,6 @@ class ProximityInfoState { float mAverageSpeed; bool mHasTouchPositionCorrectionData; int mMostCommonKeyWidthSquare; - std::string mLocaleStr; int mKeyCount; int mCellHeight; int mCellWidth; @@ -289,7 +290,7 @@ class ProximityInfoState { // inputs including the current input point. std::vector<NearKeycodesSet> mSearchKeysVector; bool mTouchPositionCorrectionEnabled; - int mInputCodes[MAX_PROXIMITY_CHARS_SIZE_INTERNAL * MAX_WORD_LENGTH]; + int mInputProximities[MAX_PROXIMITY_CHARS_SIZE_INTERNAL * MAX_WORD_LENGTH]; int mNormalizedSquaredDistances[MAX_PROXIMITY_CHARS_SIZE_INTERNAL * MAX_WORD_LENGTH]; int mSampledInputSize; int mPrimaryInputWord[MAX_WORD_LENGTH]; diff --git a/native/jni/src/proximity_info_state_utils.h b/native/jni/src/proximity_info_state_utils.h new file mode 100644 index 000000000..53b992a2a --- /dev/null +++ b/native/jni/src/proximity_info_state_utils.h @@ -0,0 +1,319 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LATINIME_PROXIMITY_INFO_STATE_UTILS_H +#define LATINIME_PROXIMITY_INFO_STATE_UTILS_H + +#include <vector> + +#include "defines.h" +#include "geometry_utils.h" +#include "hash_map_compat.h" +#include "proximity_info.h" + +namespace latinime { +class ProximityInfoStateUtils { + public: + static int updateTouchPoints(const int mostCommonKeyWidth, + const ProximityInfo *const proximityInfo, const int maxPointToKeyLength, + const int *const inputProximities, + const int *const inputXCoordinates, const int *const inputYCoordinates, + const int *const times, const int *const pointerIds, const int inputSize, + const bool isGeometric, const int pointerId, const int pushTouchPointStartIndex, + std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs, + std::vector<int> *sampledInputTimes, std::vector<int> *sampledLengthCache, + std::vector<int> *sampledInputIndice) { + if (DEBUG_SAMPLING_POINTS) { + if (times) { + for (int i = 0; i < inputSize; ++i) { + AKLOGI("(%d) x %d, y %d, time %d", + i, xCoordinates[i], yCoordinates[i], times[i]); + } + } + } +#ifdef DO_ASSERT_TEST + if (times) { + for (int i = 0; i < inputSize; ++i) { + if (i > 0) { + ASSERT(times[i] >= times[i - 1]); + } + } + } +#endif + const bool proximityOnly = !isGeometric + && (inputXCoordinates[0] < 0 || inputYCoordinates[0] < 0); + int lastInputIndex = pushTouchPointStartIndex; + for (int i = lastInputIndex; i < inputSize; ++i) { + const int pid = pointerIds ? pointerIds[i] : 0; + if (pointerId == pid) { + lastInputIndex = i; + } + } + if (DEBUG_GEO_FULL) { + AKLOGI("Init ProximityInfoState: last input index = %d", lastInputIndex); + } + // Working space to save near keys distances for current, prev and prevprev input point. + NearKeysDistanceMap nearKeysDistances[3]; + // These pointers are swapped for each inputs points. + NearKeysDistanceMap *currentNearKeysDistances = &nearKeysDistances[0]; + NearKeysDistanceMap *prevNearKeysDistances = &nearKeysDistances[1]; + NearKeysDistanceMap *prevPrevNearKeysDistances = &nearKeysDistances[2]; + // "sumAngle" is accumulated by each angle of input points. And when "sumAngle" exceeds + // the threshold we save that point, reset sumAngle. This aims to keep the figure of + // the curve. + float sumAngle = 0.0f; + + for (int i = pushTouchPointStartIndex; i <= lastInputIndex; ++i) { + // Assuming pointerId == 0 if pointerIds is null. + const int pid = pointerIds ? pointerIds[i] : 0; + if (DEBUG_GEO_FULL) { + AKLOGI("Init ProximityInfoState: (%d)PID = %d", i, pid); + } + if (pointerId == pid) { + const int c = isGeometric ? + NOT_A_COORDINATE : getPrimaryCodePointAt(inputProximities, i); + const int x = proximityOnly ? NOT_A_COORDINATE : inputXCoordinates[i]; + const int y = proximityOnly ? NOT_A_COORDINATE : inputYCoordinates[i]; + const int time = times ? times[i] : -1; + + if (i > 1) { + const float prevAngle = getAngle( + inputXCoordinates[i - 2], inputYCoordinates[i - 2], + inputXCoordinates[i - 1], inputYCoordinates[i - 1]); + const float currentAngle = + getAngle(inputXCoordinates[i - 1], inputYCoordinates[i - 1], x, y); + sumAngle += getAngleDiff(prevAngle, currentAngle); + } + + if (pushTouchPoint(mostCommonKeyWidth, proximityInfo, maxPointToKeyLength, + i, c, x, y, time, isGeometric /* do sampling */, + i == lastInputIndex, sumAngle, currentNearKeysDistances, + prevNearKeysDistances, prevPrevNearKeysDistances, + sampledInputXs, sampledInputYs, sampledInputTimes, sampledLengthCache, + sampledInputIndice)) { + // Previous point information was popped. + NearKeysDistanceMap *tmp = prevNearKeysDistances; + prevNearKeysDistances = currentNearKeysDistances; + currentNearKeysDistances = tmp; + } else { + NearKeysDistanceMap *tmp = prevPrevNearKeysDistances; + prevPrevNearKeysDistances = prevNearKeysDistances; + prevNearKeysDistances = currentNearKeysDistances; + currentNearKeysDistances = tmp; + sumAngle = 0.0f; + } + } + } + return sampledInputXs->size(); + } + + static const int *getProximityCodePointsAt( + const int *const inputProximities, const int index) { + return inputProximities + (index * MAX_PROXIMITY_CHARS_SIZE_INTERNAL); + } + + static int getPrimaryCodePointAt(const int *const inputProximities, const int index) { + return getProximityCodePointsAt(inputProximities, index)[0]; + } + + static void popInputData(std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs, + std::vector<int> *sampledInputTimes, std::vector<int> *sampledLengthCache, + std::vector<int> *sampledInputIndice) { + sampledInputXs->pop_back(); + sampledInputYs->pop_back(); + sampledInputTimes->pop_back(); + sampledLengthCache->pop_back(); + sampledInputIndice->pop_back(); + } + + private: + DISALLOW_IMPLICIT_CONSTRUCTORS(ProximityInfoStateUtils); + + typedef hash_map_compat<int, float> NearKeysDistanceMap; + + // Calculating point to key distance for all near keys and returning the distance between + // the given point and the nearest key position. + static float updateNearKeysDistances(const ProximityInfo *const proximityInfo, + const float maxPointToKeyLength, const int x, const int y, + NearKeysDistanceMap *const currentNearKeysDistances) { + static const float NEAR_KEY_THRESHOLD = 2.0f; + + currentNearKeysDistances->clear(); + const int keyCount = proximityInfo->getKeyCount(); + float nearestKeyDistance = maxPointToKeyLength; + for (int k = 0; k < keyCount; ++k) { + const float dist = proximityInfo->getNormalizedSquaredDistanceFromCenterFloatG(k, x, y); + if (dist < NEAR_KEY_THRESHOLD) { + currentNearKeysDistances->insert(std::pair<int, float>(k, dist)); + } + if (nearestKeyDistance > dist) { + nearestKeyDistance = dist; + } + } + return nearestKeyDistance; + } + + // Check if previous point is at local minimum position to near keys. + static bool isPrevLocalMin(const NearKeysDistanceMap *const currentNearKeysDistances, + const NearKeysDistanceMap *const prevNearKeysDistances, + const NearKeysDistanceMap *const prevPrevNearKeysDistances) { + static const float MARGIN = 0.01f; + + for (NearKeysDistanceMap::const_iterator it = prevNearKeysDistances->begin(); + it != prevNearKeysDistances->end(); ++it) { + NearKeysDistanceMap::const_iterator itPP = prevPrevNearKeysDistances->find(it->first); + NearKeysDistanceMap::const_iterator itC = currentNearKeysDistances->find(it->first); + if ((itPP == prevPrevNearKeysDistances->end() || itPP->second > it->second + MARGIN) + && (itC == currentNearKeysDistances->end() + || itC->second > it->second + MARGIN)) { + return true; + } + } + return false; + } + + // Calculating a point score that indicates usefulness of the point. + static float getPointScore(const int mostCommonKeyWidth, + const int x, const int y, const int time, const bool lastPoint, const float nearest, + const float sumAngle, const NearKeysDistanceMap *const currentNearKeysDistances, + const NearKeysDistanceMap *const prevNearKeysDistances, + const NearKeysDistanceMap *const prevPrevNearKeysDistances, + std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs) { + static const int DISTANCE_BASE_SCALE = 100; + static const float NEAR_KEY_THRESHOLD = 0.6f; + static const int CORNER_CHECK_DISTANCE_THRESHOLD_SCALE = 25; + static const float NOT_LOCALMIN_DISTANCE_SCORE = -1.0f; + static const float LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE = 1.0f; + static const float CORNER_ANGLE_THRESHOLD = M_PI_F * 2.0f / 3.0f; + static const float CORNER_SUM_ANGLE_THRESHOLD = M_PI_F / 4.0f; + static const float CORNER_SCORE = 1.0f; + + const size_t size = sampledInputXs->size(); + // If there is only one point, add this point. Besides, if the previous point's distance map + // is empty, we re-compute nearby keys distances from the current point. + // Note that the current point is the first point in the incremental input that needs to + // be re-computed. + if (size <= 1 || prevNearKeysDistances->empty()) { + return 0.0f; + } + + const int baseSampleRate = mostCommonKeyWidth; + const int distPrev = getDistanceInt( + sampledInputXs->back(), sampledInputYs->back(), + (*sampledInputXs)[size - 2], (*sampledInputYs)[size - 2]) * DISTANCE_BASE_SCALE; + float score = 0.0f; + + // Location + if (!isPrevLocalMin(currentNearKeysDistances, prevNearKeysDistances, + prevPrevNearKeysDistances)) { + score += NOT_LOCALMIN_DISTANCE_SCORE; + } else if (nearest < NEAR_KEY_THRESHOLD) { + // Promote points nearby keys + score += LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE; + } + // Angle + const float angle1 = getAngle(x, y, sampledInputXs->back(), sampledInputYs->back()); + const float angle2 = getAngle(sampledInputXs->back(), sampledInputYs->back(), + (*sampledInputXs)[size - 2], (*sampledInputYs)[size - 2]); + const float angleDiff = getAngleDiff(angle1, angle2); + + // Save corner + if (distPrev > baseSampleRate * CORNER_CHECK_DISTANCE_THRESHOLD_SCALE + && (sumAngle > CORNER_SUM_ANGLE_THRESHOLD || angleDiff > CORNER_ANGLE_THRESHOLD)) { + score += CORNER_SCORE; + } + return score; + } + + // Sampling touch point and pushing information to vectors. + // Returning if previous point is popped or not. + static bool pushTouchPoint(const int mostCommonKeyWidth, + const ProximityInfo *const proximityInfo, const int maxPointToKeyLength, + const int inputIndex, const int nodeCodePoint, int x, int y, + const int time, const bool sample, const bool isLastPoint, const float sumAngle, + NearKeysDistanceMap *const currentNearKeysDistances, + const NearKeysDistanceMap *const prevNearKeysDistances, + const NearKeysDistanceMap *const prevPrevNearKeysDistances, + std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs, + std::vector<int> *sampledInputTimes, std::vector<int> *sampledLengthCache, + std::vector<int> *sampledInputIndice) { + static const int LAST_POINT_SKIP_DISTANCE_SCALE = 4; + + size_t size = sampledInputXs->size(); + bool popped = false; + if (nodeCodePoint < 0 && sample) { + const float nearest = updateNearKeysDistances( + proximityInfo, maxPointToKeyLength, x, y, currentNearKeysDistances); + const float score = getPointScore(mostCommonKeyWidth, x, y, time, isLastPoint, nearest, + sumAngle, currentNearKeysDistances, prevNearKeysDistances, + prevPrevNearKeysDistances, sampledInputXs, sampledInputYs); + if (score < 0) { + // Pop previous point because it would be useless. + popInputData(sampledInputXs, sampledInputYs, sampledInputTimes, sampledLengthCache, + sampledInputIndice); + size = sampledInputXs->size(); + popped = true; + } else { + popped = false; + } + // Check if the last point should be skipped. + if (isLastPoint && size > 0) { + if (getDistanceInt(x, y, sampledInputXs->back(), + sampledInputYs->back()) * LAST_POINT_SKIP_DISTANCE_SCALE + < mostCommonKeyWidth) { + // This point is not used because it's too close to the previous point. + if (DEBUG_GEO_FULL) { + AKLOGI("p0: size = %zd, x = %d, y = %d, lx = %d, ly = %d, dist = %d, " + "width = %d", size, x, y, mSampledInputXs.back(), + mSampledInputYs.back(), ProximityInfoUtils::getDistanceInt( + x, y, mSampledInputXs.back(), mSampledInputYs.back()), + mProximityInfo->getMostCommonKeyWidth() + / LAST_POINT_SKIP_DISTANCE_SCALE); + } + return popped; + } + } + } + + if (nodeCodePoint >= 0 && (x < 0 || y < 0)) { + const int keyId = proximityInfo->getKeyIndexOf(nodeCodePoint); + if (keyId >= 0) { + x = proximityInfo->getKeyCenterXOfKeyIdG(keyId); + y = proximityInfo->getKeyCenterYOfKeyIdG(keyId); + } + } + + // Pushing point information. + if (size > 0) { + sampledLengthCache->push_back( + sampledLengthCache->back() + getDistanceInt( + x, y, sampledInputXs->back(), sampledInputYs->back())); + } else { + sampledLengthCache->push_back(0); + } + sampledInputXs->push_back(x); + sampledInputYs->push_back(y); + sampledInputTimes->push_back(time); + sampledInputIndice->push_back(inputIndex); + if (DEBUG_GEO_FULL) { + AKLOGI("pushTouchPoint: x = %03d, y = %03d, time = %d, index = %d, popped ? %01d", + x, y, time, inputIndex, popped); + } + return popped; + } +}; +} // namespace latinime +#endif // LATINIME_PROXIMITY_INFO_STATE_UTILS_H diff --git a/native/jni/src/proximity_info_utils.h b/native/jni/src/proximity_info_utils.h new file mode 100644 index 000000000..09302075a --- /dev/null +++ b/native/jni/src/proximity_info_utils.h @@ -0,0 +1,247 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LATINIME_PROXIMITY_INFO_UTILS_H +#define LATINIME_PROXIMITY_INFO_UTILS_H + +#include <cmath> + +#include "additional_proximity_chars.h" +#include "char_utils.h" +#include "defines.h" +#include "geometry_utils.h" +#include "hash_map_compat.h" + +namespace latinime { +class ProximityInfoUtils { + public: + static int getKeyIndexOf(const int keyCount, const int c, + const hash_map_compat<int, int> *const codeToKeyMap) { + if (keyCount == 0) { + // We do not have the coordinate data + return NOT_AN_INDEX; + } + if (c == NOT_A_CODE_POINT) { + return NOT_AN_INDEX; + } + const int lowerCode = toLowerCase(c); + hash_map_compat<int, int>::const_iterator mapPos = codeToKeyMap->find(lowerCode); + if (mapPos != codeToKeyMap->end()) { + return mapPos->second; + } + return NOT_AN_INDEX; + } + + static void initializeProximities(const int *const inputCodes, + const int *const inputXCoordinates, const int *const inputYCoordinates, + const int inputSize, const int *const keyXCoordinates, + const int *const keyYCoordinates, const int *const keyWidths, const int *keyHeights, + const int *const proximityCharsArray, const int maxProximityCharsSize, + const int cellHeight, const int cellWidth, const int gridWidth, + const int mostCommonKeyWidth, const int keyCount, const char *const localeStr, + const hash_map_compat<int, int> *const codeToKeyMap, int *inputProximities) { + // Initialize + // - mInputCodes + // - mNormalizedSquaredDistances + // TODO: Merge + for (int i = 0; i < inputSize; ++i) { + const int primaryKey = inputCodes[i]; + const int x = inputXCoordinates[i]; + const int y = inputYCoordinates[i]; + int *proximities = &inputProximities[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL]; + calculateProximities(keyXCoordinates, keyYCoordinates, keyWidths, keyHeights, + proximityCharsArray, maxProximityCharsSize, cellHeight, cellWidth, gridWidth, + mostCommonKeyWidth, keyCount, x, y, primaryKey, localeStr, codeToKeyMap, + proximities); + } + + if (DEBUG_PROXIMITY_CHARS) { + for (int i = 0; i < inputSize; ++i) { + AKLOGI("---"); + for (int j = 0; j < MAX_PROXIMITY_CHARS_SIZE_INTERNAL; ++j) { + int proximityChar = + inputProximities[i * MAX_PROXIMITY_CHARS_SIZE_INTERNAL + j]; + proximityChar += 0; + AKLOGI("--- (%d)%c", i, proximityChar); + } + } + } + } + + static AK_FORCE_INLINE int getStartIndexFromCoordinates(const int maxProximityCharsSize, + const int x, const int y, const int cellHeight, const int cellWidth, + const int gridWidth) { + return ((y / cellHeight) * gridWidth + (x / cellWidth)) * maxProximityCharsSize; + } + + static inline float getSquaredDistanceFloat(const float x1, const float y1, const float x2, + const float y2) { + return SQUARE_FLOAT(x1 - x2) + SQUARE_FLOAT(y1 - y2); + } + + static inline float pointToLineSegSquaredDistanceFloat(const float x, const float y, + const float x1, const float y1, const float x2, const float y2, const bool extend) { + const float ray1x = x - x1; + const float ray1y = y - y1; + const float ray2x = x2 - x1; + const float ray2y = y2 - y1; + + const float dotProduct = ray1x * ray2x + ray1y * ray2y; + const float lineLengthSqr = SQUARE_FLOAT(ray2x) + SQUARE_FLOAT(ray2y); + const float projectionLengthSqr = dotProduct / lineLengthSqr; + + float projectionX; + float projectionY; + if (!extend && projectionLengthSqr < 0.0f) { + projectionX = x1; + projectionY = y1; + } else if (!extend && projectionLengthSqr > 1.0f) { + projectionX = x2; + projectionY = y2; + } else { + projectionX = x1 + projectionLengthSqr * ray2x; + projectionY = y1 + projectionLengthSqr * ray2y; + } + return getSquaredDistanceFloat(x, y, projectionX, projectionY); + } + + // Normal distribution N(u, sigma^2). + struct NormalDistribution { + public: + NormalDistribution(const float u, const float sigma) + : mU(u), mSigma(sigma), + mPreComputedNonExpPart(1.0f / sqrtf(2.0f * M_PI_F * SQUARE_FLOAT(sigma))), + mPreComputedExponentPart(-1.0f / (2.0f * SQUARE_FLOAT(sigma))) {} + + float getProbabilityDensity(const float x) const { + const float shiftedX = x - mU; + return mPreComputedNonExpPart * expf(mPreComputedExponentPart * SQUARE_FLOAT(shiftedX)); + } + + private: + DISALLOW_IMPLICIT_CONSTRUCTORS(NormalDistribution); + const float mU; // mean value + const float mSigma; // standard deviation + const float mPreComputedNonExpPart; // = 1 / sqrt(2 * PI * sigma^2) + const float mPreComputedExponentPart; // = -1 / (2 * sigma^2) + }; // struct NormalDistribution + + private: + DISALLOW_IMPLICIT_CONSTRUCTORS(ProximityInfoUtils); + + static bool isOnKey(const int *const keyXCoordinates, const int *const keyYCoordinates, + const int *const keyWidths, const int *keyHeights, const int keyId, const int x, + const int y) { + if (keyId < 0) return true; // NOT_A_ID is -1, but return whenever < 0 just in case + const int left = keyXCoordinates[keyId]; + const int top = keyYCoordinates[keyId]; + const int right = left + keyWidths[keyId] + 1; + const int bottom = top + keyHeights[keyId]; + return left < right && top < bottom && x >= left && x < right && y >= top && y < bottom; + } + + static void calculateProximities( + const int *const keyXCoordinates, const int *const keyYCoordinates, + const int *const keyWidths, const int *keyHeights, + const int *const proximityCharsArray, + const int maxProximityCharsSize, const int cellHeight, const int cellWidth, + const int gridWidth, const int mostCommonKeyWidth, const int keyCount, + const int x, const int y, const int primaryKey, const char *const localeStr, + const hash_map_compat<int, int> *const codeToKeyMap, int *proximities) { + const int mostCommonKeyWidthSquare = mostCommonKeyWidth * mostCommonKeyWidth; + int insertPos = 0; + proximities[insertPos++] = primaryKey; + const int startIndex = getStartIndexFromCoordinates( + maxProximityCharsSize, x, y, cellHeight, cellWidth, gridWidth); + if (startIndex >= 0) { + for (int i = 0; i < maxProximityCharsSize; ++i) { + const int c = proximityCharsArray[startIndex + i]; + if (c < KEYCODE_SPACE || c == primaryKey) { + continue; + } + const int keyIndex = getKeyIndexOf(keyCount, c, codeToKeyMap); + const bool onKey = isOnKey(keyXCoordinates, keyYCoordinates, keyWidths, keyHeights, + keyIndex, x, y); + const int distance = squaredLengthToEdge(keyXCoordinates, keyYCoordinates, + keyWidths, keyHeights, keyIndex, x, y); + if (onKey || distance < mostCommonKeyWidthSquare) { + proximities[insertPos++] = c; + if (insertPos >= maxProximityCharsSize) { + if (DEBUG_DICT) { + ASSERT(false); + } + return; + } + } + } + const int additionalProximitySize = + AdditionalProximityChars::getAdditionalCharsSize(localeStr, primaryKey); + if (additionalProximitySize > 0) { + proximities[insertPos++] = ADDITIONAL_PROXIMITY_CHAR_DELIMITER_CODE; + if (insertPos >= maxProximityCharsSize) { + if (DEBUG_DICT) { + ASSERT(false); + } + return; + } + + const int *additionalProximityChars = + AdditionalProximityChars::getAdditionalChars(localeStr, primaryKey); + for (int j = 0; j < additionalProximitySize; ++j) { + const int ac = additionalProximityChars[j]; + int k = 0; + for (; k < insertPos; ++k) { + if (ac == proximities[k]) { + break; + } + } + if (k < insertPos) { + continue; + } + proximities[insertPos++] = ac; + if (insertPos >= maxProximityCharsSize) { + if (DEBUG_DICT) { + ASSERT(false); + } + return; + } + } + } + } + // Add a delimiter for the proximity characters + for (int i = insertPos; i < maxProximityCharsSize; ++i) { + proximities[i] = NOT_A_CODE_POINT; + } + } + + static int squaredLengthToEdge(const int *const keyXCoordinates, + const int *const keyYCoordinates, const int *const keyWidths, const int *keyHeights, + const int keyId, const int x, const int y) { + // NOT_A_ID is -1, but return whenever < 0 just in case + if (keyId < 0) return MAX_POINT_TO_KEY_LENGTH; + const int left = keyXCoordinates[keyId]; + const int top = keyYCoordinates[keyId]; + const int right = left + keyWidths[keyId]; + const int bottom = top + keyHeights[keyId]; + const int edgeX = x < left ? left : (x > right ? right : x); + const int edgeY = y < top ? top : (y > bottom ? bottom : y); + const int dx = x - edgeX; + const int dy = y - edgeY; + return dx * dx + dy * dy; + } +}; +} // namespace latinime +#endif // LATINIME_PROXIMITY_INFO_UTILS_H |