blob: 1b5c60c182983552454803d1ff0a73049ddbfc23 [file] [log] [blame]
caryclark@google.com639df892012-01-10 21:46:10 +00001#include "CubicIntersection.h"
2#include "LineParameters.h"
3#include <algorithm> // used for std::swap
4
5// return false if unable to clip (e.g., unable to create implicit line)
6// caller should subdivide, or create degenerate if the values are too small
7bool bezier_clip(const Cubic& cubic1, const Cubic& cubic2, double& minT, double& maxT) {
8 minT = 1;
9 maxT = 0;
10 // determine normalized implicit line equation for pt[0] to pt[3]
11 // of the form ax + by + c = 0, where a*a + b*b == 1
12
13 // find the implicit line equation parameters
14 LineParameters endLine;
15 endLine.cubicEndPoints(cubic1);
16 if (!endLine.normalize()) {
17 printf("line cannot be normalized: need more code here\n");
18 return false;
19 }
20
21 double distance[2];
22 endLine.controlPtDistance(cubic1, distance);
23
24 // find fat line
25 double top = distance[0];
26 double bottom = distance[1];
27 if (top > bottom) {
28 std::swap(top, bottom);
29 }
30 if (top * bottom >= 0) {
31 const double scale = 3/4.0; // http://cagd.cs.byu.edu/~tom/papers/bezclip.pdf (13)
32 if (top < 0) {
33 top *= scale;
34 bottom = 0;
35 } else {
36 top = 0;
37 bottom *= scale;
38 }
39 } else {
40 const double scale = 4/9.0; // http://cagd.cs.byu.edu/~tom/papers/bezclip.pdf (15)
41 top *= scale;
42 bottom *= scale;
43 }
44
45 // compute intersecting candidate distance
46 Cubic distance2y; // points with X of (0, 1/3, 2/3, 1)
47 endLine.cubicDistanceY(cubic2, distance2y);
48
49 int flags = 0;
50 if (approximately_lesser(distance2y[0].y, top)) {
51 flags |= kFindTopMin;
52 } else if (approximately_greater(distance2y[0].y, bottom)) {
53 flags |= kFindBottomMin;
54 } else {
55 minT = 0;
56 }
57
58 if (approximately_lesser(distance2y[3].y, top)) {
59 flags |= kFindTopMax;
60 } else if (approximately_greater(distance2y[3].y, bottom)) {
61 flags |= kFindBottomMax;
62 } else {
63 maxT = 1;
64 }
65 // Find the intersection of distance convex hull and fat line.
66 char to_0[2];
67 char to_3[2];
68 bool do_1_2_edge = convex_x_hull(distance2y, to_0, to_3);
69 x_at(distance2y[0], distance2y[to_0[0]], top, bottom, flags, minT, maxT);
70 if (to_0[0] != to_0[1]) {
71 x_at(distance2y[0], distance2y[to_0[1]], top, bottom, flags, minT, maxT);
72 }
73 x_at(distance2y[to_3[0]], distance2y[3], top, bottom, flags, minT, maxT);
74 if (to_3[0] != to_3[1]) {
75 x_at(distance2y[to_3[1]], distance2y[3], top, bottom, flags, minT, maxT);
76 }
77 if (do_1_2_edge) {
78 x_at(distance2y[1], distance2y[2], top, bottom, flags, minT, maxT);
79 }
80
81 return minT < maxT; // returns false if distance shows no intersection
82}
83