Repository navigation
Cubic bezier intersections - #422
Conversation
|
Looking into the fat_line issue more: CubicBezierSegment {
from: point(0.0f32, 1.0),
ctrl1: point(0.5, 0.0),
ctrl2: point(0.5, 0.0),
to: point(1.0, 1.0),
}For that curve the intial
|
Nice catch. Yes this makes sense. |
I'm interested in having a fast specific quad/quad intersection routine. In the mean time it's fine to implement it temporarily as a cubic-cubic intersection if you would like to have the API in place (or by decomposing the quads into monotonic segments and intersect monotonic quadratic segments which might be faster). Quad/cubic is less important to me but I'll happily merge an implementation (specific or defaulting to cubic/cubic) if it is valuable to you.
Since the implementation is a few hundred lines, don't hesitate to keep it in a separate file as plain function and add a method to
I think that it makes sense to do this separately. Thanks again, this is great stuff! |
20dc32b to
8f9a5eb
Compare
|
Getting closer :-) I'm (currently) planning on leaving the remaining TODOs in the code for this first round (except for the epsilon TODO: I need to decide on a reasonable epsilon when the scalar is f32, and then figure out how to recognize that we're f32). [The build is failing because I added the rand crate locally for testing.] A couple questions: This version computes parameter pairs at which two curves intersect. Do you want to include endpoints? Do you want to include multiple intersections? So if two curves both start at the same point, should we report one intersection or four for the start/end points? (Or if we're not including endpoints: if two curves with self intersections intersect at their self intersections, how many times should we report?) [I'm not sure offhand what the max intersection count is if you count with multiplicities.] Then a couple questions when the cubic curve actually turns out to be linear or a point: If you have two curves that are actually line segments, and they intersect in a line segment, what should we return? Note also that since we're looking for parameter values, lines like CubicBezierSegment {
from: point(0.0, 0.0),
ctrl1: point(-5.0, 0.0),
ctrl2: point(15.0, 0.0),
to: point(10.0, 0.0)
}can introduce multiplicities as well. If one of the curves is a point, there are some issues. The main one is that we crash if we try to compute the equation of a baseline of a curve that's actually a point, but that can be worked around (and is in the current version). The other issue is that while the algorithm in theory should be capable of determining whether a point is on a curve or not, in practice there's an issue: [Even if both curves start out as non-points, the algorithm can reduce one of the curve domain ranges to a small enough range that the curve becomes a point, at which point we basically can't go any further (for the reason described above). In practice, since the algorithm at each step tries to restrict the larger of the two curve domain ranges, if one of the ranges is very small then the other usually is as well, and it's not a huge deal to just use the values we have when we get to that point. But I don't think that's guaranteed to always be the case, so there's a TODO in the code to do more when we get there.] |
|
Here's an example, just for reference: CubicBezierSegment {
from: point(-471244.85804946127, -853594.0480788357),
ctrl1: point(83646.91299805045, 313668.1101781607),
ctrl2: point(-307765.4455459253, 987369.7692759733),
to: point(289654.82139062043, -580419.2651627442)
}
CubicBezierSegment {
from: point(-438143.9250510582, -743205.8393951938),
ctrl1: point(929869.6336193881, 169490.0770738949),
ctrl2: point(-121379.3777123153, -591659.8266175895),
to: point(-294665.23825776705, -370965.73996210133)
}The reported intersection parameters and their distances are: Only the third intersection resulted from the algorithm internally running one of the curves down to a point (as I discussed in the previous comment), the others ran normally. The curves do indeed intersect in four points(!), and the intersection with the largest dist has a shallower intersection angle, so i guess it's not surprising that the error there is larger. Presumably even larger errors could be produced by curves intersecting at even shallower angles. The algorithm currently uses an epsilon of 1e-12. I'm not sure there's anything to do here; I'm just pointing it out I guess. |
Ideally, when two curves touch at their endpoints, the endpoints are not included in the intersections. The rationale is that for a lot of algorithms (and in particular the ones in this repository), we don't need to do anything (or don't need to do the same things) when two segments touch at their endpoints as opposed to when they self intersect in the middle, and it's trivial to compare the positions at the endpoints to see if they touch. On the other hand, if there is an intersection at the endpoint of one of the curves, but not at the endpoint of the other curve, then ideally we would report it as an intersection. This would match the behavior of the intersection of line segments.
If we don't report intersections when only endpoints are touching then in this case we would not report any intersection.
Good one. I'd say report intersections for each couple
The intersection code for lines and line segments does't report intersections for segments that overlap. It can seem like a surprising choice at first, but in practice this is also a case that algorithms tend to handle separately, and it simplifies the implementation and the speed of the intersection code to not deal with it. I'd suggest doing the same with curve intersections.
If it makes things simpler to consider that a curve that is a point doesn't create any intersection, it's totally fine by me. This type of degenerate segment doesn't contribute to the shape of paths that contain them so all of lyon's algorithms are fine with treating them as if they didn't exist, and I suspect it's the same for many other algorithms (don't hesitate to weight in if your own needs differ of course).
Yeah, just do what's simple/fast for this case, really.
I really appreciate (and am impressed by) how thorough you are about this. I'm not sure whether it makes sense, but a lot of the algorithms in |
Returns the parameters (if any) corresponding to a given x or y value. (It doesn't really seem to make sense to have a similar parameters_for_point since it's rarely possible to be exact in that scenario - closest value to point would be useful, but more difficult.) Both of those methods, as well as is_a_point, will be used by the bézier clipping code to come.
fat_line_min_max is what we actually need to do bézier clipping.
…ping. Initially ported from the paper.js implementation: https://github.com/paperjs/paper.js/blob/0deddebb2c83ea2a0c848f7c8ba5e22fa7562a4e/src/path/Curve.js#L2008 See "Bézier Clipping method", also known as fat line clipping, in https://scholarsarchive.byu.edu/facpub/1/ for motivation and details of how the process works.
8f9a5eb to
0a0501b
Compare
That was due to a bug :-) If I repeat the same test now - one million pairs of curves with data values coming from random numbers between -1_000_000 and 1_000_000 - I get the following max distances between computed intersections for five runs: |
|
f32 vs f64
Both of those stem from the larger issue that with f32s, it's just hard to reduce the curves around a possible intersection to a small enough domain to get a very close approximation - there just aren't that many decimal places to work with (at least I think that's the issue). Currently for f32s we're using a domain epsilon of 1e-5 - i.e. if the domains of the subcurves around a possible intersection are smaller than 1e-5 then we conclude that there's an intersection there. If I change that to 1e-6 then we start missing some intersections all together; I haven't looked into why yet. [The first type of failure seems to always occur at an endpoint of one of the curves: the domain at 0.0 or 1.0 gets small enough and still intersects the fat line of the other curve, so we conclude there's an intersection where there isn't.] The positive news in the case of f32s is that in those million pair-curve runs, the incidence of the first type of error seems to be about 1 in every two million pairs, and the incidence of the second type of error seems to be around 1 in every million pairs. Aside from those errors, all other pairs have errors < 0.5. The absolute size of the errors decreases for curves with smaller coefficients, but I suspect the incidence of type 1 errors is about the same (I haven't checked). The type two errors is an easy thing to adjust: we just increase the distance between intersection pairs that we consider to be the same (of course that leads to more actually distinct pairs being considered the same, but personally I consider that less bad). The type 1 error is more difficult I think, though there are things I could try (which might wind up adding more code that the f64 case doesn't need/want). How much do we care about the f32 case? Is this maybe good enough for now? |
|
Stability |
|
Endpoints We actually do pretty poorly at finding endpoint/endpoint intersections on random loops with the same origin. On average the algorithm detects ~2/4 of the possible endpoint/endpoint intersections, sometimes none. I'm not really sure why that is, I haven't checked closely. I was concerned that that would mean we would have trouble finding endpoint intersections when the algorithm internally subdivides a curve at an intersection, at which point that subdivision point becomes an endpoint at which it needs to find an intersection, but I've included a couple tests, and have looked at a few more, where there's no problem - in fact in that case the algorithm finds the intersection from each side of the subdivided curve. To be clear, the only way I know of to simulate such a case is by looking at two loops with the same origin that intersect at 0.5: since a loop doesn't have a fat line, the first thing we do is split one of the curves in half. Now the other loop may get clipped by the new halves so that it's no longer a loop and we never need to subdivide the second loop at the intersection point, so we only need to find an endpoint/interior point intersection, which is probably easier. That's as far as I've gotten; I think there are likely issues if we ever internally wind up subdividing both curves at an intersection point, but that seems pretty rare. |
|
An interesting example let curve1 = CubicBezierSegment {
from: point(-1.0, 0.0),
ctrl1: point(0.0, 0.0),
ctrl2: point(-1.0, -0.1),
to: point(-1.0, -0.1),
}
let curve2 = CubicBezierSegment {
from: point(0.0, 0.0),
ctrl1: point(5.0, -5.0),
ctrl2: point(-5.0, -5.0),
to: point(0.0, 0.0),
}We're really only interested in the right half of the loop in curve2 - the left half is there just so that the fast bounding boxes of the initial curves intersect. There are zero intersections. We start by trying to restrict curve1 against the fat line of curve2 - but curve2 is a loop and has no fat line, so we split it in half and try again. Now let curve2 be the right half of the loop, and consider restricting curve1 against the fat line of curve2. The left edge of the fat line of curve2 is the y-axis, and the fast convex hull of curve1 touches that fat line only with its first control point, which ends exactly on the y-axis. So clipping reduces curve1 to a single point that may or may not be an intersection. Even though curve2 is still "huge", the basic algorithm is now stopped: curve1 can't be reduced any further (it's a point), and you can't reduce curve2 any further because the curve1 point has no fat line to reduce against. (Currently we handle this case by noting that the curve1 point is too far away from some curve2 samples to indicate an intersection.) |
|
Known failures/ways to break
CubicBezierSegment {
from: point(0.0, 0.0),
ctrl1: point(0.0, 8.0),
ctrl2: point(10.0, 8.0),
to: point(10.0, 0.0),
}
cubicbeziersegment {
from: point(0.0, 12.0),
ctrl1: point(0.0, 4.0),
ctrl2: point(10.0, 4.0),
to: point(10.0, 12.0),
}The algorithm fails after 57 recursions on a very close fat line miss of two very small subcurves at the intersection point (presumably due to roundoff errors). This case could be fixed by adding a condition that says something like "if the subcurves are pretty small and their endpoints are pretty close, then consider it an intersection", but then that criterion will also apply to curves near (but not that near) to very shallow intersection points, and extra intersection points will start popping up in other places where they're not wanted. So that's probably not the right solution :-P The f32 version of this test actually passes.
|
|
Adjustments The (my) major issue with feeling certain about intersections is the case where one of the curves is reduced to a point. In general the algorithm switches back and forth with always trying to clip whichever curve is currently longer, so if one of the curves has reduced to a point, then the other curve in general is probably not too far behind, and doing what we do (sampling distances from the point to the remaining curve) is not too bad. But that's not guaranteed to be the case (see the "Interesting example" for example), so it would be nice if we could avoid the point case more. Or you could embrace the point! Once one curve is a point, simply keep subdividing the other curve, at each stage checking whether or not the point is inside the fat line of the other curve. Once the domain of the other curve is small enough, you have an intersection. The problem I ran into with that is that eventually the other curve gets small enough that it's basically a line, so its fat line is basically a line, and then roundoff errors lead to the point not being exactly on the line when it should be and the intersection gets discarded. I guess the thing to do would be to only require the point to be within epsilon of the fat line, but at the time that didn't fit in nicely. If it works (it seems like it should, and not be too bad?), this would be a way to check for intersection of a point with a curve (something we currently don't attempt). Alternatively you can try to be smarter about reasoning about why clipping reduced one of the curves to a point. If both curves are small enough that they register as lines, then the fat line intersection, if any, will always be a point, and (since the fast bounding boxes intersected?) you can conclude that there's a real intersection (not just with the fat line, but with the actual curve line segment [hmm, that's not quite true]). Or if the endpoints of the curve being clipped are both on the same side of the fat line and there was a single fat line intersection in the interior of the curve, then you can conclude that's not a real intersection. If there's a single fat line intersection with one of the endpoints of the curve, then you can check for endpoint/endpoint intersections (if that curve endpoint touches a non-endpoint part of the fat line, then there's probably not (never?) an intersection unless the fat line curve is a line, since fat lines of non-line curves strictly contain the curve). I think that might be all the cases (but maybe not). Alternatively, at one point I added some logic so that if curve1 was reduced to a point by clipping and the curve2 domain was still too large to conclude intersection (and the curve1 domain was already small enough to conclude intersection), then you would stick with the initial non-point curve1 domain and just subdivide curve2 and hope for the best. In the specific example I was looking at this led to two intersections instead of one, and both intersections were too far away from the actual known intersection to conclude they were all the same. [Right now I'm not sure how that would happen... I abandoned this one pretty quickly.] |
|
r? @nical |
Actually in the f32 case it looks like all of the tests (that use f32-like numbers) still pass using an epsilon of 1e-6 instead of 1e-5; it's when I go to 1e-7 that the first test in test_cubic_curve_curve fails with 0 intersections instead of 1 (do_test_once(curve1, curve2) passes, do_test_once(curve2, curve1) fails), and test_cubic_interior_endpoint fails with one intersection instead of 2 (do_test_once(curve1, curve2) fails, do_test_once(curve2, curve1) passes). Now, using epsilon = 1e-6 for f32s, I'm noticing for the first time that some of the tests are producing a lot of repeated intersections. The f32 version of test_cubic_glancing_intersection (that's the test where the f64 version actually fails to find the intersection) is finding the (0.5, 0.5) intersection 77 times (all as slight variations such as 0.49993077 0.49993002). Apparently the image of an interval of width 1e-6 is not all that small, i.e. its fat line can be relatively large (in the f64 case it would be the image of an interval of width 1e-12). In the f64 case, the only test that produces a repeated intersection is test_cubic_no_duplicated_root, and the root is produced 2 times (I was watching this count for f64s, but didn't think to for f32s). In the f32 case it looks like we have 8 significant digits to work with, and it seems like things are maybe starting to break down at epsilon = 1e-7, so I'm not sure how much that repetition can be improved. I guess in the end the output seems pretty good I would say based on what I've seen so far, so maybe it's just the way it will be. Sorry I missed this before submitting earlier, I did the majority of my testing using f64s. I'll try to take a look into what's going wrong when epsilon = 1e-7 tomorrow, and if I don't see any reason not to, I expect I'll at least change epsilon to 1e-6 (in add_curve_intersections) from its current 1e-5 value. I'll also take a look at whether changing epsilon to 1e-6 improves the frequency of those type 1 and type 2 errors I discussed above. I realize you haven't really had a chance to look at things yet, but if you have any general thoughts on f32 vs. f64 for this functionality, it might help in knowing how much to push for one or the other. If not we can just see how things shake out and go from there :-) |
|
Your journey into cubic bézier intersections is a fascinating read. I'll look at the code soon. Don't worry about f32 precision, it looks reasonable from what you wrote. Even the line segment intersection code has precision issues with f32 and the tessellator code ends up using f64 just for intersections. I think that it's good to be generic over that so that people can pick the precision that fits their need. |
|
So ... I was missing a class of error in my random curves testing: the one where one of the curves reduces to a point and then we discard the potential intersection because when we sample distances from the point to the other curve, they're not small enough to conclude intersection. And it turns out there are currently a lot of those errors, like in one f64 million curve-pair run, 22,781 of them (I checked the first 10 by hand and they're all actual intersections) :-/ It's just as bad with f32s, possibly a little worse. For f64s it looks like just adjusting the epsilon for that max distance might be reasonable (preliminarily looking like it would be ~0.005); for f32s I'm seeing the max of that distance, for random coefficients from -100_000 to 100_000, right around 10, which I think is too high to accept in general, so I'll need to do a little more checking and maybe try a couple more things. (I'm struggling with trying to decide what a reasonable range of coefficient to test on f32s is; do you have any thoughts on that? Things are going to fail more as coefficients get larger in general, but I'd like to feel like I have reasonable error rates in some range at least. Originally I was looking at -1_000 to 1_000, but now I'm thinking maybe -100_000 to 100_000? (For that matter, is -1_000_000 to 1_000_000 reasonable for f64s?)) Probably best to hold off on the review for now; apologies if you've already begun. |
Actually it's a lot worse, I was (optimistically) leaving out a zero when I read the numbers: for f32s we're hitting that condition about 300_000 (not 30_000) times for every million pairs of curves with coefficients between -100_000 and 100_000. Wow. (I mean, in a sense that's just saying that epsilon for that condition was chosen poorly (assuming there's a good way to choose it), but wow, curves are reducing to a point a lot.) |
|
Sorry for the wait. Fantastic work! |
|
Ah sorry, I should have given an update sooner - I'm just working on finishing up notes on a new version; I should be able to post something later tonight that does a lot better on the last issues I mentioned. Thanks for the review! |
This is WIP - it's pretty much a straight port from the paper.js version. The main path seems to work on the few examples I've tested (it can find 9 intersections of two cubics, and the results match those of paper.js), but there are still a number of TODOs in the code.
I'm submitting now in case you'd like to give some early feedback (but if not no worries - I would say it's not ready for a technical review yet). [In particular I'm new to rust, so if you see some bad patterns I'd be happy to hear about them.]
A couple remarks:
I had to update the fat line cubic bezier computation to match that of paper.js: the algorithm was running out of space with the original fat lines (possibly because of other bugs I had at the time, I haven't gone back to check, but it seems the current (d1 * d2).is_sign_positive() will always have d1 * d2 <= 0, which seems suspicious; the constants are also different than what I've been seeing, but I haven't looked into that either). Do you have thoughts on the new version? If it's okay then I won't dig anymore.
Can you maybe say a few words about how you see this functionality fitting into the api? How will quad/quad intersections work? or quad/cubic? Right now I have the code in its own module, but that was mostly for my own benefit - I guess ultimately it will belong in cubic_bezier.rs to match line_intersections_t and line_intersections? (I haven't thought about self intersections yet.)