cgv
Loading...
Searching...
No Matches
piecewise_linear_interpolator.h
1#pragma once
2
3#include "interpolator.h"
4
5namespace cgv {
6namespace math {
7
8template<typename T>
10public:
11 T interpolate(control_point_container<T> control_points, float t) const {
12 size_t count = control_points.size();
13
14 if(count == 0)
15 return (T)0;
16
17 if(count == 1)
18 return control_points[0].second;
19
20 t = cgv::math::clamp(t, control_points.min().first, control_points.max().first);
21
22 if(t > control_points[0].first) {
23 size_t idx = 0;
24
25 for(size_t i = 1; i < count; ++i) {
26 if(control_points[idx].first <= t && control_points[i].first > t)
27 break;
28 idx = i;
29 }
30
31 if(idx < count - 1) {
32 std::pair<float, T> n0 = control_points[idx];
33 std::pair<float, T> n1 = control_points[idx + 1];
34
35 float t0 = n0.first;
36 float t1 = n1.first;
37
38 float a = (t - t0) / (t1 - t0);
39
40 return (T)((1.0f - a) * n0.second + a * n1.second);
41 } else {
42 return control_points[idx].second;
43 }
44 } else {
45 return control_points[0].second;
46 }
47 }
48
49 std::vector<T> interpolate(control_point_container<T> control_points, size_t n) const {
50 size_t count = control_points.size();
51
52 std::vector<T> data(n, (T)0);
53
54 if(n == 0 || count == 0)
55 return data;
56
57 if(count == 1) {
58 std::fill(data.begin(), data.end(), control_points[0].second);
59 return data;
60 }
61
62 size_t l = 0;
63 size_t r = 1;
64
65 if(control_points.min().first > 0.0f)
66 r = 0;
67
68 float step = 1.0f / static_cast<float>(n - 1);
69
70 for(size_t i = 0; i < n; ++i) {
71 float t = static_cast<float>(i) * step;
72
73 while(t > control_points[r].first && l < count - 1) {
74 l = r;
75 r = std::min(l + 1, count - 1);
76 }
77
78 if(l == r) {
79 data[i] = (T)(control_points[r].second);
80 } else {
81 std::pair<float, T> n0 = control_points[l];
82 std::pair<float, T> n1 = control_points[r];
83
84 float t0 = n0.first;
85 float t1 = n1.first;
86
87 float a = (t - t0) / (t1 - t0);
88
89 data[i] = (T)((1.0f - a) * n0.second + a * n1.second);
90 }
91 }
92
93 return data;
94 }
95};
96
97}
98}
the cgv namespace
Definition print.h:11