17bc5b65b00d8b6b60aad88e3f91c773045ea697
[ipdf/code.git] / src / bezier.h
1 #ifndef _BEZIER_H
2 #define _BEZIER_H
3
4 #include <vector>
5 #include <algorithm>
6
7 #include "real.h"
8 #include "rect.h"
9 namespace IPDF
10 {
11         extern int Factorial(int n);
12         extern int BinomialCoeff(int n, int k);
13         extern Real Bernstein(int k, int n, const Real & u);
14         
15         inline std::pair<Real,Real> SolveQuadratic(const Real & a, const Real & b, const Real & c)
16         {
17                 Real x0((-b + Sqrt(b*b - Real(4)*a*c))/(Real(2)*a));
18                 Real x1((-b - Sqrt(b*b - Real(4)*a*c))/(Real(2)*a));
19                 return std::pair<Real,Real>(x0,x1);
20         }
21
22         inline std::vector<Real> SolveCubic(const Real & a, const Real & b, const Real & c, const Real & d)
23         {
24                 // This is going to be a big one...
25                 // See http://en.wikipedia.org/wiki/Cubic_function#General_formula_for_roots
26
27                 // delta = 18abcd - 4 b^3 d + b^2 c^2 - 4ac^3 - 27 a^2 d^2
28                 
29                 Real discriminant = Real(18) * a * b * c * d - Real(4) * (b * b * b) * d 
30                                 + (b * b) * (c * c) - Real(4) * a * (c * c * c)
31                                 - Real(27) * (a * a) * (d * d);
32                 
33                 Debug("Trying to solve %fx^3 + %fx^2 + %fx + %f (Discriminant: %f)", a,b,c,d, discriminant);
34                 // discriminant > 0 => 3 distinct, real roots.
35                 // discriminant = 0 => a multiple root (1 or 2 real roots)
36                 // discriminant < 0 => 1 real root, 2 complex conjugate roots
37
38                 Real delta0 = (b*b) - Real(3) * a * c;
39                 Real delta1 = Real(2) * (b * b * b) - Real(9) * a * b * c + Real(27) * (a * a) * d;
40
41                 std::vector<Real> roots;
42
43                 Real C = pow((delta1 + Sqrt((delta1 * delta1) - 4 * (delta0 * delta0 * delta0)) ) / Real(2), 1/3);
44
45                 if (false && discriminant < 0)
46                 {
47                         Real real_root = (Real(-1) / (Real(3) * a)) * (b + C + delta0 / C);
48
49                         roots.push_back(real_root);
50
51                         return roots;
52
53                 }
54
55                 ////HACK: We know any roots we care about will be between 0 and 1, so...
56                 Real maxi(100);
57                 Real prevRes(d);
58                 for(int i = -1; i <= 100; ++i)
59                 {
60                         Real x(i);
61                         x /= maxi;
62                         Real y = a*(x*x*x) + b*(x*x) + c*x + d;
63                         if ( ((y < Real(0)) && (prevRes > Real(0))) || ((y > Real(0)) && (prevRes < Real(0))))
64                         {
65                                 Debug("Found root of %fx^3 + %fx^2 + %fx + %f at %f (%f)", a, b, c, d, x, y);
66                                 roots.push_back(x);
67                         }
68                         prevRes = y;
69                 }
70                 return roots;
71                         
72         }
73
74         /** A _cubic_ bezier. **/
75         struct Bezier
76         {
77                 Real x0; Real y0;
78                 Real x1; Real y1;
79                 Real x2; Real y2;
80                 Real x3; Real y3;
81                 
82                 typedef enum {LINE, QUADRATIC, CUSP, LOOP, SERPENTINE} Type;
83                 Type type;
84                 
85                 Bezier() = default; // Needed so we can fread/fwrite this struct... for now.
86                 Bezier(Real _x0, Real _y0, Real _x1, Real _y1, Real _x2, Real _y2, Real _x3, Real _y3) : x0(_x0), y0(_y0), x1(_x1), y1(_y1), x2(_x2), y2(_y2), x3(_x3), y3(_y3) 
87                 {
88                         //TODO: classify the curve
89                         type = SERPENTINE;
90                 }
91                 
92                 std::string Str() const
93                 {
94                         std::stringstream s;
95                         s << "Bezier{" << Float(x0) << "," << Float(y0) << " -> " << Float(x1) << "," << Float(y1) << " -> " << Float(x2) << "," << Float(y2) << " -> " << Float(x3) << "," << Float(y3) << "}";
96                         return s.str();
97                 }
98                 
99                 /**
100                  * Construct absolute control points using relative control points to a bounding rectangle
101                  * ie: If cpy is relative to bounds rectangle, this will be absolute
102                  */
103                 Bezier(const Bezier & cpy, const Rect & t = Rect(0,0,1,1)) : x0(cpy.x0), y0(cpy.y0), x1(cpy.x1), y1(cpy.y1), x2(cpy.x2),y2(cpy.y2), x3(cpy.x3), y3(cpy.y3), type(cpy.type)
104                 {
105                         x0 *= t.w;
106                         y0 *= t.h;
107                         x1 *= t.w;
108                         y1 *= t.h;
109                         x2 *= t.w;
110                         y2 *= t.h;
111                         x3 *= t.w;
112                         y3 *= t.h;
113                         x0 += t.x;
114                         y0 += t.y;
115                         x1 += t.x;
116                         y1 += t.y;
117                         x2 += t.x;
118                         y2 += t.y;
119                         x3 += t.x;
120                         y3 += t.y;
121                 }
122
123                 Rect SolveBounds() const;
124                 
125                 Bezier ToAbsolute(const Rect & bounds) const
126                 {
127                         return Bezier(*this, bounds);
128                 }
129                 
130                 /** Convert absolute control points to control points relative to bounds
131                  * (This basically does the opposite of the Copy constructor)
132                  * ie: If this is absolute, the returned Bezier will be relative to the bounds rectangle
133                  */
134                 Bezier ToRelative(const Rect & bounds) const
135                 {
136                         // x' <- (x - x0)/w etc
137                         // special cases when w or h = 0
138                         // (So can't just use the Copy constructor on the inverse of bounds)
139                         // Rect inverse = {-bounds.x/bounds.w, -bounds.y/bounds.h, Real(1)/bounds.w, Real(1)/bounds.h};
140                         Bezier result;
141                         if (bounds.w == 0)
142                         {
143                                 result.x0 = 0;
144                                 result.x1 = 0;
145                                 result.x2 = 0;
146                                 result.x3 = 0;
147                         }
148                         else
149                         {
150                                 result.x0 = (x0 - bounds.x)/bounds.w;   
151                                 result.x1 = (x1 - bounds.x)/bounds.w;
152                                 result.x2 = (x2 - bounds.x)/bounds.w;
153                                 result.x3 = (x3 - bounds.x)/bounds.w;
154                         }
155
156                         if (bounds.h == 0)
157                         {
158                                 result.y0 = 0;
159                                 result.y1 = 0;
160                                 result.y2 = 0;
161                                 result.y3 = 0;
162                         }
163                         else
164                         {
165                                 result.y0 = (y0 - bounds.y)/bounds.h;   
166                                 result.y1 = (y1 - bounds.y)/bounds.h;
167                                 result.y2 = (y2 - bounds.y)/bounds.h;
168                                 result.y3 = (y3 - bounds.y)/bounds.h;
169                         }
170                         return result;
171                 }
172
173                 // Performs one round of De Casteljau subdivision and returns the [t,1] part.
174                 Bezier DeCasteljauSubdivideRight(const Real& t)
175                 {
176                         Real one_minus_t = Real(1) - t;
177
178                         // X Coordinates
179                         Real x01 = x0*t + x1*one_minus_t;
180                         Real x12 = x1*t + x2*one_minus_t;
181                         Real x23 = x2*t + x3*one_minus_t;
182
183                         Real x012 = x01*t + x12*one_minus_t;
184                         Real x123 = x12*t + x23*one_minus_t;
185
186                         Real x0123 = x012*t + x123*one_minus_t;
187
188                         // Y Coordinates
189                         Real y01 = y0*t + y1*one_minus_t;
190                         Real y12 = y1*t + y2*one_minus_t;
191                         Real y23 = y2*t + y3*one_minus_t;
192
193                         Real y012 = y01*t + y12*one_minus_t;
194                         Real y123 = y12*t + y23*one_minus_t;
195
196                         Real y0123 = y012*t + y123*one_minus_t;
197
198                         return Bezier(x0, y0, x01, y01, x012, y012, x0123, y0123);
199                 }
200                 // Performs one round of De Casteljau subdivision and returns the [0,t] part.
201                 Bezier DeCasteljauSubdivideLeft(const Real& t)
202                 {
203                         Real one_minus_t = Real(1) - t;
204
205                         // X Coordinates
206                         Real x01 = x0*t + x1*one_minus_t;
207                         Real x12 = x1*t + x2*one_minus_t;
208                         Real x23 = x2*t + x3*one_minus_t;
209
210                         Real x012 = x01*t + x12*one_minus_t;
211                         Real x123 = x12*t + x23*one_minus_t;
212
213                         Real x0123 = x012*t + x123*one_minus_t;
214
215                         // Y Coordinates
216                         Real y01 = y0*t + y1*one_minus_t;
217                         Real y12 = y1*t + y2*one_minus_t;
218                         Real y23 = y2*t + y3*one_minus_t;
219
220                         Real y012 = y01*t + y12*one_minus_t;
221                         Real y123 = y12*t + y23*one_minus_t;
222
223                         Real y0123 = y012*t + y123*one_minus_t;
224
225                         return Bezier(x0123, y0123, x123, y123, x23, y23, x3, y3);
226                 }
227
228                 Bezier ReParametrise(const Real& t0, const Real& t1)
229                 {
230                         Debug("Reparametrise: %f -> %f",t0,t1);
231                         Bezier new_bezier;
232                         // Subdivide to get from [0,t1]
233                         new_bezier = DeCasteljauSubdivideLeft(t1);
234                         // Convert t0 from [0,1] range to [0, t1]
235                         Real new_t0 = t0 / t1;
236                         Debug("New t0 = %f", new_t0);
237                         new_bezier = new_bezier.DeCasteljauSubdivideRight(new_t0);
238
239                         Debug("%s becomes %s", this->Str().c_str(), new_bezier.Str().c_str());
240                         return new_bezier;
241                 }
242                 
243                 std::vector<Bezier> ClipToRectangle(const Rect& r)
244                 {
245                         // Find points of intersection with the rectangle.
246                         Debug("Clipping Bezier to Rect %s", r.Str().c_str());
247
248                         // Convert bezier coefficients -> cubic coefficients
249                         Real xd = x0 - r.x;
250                         Real xc = Real(3)*(x1 - x0);
251                         Real xb = Real(3)*(x2 - x1) - xc;
252                         Real xa = x3 - x0 - xc - xb;
253
254                         // Find its roots.
255                         std::vector<Real> x_intersection = SolveCubic(xa, xb, xc, xd);
256
257                         // And for the other side.
258                         xd = x0 - r.x - r.w;
259
260                         std::vector<Real> x_intersection_pt2 = SolveCubic(xa, xb, xc, xd);
261                         x_intersection.insert(x_intersection.end(), x_intersection_pt2.begin(), x_intersection_pt2.end());
262
263                         // Similarly for y-coordinates.
264                         // Convert bezier coefficients -> cubic coefficients
265                         Real yd = y0 - r.y;
266                         Real yc = Real(3)*(y1 - y0);
267                         Real yb = Real(3)*(y2 - y1) - yc;
268                         Real ya = y3 - y0 - yc - yb;
269
270                         // Find its roots.
271                         std::vector<Real> y_intersection = SolveCubic(ya, yb, yc, yd);
272
273                         // And for the other side.
274                         yd = y0 - r.y - r.h;
275
276                         std::vector<Real> y_intersection_pt2 = SolveCubic(ya, yb, yc, yd);
277                         y_intersection.insert(y_intersection.end(), y_intersection_pt2.begin(), y_intersection_pt2.end());
278
279                         // Merge and sort.
280                         x_intersection.insert(x_intersection.end(), y_intersection.begin(), y_intersection.end());
281                         x_intersection.push_back(Real(0));
282                         x_intersection.push_back(Real(1));
283                         std::sort(x_intersection.begin(), x_intersection.end());
284
285                         Debug("Found %d intersections.\n", x_intersection.size());
286                         
287                         std::vector<Bezier> all_beziers;
288                         if (x_intersection.empty())
289                         {
290                                 all_beziers.push_back(*this);
291                                 return all_beziers;
292                         }
293                         Real t0 = *(x_intersection.begin());
294                         for (auto it = x_intersection.begin()+1; it != x_intersection.end(); ++it)
295                         {
296                                 Real t1 = *it;
297                                 if (t1 == t0) continue;
298                                 Debug(" -- t0: %f to t1: %f", t0, t1);
299                                 Real ptx, pty;
300                                 Evaluate(ptx, pty, ((t1 + t0) / Real(2)));
301                                 if (r.PointIn(ptx, pty))
302                                 {
303                                         all_beziers.push_back(this->ReParametrise(t0, t1));
304                                 }
305                                 else
306                                 {
307                                         Debug("Segment removed (point at %f, %f)", ptx, pty);
308                                 }
309                                 t0 = t1;
310                         }
311                         return all_beziers;
312                 }
313
314                 /** Evaluate the Bezier at parametric parameter u, puts resultant point in (x,y) **/
315                 void Evaluate(Real & x, Real & y, const Real & u) const
316                 {
317                         Real coeff[4];
318                         for (unsigned i = 0; i < 4; ++i)
319                                 coeff[i] = Bernstein(i,3,u);
320                         x = x0*coeff[0] + x1*coeff[1] + x2*coeff[2] + x3*coeff[3];
321                         y = y0*coeff[0] + y1*coeff[1] + y2*coeff[2] + y3*coeff[3];
322                 }
323
324         };
325
326
327
328 }
329
330 #endif //_BEZIER_H

UCC git Repository :: git.ucc.asn.au