glviewvol

view src/curve.cc @ 7:71b479ffb9f7

curve manipulation works
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 30 Dec 2014 17:28:38 +0200
parents 04330eb80b36
children 773f89037a35
line source
1 #include <algorithm>
2 #include "curve.h"
4 #define CLAMP(x, low, high) std::min<float>(std::max<float>(x, low), high)
5 #define INDEX(x) ((x) * 65535.0)
7 void Curve::set_point(float t, float val)
8 {
9 uint16_t x = INDEX(CLAMP(t, 0.0, 1.0));
10 set_point_int(x, val);
11 }
13 static bool cpcmp(const CurvePoint &a, const CurvePoint &b)
14 {
15 return a.t_int < b.t_int;
16 }
18 void Curve::set_point_int(uint16_t ti, float val)
19 {
20 CurvePoint *p = get_point_at(ti);
21 if(p) {
22 p->value = val;
23 } else {
24 CurvePoint p;
25 p.t_int = ti;
26 p.value = val;
27 cp.push_back(p);
28 std::sort(cp.begin(), cp.end(), cpcmp);
29 }
30 }
32 bool Curve::delete_point(uint16_t ti)
33 {
34 int sz = (int)cp.size();
35 for(int i=0; i<sz; i++) {
36 if(cp[i].t_int == ti) {
37 cp.erase(cp.begin() + i);
38 return true;
39 }
40 }
41 return false;
42 }
44 CurvePoint *Curve::get_point(int idx)
45 {
46 if(idx < 0 || idx >= (int)cp.size()) {
47 return 0;
48 }
49 return &cp[idx];
50 }
52 const CurvePoint *Curve::get_point(int idx) const
53 {
54 if(idx < 0 || idx >= (int)cp.size()) {
55 return 0;
56 }
57 return &cp[idx];
58 }
60 int Curve::get_num_points() const
61 {
62 return (int)cp.size();
63 }
65 CurvePoint *Curve::get_point_at(uint16_t ti)
66 {
67 int sz = (int)cp.size();
68 for(int i=0; i<sz; i++) {
69 if(cp[i].t_int == ti) {
70 return &cp[i];
71 }
72 }
73 return 0;
74 }
76 const CurvePoint *Curve::get_point_at(uint16_t ti) const
77 {
78 int sz = (int)cp.size();
79 for(int i=0; i<sz; i++) {
80 if(cp[i].t_int == ti) {
81 return &cp[i];
82 }
83 }
84 return 0;
85 }
87 float Curve::value(float t) const
88 {
89 uint16_t x = INDEX(CLAMP(t, 0.0, 1.0));
90 return value_int(x);
91 }
93 float Curve::value_int(uint16_t ti) const
94 {
95 CurvePoint p = { ti, 0 };
96 std::vector<CurvePoint>::const_iterator it;
97 it = std::lower_bound(cp.begin(), cp.end(), p, cpcmp);
98 if(ti >= it->t_int || it == cp.begin()) {
99 return it->value;
100 }
102 std::vector<CurvePoint>::const_iterator prev = it - 1;
104 float t = (float)(ti - prev->t_int) / (float)(it->t_int - prev->t_int);
105 return prev->value + (it->value - prev->value) * t;
106 }