Skip to content

Some bézier clipping algorithm improvements - #427

Merged
nical merged 2 commits into
nical:masterfrom
kleintom:clipping_improvements
Nov 9, 2018
Merged

nical merged 2 commits into
nical:masterfrom
kleintom:clipping_improvements

Conversation

@kleintom

@kleintom kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor

No description provided.

…ithm.

The main improvements here are:

* greatly reduced failure rates when one curve reduces to a point (that is, we
  now return many more actual intersections that we used to discard);

* improvements on the rate of occurrence of large distances between curves
  sampled at returned intersection pairs.
@kleintom

kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor Author

A reminder of where I left off last time: I noticed that we were getting a lot of bézier clipping reducing one of the curves to a point, meaning there's a potential intersection at that point, and that we were throwing away a lot of those potential intersections because the way I handled that case was to sample distances from the point to the other curve: if the smallest sample was small enough we concluded intersection, otherwise we returned no intersection. On a run of one million pairs of random curves, we were throwing away ~20_000 actual intersections if the inputs were f64s, and ~300_000 actual intersections if the inputs were f32s (I think in both cases the random coefficients were between -100_000 and 100_000 for those numbers).

(Oh yeah: why are so many curves reducing to a point? From what I recall, what I was seeing was that the fat line wasn't clipping us down to a point (though that can definitely happen), but it was clipping down to a small interval of 0..1, and then that small interval was translated to what was maybe already quite a small domain for a subcurve of the original curve, at which point rounding reduced the small subdomain of the small subdomain to a single point, particularly for f32s.)

I made two changes from there.

  1. At each recursion the algorithm splits one of the curves into either a subcurve or into two parts - the first change was to always do those splits using the original curves, instead of splitting a curve that may already have been split from the original curve at many previous stages. That reduced the f64 20_000 number to, I forget, 800 maybe (I didn't write it down apparently). The f32 300_000 number only reduced to 280_000 if I remember correctly.

  2. I added some code to handle those point intersections better. Now if we have a point intersection we still try the sampling, but if that fails, we try harder to confirm that there's an intersection by solving for the curve parameters at which the curve has the x-coordinate of the point and the y-coordinate of the point (plus a little more work for edge cases). If we get solutions then we check them by testing that the corresponding intersection points aren't too far apart, and that seems to work pretty well. [I should try to see how things go if we stop doing the sampling all together and just use the new method, but I'd rather do that in a followup at this point.]

That has the added benefit that we can now accept points in the api, i.e. we can return whether or not a point lies on a cubic curve. [Honestly though I'd be okay with not exposing that functionality if you don't think there's a real need for it. Right now that code is very general: for example it has to handle the case where the point is on a self intersection of the curve (in which case it has to return two or three parameters), but in the bézier clipping case the curve we're looking at is almost always (but not always) pretty close to linear and basically never self intersects or does anything goofy. So down the road there might be room for more optimizations for the clipping case if we don't also have to handle the general case at the same time.]

That seems to work well: we still have to make a judgement on whether a potential intersection we find samples close enough to be considered a real intersection, but of the cases I looked at where we discard for being too far away, all were legit non-intersections: in all those cases we reduced to a point because some part of the previous curve (either an endpoint or a control point) landed on the fat line of the other curve (which is why it clipped to a point), but not on the other curve itself (which is why it's not an actual intersection). (That scenario will come up again later.)

@kleintom

kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor Author

Epsilons
The next issue I noticed is that not only had we been failing regularly in the point/curve degenerate case of bézier clipping, we had been failing with f32s (hardly at all with f64s) in the non-degenerate case by concluding that subcurves that were still curves (not points) did not intersect, when in fact they did intersect. (I tested that as follows: if in the f32 case we concluded that two subcurves did not bézier clip, I computed their f64 equivalents, then ran the whole intersection algorithm on those f64 curves from the start - if they intersected as f64 curves then I concluded they should have as f32s as well.)

I mentioned trying epsilon = 1e-7 for f32s last time, but then I noted that f32.EPSILON = 1.19209290e-07_f32 (the "machine epsilon"), so asking for two numbers between 0.0 and 1.0 to be less than 1e-7 seems like a bad idea.

So I tried epsilon = 1e-6, epsilon = 5e-6, and epsilon = 1e-5. Each gave a different rate at which we got the bogus non-intersections that were actually intersections - the other thing it changed is the precision of our returned intersection pairs: the larger you allow the subcurve domains to be when you declare intersection, the more latitude you have for getting the exact location of the intersection parameters wrong. I checked for that error by looking at d = (curve1.sample(intersection_t1) - curve2.sample(intersection_t2)).length(). Here's what I found for a million curve pairs with random coefficients between -100_000 and 100_000:

At f32:1e-5, 9_465 intersections with d >= 1 (2 with d > 10, max 512), 79 intersections missed due to roundoff errors
At f32:5e-6, 248 intersections with d >= 1 (3 with d > 10, max 82), 106 intersections missed due to roundoff errors
At f32:1e-6, 39 intersections with d >= 1 (1 with d > 10, max 15), 564 missed intersections due to roundoff errors

[The max d's there are a little misleading: I later did some work to improve those, so they should be smaller now - I'll say more about that later.]
I wound up going with epsilon = 5e-6 for f32s, but that may still need adjusting (there is actually more than one epsilon: for example, there's also an epsilon for when to decide when two intersection pairs should be the same, which is different, but depends on, this epsilon; then there's an epsilon for deciding if a point intersection is actually an intersection - I don't like it, but each of these epsilons kind of requires its own tuning depending on f32 or f64, and on the size of the curve coefficients in some cases - generally larger coefficients require larger epsilons to deal with larger errors in the computations (and there are always going to be cases that fail to one side or the other of a given epsilon)).

I have less to say about the choice of epsilon for f64s because the f64 behavior has always seemed much more stable (which I guess isn't a surprise) - the f32 case has more known errors, breaks its epsilon bounds more readily, seems fussier and less stable, has more perfectly reasonable looking curves that fail for some weird reason, etc.

I wrote a benchmark to try to give some idea of a) how much speed improvement we get with using f32s, and b) how much I've "regressed" (I use quotes because my previous submission was kinda broken already) by adding more processing. [Bench was just the first rust thing that came up when I looked for this stuff - if there's a better way to do what I'm describing here, I'd be happy to hear about it; also I can put my bench code somewhere if you'd like to see it.] The bench takes a fixed sequence of 10_000 curve pairs with random coefficients between -100_000 and 100_000, and just runs the bézier clipping algorithm on each pair, once as f32s, once as f64s (the random numbers were generated as f32s). Here's the diff between what I submitted last time and what I'm submitting this time:
Old code:
test test::f32_intersect ... bench: 23,645,791 (averaged over three runs)
test tests::f64_intersect ... bench: 28,188,410
New code:
test test::f32_intersect ... bench: 24,493,001
test tests::f64_intersect ... bench: 28,575,400

@kleintom

kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor Author

More known issues
In addition to what I posted last time:

Fat line intersections missed due to rounding and other errors
f32
This is what I consider to be the main source of (known) missed intersections with f32s: these occur at a rate of about 125 per million curve pairs with epsilon = 5e-6 at coefficients of +/-100_000 (as mentioned above). (There are typically around 800_000 intersections per million random curve pairs, so, for what it's worth, that's a success rate of ~(800_000 - 125) / 800_000 = 0.99984375.)

There are several ways in which the fat line intersection check can fail:

  • the curves can have a corresponding pair of numbers that differ only in their 7th digit (which is right at the limit for f32s if I'm not mistaken); such rounding errors can cause them to not intersect.
  • the subcurves can reduce to overlapping lines, which the fat line algorithm doesn't currently handle. :-/ [Not just close to lines: actual lines - not uncommon when the curves get very small.]
  • they can intersect, but the computations can fail to detect it. I've seen two errors cause this: first, one of the fat line values was computed to be positive (very small) instead of negative, and second one (or more) of the distances from the curve to the fat line was computed to have the wrong sign, which led to the conclusion that all points of the curve were on the same side (and outside of) the fat line.
  • the curves can be distorted by rounding enough that they no longer fast_bounding_box intersect, and so we discard them.

[Interestingly if I use LineEquation::signed_distance_to_point instead of Line::signed_distance_to_point, even more intersections disappear. signed_distance_to_point is also an issue with f64s, so it might be worth looking into whether its accuracy can be improved (note that it's used in the fat line bounds values as well, so is the source of both errors in the third point above).]

f64
With f64s, for each case where we decided fat lines did not intersect, I looked at all the cases where both intervals had gotten down to at least 1e-4 (they need to get down to 1e-12 for the algorithm to declare intersection). For a million curve pairs with coefficients between +/-1_000_000_000, there were 12 such instances, three of which were actual errors: one of each of the first three types above!

So for f64s, there are probably less than ~three of these errors per million pair curves (I got two such errors out of 2 million pairs with coefficients in +/-100_000).

Intersection samples distance errors
f32
Here are the "d errors", where d is the distance between the curves sampled at a returned intersection pair.
f32:5e-6(-->epsilon):100_000(-->coefficient range is -100_000 to 100_000) for a million random curve pairs:
d > 10: 1 time (d=12.410156) not an error
d between 5-10: 1 (5.226564) not an error
1-5: 233 times
0.707 - 1: 1884
< 0.707: 824_842
Another run:
d > 10: 0
5-10: 5 (no actual errors)
1-5: 231

sqrt(1/2) ~ 0.707 is the max size of the error we allow when we conclude an intersection from a point/curve - all d's larger than that had to come from the case where both subcurve domains reduced to non-points of length < epsilon (i.e. where the algorithm completed normally, as originally designed, with neither curve reducing to a point). As noted, none of those large distances indicated an error, it was just a consequence of the inaccuracy of the algorithm at the given epsilon (such as when we're trying to find the exact intersection parameters of two curves that intersect very shallowly (though that doesn't seem to always be the cause)).

f64
f64:5e-6:100_000: max distance 0.00009996977150031878
f64:5e-6:100_000_000: max distance 0.003162189643030765
f64:5e-6:1_00_000_000: max distance 0.03162017219599326
f64:5e-6:100_000_000_000: max distance 0.5335588716674515
f64:5e-6:1_000_000_000_000: max distance 6.332885743363991

Also see Another Interesting Example below for another source of known error - it seems to occur at a rate of about 1 per million random f32 pair curves, but could be more prevalent for curves of a certain shape relation.

@kleintom

kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor Author

Another Interesting Example
At an earlier stage when I was looking at error spreads in the distances between two curves at their computed intersection parameters (see above), I was seeing distances between intersection points occasionally getting over a hundred, which seemed like a lot. It turned out those largest errors were always from an endpoint of one curve ending close, but not all that close, to the interior of the other curve (these were the errors of "type 1" from my first summary, I just hadn't seen a really large error at that point).

For example, consider the following curves:

let curve1 = CubicBezierSegment {
    from: point(76868.875f32, 47679.28),
    ctrl1: point(65326.86, 856.21094),
    ctrl2: point(-85621.64, -80823.375),
    to: point(-56517.53, 28062.227),
}
let curve2 = CubicBezierSegment {
    from: point(-67977.72, 77673.53),
    ctrl1: point(-59829.57, -41917.87),
    ctrl2: point(57.4375, 52822.97),
    to: point(51075.86, 85772.84),
}

full_scale

curve1 is green, curve2 is blue. Here's a closeup closer to the "intersection":
zoomed

The algorithm gets down to the point where we're clipping the orange subcurve of curve2 against the fat line of the purple subcurve of curve1. Those two curves have four properties relevant to the bézier clipping algorithm:

  • their fast_bounding_boxes overlap (in fact the orange curve actually goes way up to the left);
  • they're both nearly, but not quite, linear (so the convex hull of one is narrow and the fat line of the other is narrow);
  • the fat line (line, not segment!) of the purple curve intersects the orange curve;
  • the curve on which the fat line is based is already very small.

Since both curves are nearly linear, the narrow fat line of the purple curve intersects the narrow convex hull of the orange curve in a narrow range, so clips the orange curve to a very small domain [if they were too linear the orange curve could be reduced to a point, and then we would actually not conclude intersection because we're more strict about distances in that case]. Since the domain of the purple subcurve was already quite small, now both domains are epsilon-small and we conclude we have an intersection where we actually don't. I don't have it nailed down, but I guess I just feel like this is sort of a general situation that can occur at multiple scales and distances and lead to large misses, so I added a check to try to catch this case, but all it does is compute the distance between the supposed intersecting points when this happens, and if it's too large we discard the intersection (so it's possible we could discard an actual intersection there, since we've seen that actual intersection distance errors aren't really bounded very well at present). So this error can still be an issue when the endpoint is close enough to the interior of the other curve (the example here still fails since the distance is within the limit I set - this is test_cubic_endpoint_not_an_intersection); I don't know a good way to stop it at the moment.

The endpoint involvement seems to me to just be a case where half the setup is already done for this to occur, like a trap - but I also occasionally see this happen near actual intersections, either leading to a duplicated intersection (if we're lucky), or to a new intersection close to the actual intersection.

@kleintom

kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor Author

Stability part two
By introducing a bug, I noticed that "bad" things can happen if you run the algorithm on a curve and a proper subcurve. We were already checking for equal curves and opposite curves - I don't know how to check for a curve being a subcurve of another curve, so we have to just live with this I think and try not to break. Currently we handle it by quitting on recursion count over and over until we've reached the function call limit, at which point all outstanding recursions fail and we finish. We wind up with 9 intersections (the max), each distance epsilon from the previous basically. Shrug.

@kleintom

kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor Author

Odds and ends

  • Another distance error case I decided to add a fix for is when the algorithm produces duplicated intersection pairs that are close together - previously we always just kept the first one and discarded all the later ones, but now we always take the one that minimizes distance between intersection points, since sometimes those duplicates arise from errors of the type discussed above occurring near the actual intersection.

  • I noticed this time around that you already have solve_t_for_[xy] for monotonic curves, which I introduced in the last series as parameters_for_[xy]_values for a general CubicBezierSegment - I kept the name change so that they wouldn't be confused with the monotonic versions, which return only one parameter value, but I'm open to whatever you'd like to do here.

  • I checked for cases where we dup two intersection pairs that we shouldn't (that's controlled by an epsilon). [These numbers have changed since a previous discussion on the issue.]
    f32
    I'm seeing 1-2 dups per run of a million curve pairs at 100_000, mostly of the "Another Interesting Example" variety (so they should be duped). One interesting example I saw: an actual intersecting pair reduced to a pair that was a near miss non-intersection but still fat line intersected, and then that pair split into two pairs, each of which registered as intersections of the "Another Interesting Example" variety.
    f64
    The dups being detected for f64 curves (134 dups for a million pair curves with coefficients +/- one million) are mostly (all in the cases I checked) arising from point_curve_intersection, where we compute an intersection parameter for the x curve and a parameter for the y curve, and they turn out to not be epsilon close for the epsilon we have on hand - there's a TODO to tune that up (even though the dup eventually gets caught in add_intersection).

  • On the topic of controlling the distance between the curves sampled at a returned intersection pair. I consider this basically an f32 issue; f64 errors seem more strongly controlled (until you get into the trillions). As I've said before, we decide we have an intersection when the domains of both curves have reduced to a size < epsilon, and then we just take the midpoints of those intervals as the intersection pair. So clearly the smaller epsilon is, the better the error will be controlled - but we've also seen that the smaller epsilon is, the more rounding errors and missed intersections we see, so the two issues are somewhat at odds. One easy thing that I think might help would be: instead of just taking the midpoint of the small subcurve domains as the final intersection pair, try the intersection of the subcurve baselines - assuming those subcurves are small, which they should be, they should also be pretty much linear, so that might provide a better estimate. I'll leave that for a followup though. (And there are other more drastic things that could be tried.)

@kleintom

kleintom commented Nov 7, 2018

Copy link
Copy Markdown
Contributor Author

r? @nical
p.s. I meant to mention, just as a general comment: the graphs above were produced by matplotlib - I hadn't used it much before, but I used it here and it came in extremely handy: not only was it able to handle accurate (as far as I could tell) graphing of nearly every tiny curve I fed it, but the plotter comes with zooming and panning and point-under-mouse controls so that I could zoom in on close intersections easily. Analyzing this stuff would have gone a lot worse without it.

@kleintom

kleintom commented Nov 8, 2018

Copy link
Copy Markdown
Contributor Author

FYI: I'm once again a day slow on this... but: I ran a test where I computed intersections for a million curve pairs first as f32s, and then as f64s, and compared the intersections counts:
with coefficients between -100_000 and 100_000, there were ~1_000 mismatches using the code in this PR: 9 of those had more f32 intersections than f64 intersections, of those 6 were correct for f32s and wrong with f64s, 3 were correct for f64s and were wrong with f32s because they slipped below my "Another interesting example" check (they were that type of error, but the distance between the endpoint and the other curve was smaller than what I was discarding).

With the previous version of the algorithm, I get 129_280 mismatches with 502 where more f32 intersections were found than f64 intersections. [I expect in this case that there are more where both the f32 and the f64 count were low, so were wrong even if they didn't show up in this test as a mismatch (and of course there could still be more of those in the current code as well!).]

So this PR still seems like a big improvement, but there are still some types of error that I'm either not aware of or was previously miscounting.

@nical

nical commented Nov 9, 2018

Copy link
Copy Markdown
Owner

I kept the name change so that they wouldn't be confused with the monotonic versions, which return only one parameter value, but I'm open to whatever you'd like to do here.

We can change the naming later, I'm not entirely sure whether I prefer solve_t but there is a lot to digest here and I'd rather focus on the logic.

On the topic of controlling the distance between the curves sampled at a returned intersection pair. I consider this basically an f32 issue

Nice, if we can avoid the need for a precision parameter it's great. It's a bit of a last resort solution when there isn't a good default for the algorithm.

So this PR still seems like a big improvement

Yes indeed, nice work!

@nical
nical merged commit 457fec6 into nical:master Nov 9, 2018
@kleintom

Copy link
Copy Markdown
Contributor Author

I mentioned trying to improve the control on the distance between computed intersection points by computing intersection parameters using the intersection of the baselines of the final smallest subcurves generated by the algorithm (rather than using the midpoints of the domains of those smallest curves, as we currently do). That didn't really work out.

I checked a million pairs of f32 curves with random coefficients between -100_000 and 100_000. Of 553_971 intersections found when the domains of subcurves reduced to less than epsilon (but not to a point), 218_130 of them had final subcurves whose baselines actually intersected (335_841 did not intersect!) - for those 218_130, using the intersection of the base lines resulted in an average distance improvement of 0.0507 (if you look at only those cases where the distance decreased, the average is 0.0558). The max improvement was 0.7149. In 18_437 cases, using the line intersection was worse than using the midpoints, by an average of -0.0048 and a max of -0.036.

The max improvement of 0.7149 suggests to me that this issue isn't really the cause of distance-between-computed-intersection-points errors of >1 in the f32 case. Since a) most subcurves are distorted enough at that level to not even intersect, and b) the improvement (when there is an improvement) isn't very large, I don't think it's worth pursuing this (but let me know if you disagree and I can post a patch).

Here's a random (the first one I looked at with one intersection point) graph showing the various subcurves that are computed as the algorithm progresses. The initial pair of curves is bright red; successive pairs of curves turn more and more green as the algorithm recurses toward a potential intersection. It's a little confusing, but the last recursion is on the blue curve (which is a horizontal line) and the lowest (brightest green) of the other set of curves - in that recursion the lowest other green curve is clipped by the blue curve down to the orange curve (which, yes, looks completely wrong!). [The orange curve never actually gets used in the algorithm because its domain, and the domain of the blue curve, are now small enough to conclude there's an intersection.] Note that the two curves didn't even intersect in the previous iteration (the blue and the lowest of the other set of curves), yet the algorithm still found the intersection that exists here.
f32_sequence

@kleintom

Copy link
Copy Markdown
Contributor Author

Another no-action-taken report:

  1. I added some code to handle point intersections better. Now if we have a point
    intersection we still try the sampling, but if that fails, we try harder to confirm that there's an
    intersection by solving for the curve parameters at which the curve has the x-coordinate of the point and the y-coordinate of the point (plus a little more work for edge cases). If we get solutions then we check them by testing that the corresponding intersection points aren't too far apart, and that seems to work pretty well. [I should try to see how things go if we stop doing the sampling all together and just use the new method, but I'd rather do that in a followup at this point.]

This was in reference to how we handle the case where one of the curves reduces to a point - how do we tell if the point actually intersects the other curve? Previously we were sampling the curve to see if it was close to the point; this PR added new processing as described in the quote.

I tried two changes to that: 1) I got rid of the sampling all together. That turned out a bit slower (according to my bench), so I also 2) got rid of the last check in point_curve_intersections where we check if the point lies just outside a corner of the convex hull of the curve and within epsilon of the curve [I'd really like to get rid of that check, and I think we'd be fine nearly always (or maybe even really always?), but I worry that it's possible for somebody to sample a curve at say a cusp at a corner of the convex hull, for the sample to round diagonally outside the convex hull, and then to miss the intersection if we don't check for that... We could speed up if we're willing to live with that possibility :-) I guess I could also try harder to see if it ever happens in practice; in the couple tests I've hand written it did not happen].

I then ran 5_000_000 curve pairs with random coefficients between -100_000 and 100_000 and compared the number of intersections for each pair of curves with and without those changes. The code found exactly the same number of intersections with and without those changes, for both f32 and f64 curves (which suggests that the new point processing is working pretty well, at least for the types of curves seen deep in the clipping algorithm). The bench showed a slight slowdown for f32 curves - from 24,493,001 to 24,754,269 - and a slight speedup for f64 curves - from 28,575,400 to 28,363,437. Since the only reason we're keeping the f32 processing is for the speedup vs. f64 (and since sampling is a pretty simple straightforward operation), I guess it makes since to just keep the sampling for now. Let me know if you have other thoughts though :-)

@kleintom

Copy link
Copy Markdown
Contributor Author
  1. got rid of the last check in point_curve_intersections where we check if the point lies just outside a corner of the convex hull of the curve and within epsilon of the curve

Actually thinking about it for another second, in general the clipping algorithm reaches that point very rarely (usually, but not always, when a curve reduces to a point, you've found an intersection) - I checked and for the 10_000 pairs of curves in my bench, that code is never reached. Getting rid of the check would mostly just speed up the case where we're testing a point that doesn't lie on a curve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants