FastLED 3.9.7
Loading...
Searching...
No Matches
ApproximatingFunction.h
1// Copyleft (c) 2012, Zach Vorhies
2// Public domain, no rights reserved.
3
4#ifndef APPROXIMATING_FUNCTION_H_
5#define APPROXIMATING_FUNCTION_H_
6
7//#include <Arduino.h>
8
9template<typename X, typename Y>
10const Y MapT(const X& x,
11 const X& x1, const X& x2,
12 const Y& y1, const Y& y2) {
13 Y return_val = static_cast<Y>((x - x1) * (y2 - y1) / (x2 - x1) + y1);
14 return return_val;
15}
16
17template <typename KeyT, typename ValT>
18struct InterpData {
19 InterpData(const KeyT& k, const ValT& v) : key(k), val(v) {}
20 KeyT key;
21 ValT val;
22};
23
24template <typename KeyT, typename ValT>
25inline void SelectInterpPoints(const KeyT& k,
26 const InterpData<KeyT, ValT>* array,
27 const int n, // Number of elements in array.
28 int* dest_lower_bound,
29 int* dest_upper_bound) {
30 if (n < 1) {
31 *dest_lower_bound = *dest_upper_bound = -1;
32 return;
33 }
34 if (k < array[0].key) {
35 *dest_lower_bound = *dest_upper_bound = 0;
36 return;
37 }
38
39 for (int i = 0; i < n - 1; ++i) {
40 const InterpData<KeyT, ValT>& curr = array[i];
41 const InterpData<KeyT, ValT>& next = array[i+1];
42
43 if (curr.key <= k && k <= next.key) {
44 *dest_lower_bound = i;
45 *dest_upper_bound = i+1;
46 return;
47 }
48 }
49 *dest_lower_bound = n - 1;
50 *dest_upper_bound = n - 1;
51}
52
53template <typename KeyT, typename ValT>
54inline ValT Interp(const KeyT& k, const InterpData<KeyT, ValT>* array, const int n) {
55 if (n < 1) {
56 return ValT(0);
57 }
58
59 int low_idx = -1;
60 int high_idx = -1;
61
62 SelectInterpPoints<KeyT, ValT>(k, array, n, &low_idx, &high_idx);
63
64 if (low_idx == high_idx) {
65 return array[low_idx].val;
66 }
67
68 const InterpData<KeyT, ValT>* curr = &array[low_idx];
69 const InterpData<KeyT, ValT>* next = &array[high_idx];
70 // map(...) only works on integers. MapT<> is the same thing but it works on
71 // all datatypes.
72 return MapT<KeyT, ValT>(k, curr->key, next->key, curr->val, next->val);
73}
74
75#endif // APPROXIMATING_FUNCTION_H_