• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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 #ifndef MATHUTILS_H
17 #define MATHUTILS_H
18 
19 namespace android {
20 namespace uirenderer {
21 
22 #define NON_ZERO_EPSILON (0.001f)
23 #define ALPHA_EPSILON (0.001f)
24 
25 class MathUtils {
26 public:
27     /**
28      * Check for floats that are close enough to zero.
29      */
isZero(float value)30     inline static bool isZero(float value) {
31         return (value >= -NON_ZERO_EPSILON) && (value <= NON_ZERO_EPSILON);
32     }
33 
isPositive(float value)34     inline static bool isPositive(float value) {
35         return value >= NON_ZERO_EPSILON;
36     }
37 
38     /**
39      * Clamps alpha value, and snaps when very near 0 or 1
40      */
clampAlpha(float alpha)41     inline static float clampAlpha(float alpha) {
42         if (alpha <= ALPHA_EPSILON) {
43             return 0;
44         } else if (alpha >= (1 - ALPHA_EPSILON)) {
45             return 1;
46         } else {
47             return alpha;
48         }
49     }
50 
51     /*
52      * Clamps positive tessellation scale values
53      */
clampTessellationScale(float scale)54     inline static float clampTessellationScale(float scale) {
55         const float MIN_SCALE = 0.0001;
56         const float MAX_SCALE = 1e10;
57         if (scale < MIN_SCALE) {
58             return MIN_SCALE;
59         } else if (scale > MAX_SCALE) {
60             return MAX_SCALE;
61         }
62         return scale;
63     }
64 
areEqual(float valueA,float valueB)65     inline static bool areEqual(float valueA, float valueB) {
66         return isZero(valueA - valueB);
67     }
68 
69     template<typename T>
max(T a,T b)70     static inline T max(T a, T b) {
71         return a > b ? a : b;
72     }
73 
74     template<typename T>
min(T a,T b)75     static inline T min(T a, T b) {
76         return a < b ? a : b;
77     }
78 
79     template<typename T>
clamp(T a,T minValue,T maxValue)80     static inline T clamp(T a, T minValue, T maxValue) {
81         return min(max(a, minValue), maxValue);
82     }
83 
lerp(float v1,float v2,float t)84     inline static float lerp(float v1, float v2, float t) {
85         return v1 + ((v2 - v1) * t);
86     }
87 }; // class MathUtils
88 
89 } /* namespace uirenderer */
90 } /* namespace android */
91 
92 #endif /* MATHUTILS_H */
93