Showing posts with label X-Plane Scenery Tools. Show all posts
Showing posts with label X-Plane Scenery Tools. Show all posts

Saturday, September 03, 2011

Bezier Curve Optimization

I've been meaning to write up a few notes about how we turn OSM vector data into bezier curves for X-Plane.  The code is all open source - look in the scenery tools web code browser at NetPlacement.cpp and BezierApprox.cpp for the code.

First, a few basics:
  • OSM vector data comes as a polyline data - that is, each road is a series of points connected by straight line segments.  There are a lot of points - sometimes every few meters along a road.
  • X-Plane 10 uses piece-wise bezier curves, meaning a road is a string of end-to-end bezier curves.  Each curve can be a line segment, quadratic, or cubic bezier curver, but not anything of higher degree.  
  • The representation in X-Plane for the piece-wise bezier curves is a list of "tagged" points, where the tag defines whether a point is a piece-wise curve end-point or control point.  Semantically, the two end points must not be control points (must not be tagged) and we can never have more than two consecutive control points (because that would define a higher-order bezier).
  • There is no requirement that the curve be smooth - we can create a sharp corner at any non-control point, even between two bezier curves.
Both OSM and X-Plane's road system have network topology, but for the purpose of converting a polyline to a piece-wise bezier curve we care only about a single road between junctions - that is, a "curve" in topology-terms.

We divide the problem into two parts: converting the polyline to a piece-wise bezier curve and optimizing that bezier curve to reduce point count.

To build the initial beziers we take an idea from ATI's PN-Triangles paper. The basic idea from the paper is this: if we have a poly-line (or triangle mesh) approximation of a curved surface, we can estimate the tangents at the vertices by averaging the direction of all incident linear components.  With the tangents at the vertices, we can then construct a bezier surface through that tangent (because a bezier curve's tangent at its end point runs toward the next control point) and use that to "round out" the mesh.

The idea is actually a lot easier to understand for polylines, where the dimensionality is lower.  For each vertex in our road, we'll find the "average" direction of the road (the tangent line) at that vertex based on the two segments coming into that vertex.  The bezier control points adjacent to the vertex must run along that tangent line; we can then adjust the distance of the control points from the end point to control the amount of "bulge".

We start with a poly-line.

We calculate the tangents at each vertex.

We place bezier control points along the tangents at fixed fractional lengths.

The result is a smooth piece-wise approximation through every point.
PN triangles tends to make meshes "bulge", because a curve around a convex hull always extends outward.  You can see the same look in our interpolation.  This is good for on-ramps but actually looks quite bad for a straight-away road - the road "bulges out" when the curve ends.

To address this, we categorize a road as "straight" if the road is long enough that if we built a curve out of it, the radius of that curve would be larger than a constant value.  (We pick different constants for different types of roads.)  In other words, if two highway segments are each 1 km long and they meet at a 3 degree angle, we do not assume it is part of an arc with a 19 km radius - we assume that most of the 1 km road are straight, with a small curve (of much smaller radius) at the end.  For any given point, we can decide whether either one or both of the two adjoining line segments is "straight" or should be entirely curved.  We then form five cases:
  1. If two segments come together at a very sharp angle, we simply keep the sharp angle.  We assume that if the data had this sharp angle in the original vector data (which is quite highly noded) then there really is some kind of sharp corner.
  2. If the two segments come together at a very shallow angle, we simply keep the corner, because who cares.  This case matters when we have a very tiny angle (e.g. 0.25 degrees) but very long line segments, such that removing the tiny angle would cause significant change in the vector position due to the long "arm" and not the steep angle.  We trust that for our app the tiny curve isn't going to be visible.
  3. If the two segments are both curved, we use the PN-triangle-style tangents as usual.
  4. If one of the segments is curved and one is straight, the tangent at the point comes from the straight curve.  This takes the "bulge" out of the beginning and ending of our curves by ensuring that the curve ends by heading "into" the straight-away.
  5. If both segments are straight, we need to round the corner on the inside.  We do this by pulling back the corner along both curves and using the original point as a quadratic bezier control point.
One note about cases 2 and 5: if you pull back a vertex proportional to the angle of the vertex, then very small angles can result in very small pull-backs, resulting in a very short curve.  In the case of X-Plane, we want to ensure that there is a minimum distance between points (so that rounding errors in the DSF encode don't give us colocated points); this means that the minimum angle for case 2 has to be large enough to prevent a "tiny curve" in case 5.
The five curve cases, illustrated.
With these five curve cases we get pretty good looking curved roads.  But our point gets out of control - at a minimum we've kept every original point, and on top of that we've added one or two bezier contrl points per segment.

What we need to do is generalize our curves.  Again, the PN-triangles observation can help us.  If we want to replace two piece-wise bezier curves with a single one, we know this: the tangent at the end of the curves can't change.  This means that the two control points of the approximate curve must be colinear with the control points of the original curve ends and the original curve ends itself.

So what?  Well, if we can only move the control points "in and out" then there are really only two scalar variables for all possible approximations: how much to scale the control handles at the start and end.  And that's something we can check with brute force!

Below is the basic step to approximating a piece-wise bezier curve with two pieces as a single cubic bezier.
We start with a piece-wise bezier with nodes and control points.

For each range of curves that we will simplify, we "push" the outermost control points along the tangent vector by an arbitrary scaling factor.

The resulting curve will be close, but not quite the same as the original.

The original also looks "reasonable" on its own - that is, the approximations tend to have good curvature characteristics.
To find the approximate curve, we simply "search" a whole range of scalar values by trying them and measuring curve error.  In the scenery tools code, we do a two-step search, refining the scalars around the values of least error.  The initial values are picked experimentally; it's almost certainly possible to do a better job of guessing scalar values but I haven't had time to research it more.

To measure the error we approximate the bezier with polylines (e.g. we turn each individual bezier into a poly-line of N segments) and then compare the polylines.  The polyline comparison is the variance of the distances of each point in one polyline to the other. (in other words, we treat one polyline as a point set and take the variance of the distance-to-polyline of each point).  This is similar to the Hausdorff distance with two key differences:
  • Because we are taking variance and not a minimum error, we can't use our previous minimum distance from a point to a line segment to limit our spatial searches.  (See below.)  Instead, we pick some large distance beyond which the curves are too different and we use that to limit.  For low maximum acceptable errors this gives us good performance.
  • Since the variance depends on all points and not just the worst one, we can rank multiple approximations - that is, generally better approximations score quite a bit higher.
To speed up the polyline compare (which is naively O(N^2) and dominates CPU time if implemented via a nested for-loop) we can create a spatial index for the "master" line (since we will compare many candidates to it) and search only a few of the master segments when looking for the closest one.  If we know that past a certain error we're simply broken, then we can limit our queries. For my implementation, I pick an axis (e.g. X or Y) based on the original curve shape and then subdivide the polyline into monotone sub-polylines that can be put into a coordinate-sorted map.  Then we can use lower_bound to find our segments in log(N) time.  An rtree would probably work as well.

Phew.  So we can take a piece-wise bezier and come up with the best approximation through brute force and error checking.  How do we simplify an entire road?  The answer is not Douglas-Peuker.  Instead we use a bottom-up combine:
  • For every non-end node in the piece-wise curve, we build the approximation of the two adjoining bezier curves and measure its error.
  • We queue every "possible merge" by error.
  • Until the queue is empty or the lowest error is too large we..
  • Replace the two curves in the merge by one.
  • Recalculate the two neighboring merges (since one of their source curves is now quite a bit different).  Note that we must keep the original beziers around to get accurate error metrics, so a merge of two curves that originally covered eight curves is an approximation of all eight originals, not the two previous merges.
Why is this better than DP?  Well, the cost of approximating two curves is going to be O(NlogN) where N is the number of pieces in the piece-wise curve - this comes straight from the cost of error measurement.  Therefore the first run through DP, just to add one point back, is going to be O(N^2logN) because it must do a full curve comparison between the original and every pair it tries.  When the curve approximation is going to contain a reasonably large number of pieces (e.g. we might merge each bezier with its neighbor and be done) the bottom-up approach gets there fast while DP does a ton of work just to realize that it didn't need to do that work.  (DP doesn't have this issue with polylines because the comparison cost is constant per trial point.)

Sunday, October 11, 2009

Connected Networks, Shaping Points, and WED

I implemented connected networks in WED and I'm about to go rip the code out and try again. What went wrong?

Well, first, to be clear:
  • A "curve" in computational geometry terms is just a line you could draw without lifting your pen. So a line segment, a bezier curve, a circle, or a Z shape, those are all "curves".
  • A connected network is a series of curves where each curve ends in a node. Two curves starting/ending at the same point share the node at that point. (In other words, two curves may cross without a node, but if two curves end at a node, the node is always shared.)
  • A shaping point is a point on a curve used to define the curve (like a sharp corner in our "Z" shape) that is not a node. Conceptually the lines on both sides of the shaping point are part of the same curve.
This concept is already used in X-Plane - it is the foundation for the road grid system. (Nodes represent the real junctions where a car can make a decision.) One note from the X-Plane road system: since shaping points don't define a break between two curves, but rather the shape of one big curve, we need to insert a node if the road is going to change types at a point. In other words, we need a node to start/end a road, have an intersection with another road, or change types. Otherwise a shaping point is fine.

I was working on connected networks support in WED. WED has an underlying set of geometric primitives. Putting new editing features in is trivially easy when the geometric primitives exist. (For example, overlay editing uses the same geometry as airports, so it was an easy feature.) But WED does not yet have connected network support. We need it to edit road grids and we will probably need it to define the taxi paths of AI airplanes in the future.

The Naive Approach

So the first thing I did was define an "edge" type. Its interface is a point sequence, but it had the special property that its end nodes were shared points, while its internal (shape) points were "contained" inside the primitive.

This worked and I can edit using this type, but it turns out it doesn't really work very well. Here are all of the reasons why this turned out to be a poor design choice:
  • The user interface doesn't make obvious distinctions between nodes and shaping points, but the data model does. This means that a lot of operations have to convert nodes to shape points or vice versa. Thus the editing logic spends a lot of time trying to 'maintain' the rules about nodes vs. shape points.
  • To make it worse, since nodes are not part of a curve but shape points are, it means our points are constantly appearing and disappearing from the hierarchy of editing primitives as a shape point becomes a node (which can have a real name) or not. Furthermore, the number of edges is constantly changing. The change in the hierarchy presented to the user makes sense if you are familiar with topology theory...which is to say, it doesn't make much sense at all.
  • The internal code for the edge itself has a lot of special cases because the end nodes and internal nodes are different. This starts to matter when we consider several bezier curves ending at a single point. Normally WED keeps the curve control handle with the point, but if a point is shared, this doesn't work, so this information has to belong to the edge.
Take 2

So the new design will try a different assumption: no shape points. Every point will split a curve into two parts whether it's a shaping point or not. The good:
  • All nodes are handled the same, and no rules have to be enforced. Every point is a node, and we're done. Every segment is a bezier curve, with the control handles owned by the edge.
And the bad:
  • We have to merge edges into shape points on export. This is actually not very hard and is the least of our problems.
  • We need to provide a really good interface for working with multiple edges, since a single edge is almost always going to be a smaller unit of work than the user wants to deal with. This means selecting an entire string of edges (not hard) but also having edit-multiple-entities work well. (This feature is a little bit borked right now.)
  • It will be possible for the user to "create" more entities by not keeping meta-data for a string of edges in sync. This kind of "accidental split" wasn't possible with the old design.
So we've traded a series of invariance bugs (e.g. the risk of WED data model not meeting requirements that aren't enforced by the compiler) for a series of usability bugs (e.g. users getting annoyed that it's hard to use the program).

Wednesday, April 15, 2009

Sometimes You Get a Gift

Sometimes you get really lucky and a library has a routine that just does exactly what you want.

I got lucky the other day, thanks to this function: make_conforming_Delaunay_2.

The X-Plane scenery tools creates a mesh by triangulating a big pile of points, prioritizing the points that are most important to capturing the "shape" of the terrain.  It also adds in a series of edges ("constraints") that must exist, to ensure that the borders between land-water are triangle edges.

The problem is that these edges reduce the "quality" of the triangulation - a long forced edge can force a long thin triangle, which in turn looks ugly.  For example, in this picture, the red edges are forced into the triangulation, causing a lot of long thin triangles.

CGAL::make_conforming_Delaunay_2 is like a one-stop spa and resort for your mesh...it adds the necessary points to cut long thin triangles into more balanced ones, like this.

I don't expect that kind of service from a code library, but when it happens, I like it!

Why CGAL?

The X-Plane scenery tools use CGAL as a base library for most geometry calculations.  This post attempts to explain the situation.

For The Impatient

CGAL uses precise numeric types - replacements for normal floating point math that don't have rounding errors. You can treat the data types that come from CGAL as "opaque" - they aren't really opaque, but their implementation is complex enough that you're better off not looking inside it.  The main things to know:
  • Point_2 has members .x() and .y() that return the X and Y coordinates.  You need to use CGAL::to_double to convert these opaque (but precise) numeric to a double.
  • Be warned: the conversion to_double is not exact!  You may get rounding errors 'just because'.
  • You can't change a Point_2 (or any other CGAL geometric primitive) once it is created.  Instead you would construct a new Point_2 that is based on the original Point_2.
No Rounding Errors?  How?!?

Here's a very brief sketch of how you can have floating point that doesn't create rounding errors.  There are basically two cases we have to look at:
  • For multiplication, addition and subtraction, the risk is that we might run out of mantissa and have to round.  To work around this, we build an object that can dynamically allocate memory for the mantissa.  If we run out of space, we just allocate more.
  • For division, that's not good enough; 1/3 is a repeating decimal (in base 10 or binary) no matter how many digits you have.  So we store the numerator and denominator separately (both having arbitrary mantissa).
Those two techniques give us a numeric type that is capable of performing +, -, * and / without rounding errors, which is actually enough to implement most geometry algorithms.

What CGAL actually does is a lot more sophisticated and well-optimized.  Arbitrary precision math is slow (think of what happens if you replace every FPU operation with a dynamic memory operation).  CGAL can pool and reference count number "objects", use real FPU approximations (switching to slow precise math only when necessary) and has a number of wrappers that defer expensive computations, avoiding unnecessary work.

Ben, Did You Take an H-Bomb to a Knife Fight?

The big question here is perhaps: is it worth it?  CGAL is heavy-weight complex heavily templated machinery and there are penalties for using it (in terms of performance, memory footprint, ease-of-debugging, etc).  Well?

Yes - I can say unequivocally that CGAL is worth it - I know because I have tried building the scenery tools both ways, and the CGAL way is much, much easier.

There is a fundamental problem with the kinds of algorithms that the scenery tools must do (finding the union of polygons, etc.): rounding error.

An algorithm that is correct in principle according to the rules of geometry becomes wrong when coded in floating point; imagine if the mid-point between two points is not actually collinear with the original points...that kind of thing happens all the time with floating point. (Other fun phenomena include points that are not on either side of a line, nor are they on the line itself, and triangles that are neither clockwise nor counterclockwise.)

We have only two real options to deal with this:
  1. Recognize when floating point has failed us and code a reasonable alternative.
  2. Get better floating point.  (This is exactly what CGAL does.)
Now I like CGAL because it has algorithms right out of the box that I need, coded a lot better than I would ever do...examples:
  • Fast incremental constrained Delaunay triangulation.
  • Union and intersection of large numbers of polygons in optimal computation time.
But the big win of CGAL (to me) is in avoiding edge cases.  The scenery code involves a lot of "constructive" geometry - that is, code where I go in and compute some new shapes based loosely on input data in a way that "looks nice" for X-Plane.  These are big blocks of code using fundamental geometric operations...finding the intersection of lines, adding vectors to points, and testing side-of-line.

Thus option 1 (detect edge cases) isn't really viable.  It would mean asking 'how can this blow up' for pretty much every single line of code I write, and in some cases there isn't a really great answer if something goes wrong.

By using exact floating point, CGAL provides exact constructive geometry, which means that I can go write big fat piles of constructive scenery-creation code and trust that the results are what I think they should be regardless of how weird the input data is.

Friday, April 03, 2009

XPTools - A Thing of Beauty

I'm going to start blogging about the X-Plane Scenery Tools code tree here...the source code is too technical of a subject for my scenery blog, which is aimed at authors, not programmers. Now that the repository has been cleaned up, other programmers can start working with the code pretty easily...if they Google for answers maybe some of these posts will show up.

Let me show something that I think is really quite beautiful:

http://dev.x-plane.com/cgit/cgit.cgi/xptools.git/tree/?h=master

That is the root level of the X-Plane Scenery Tools code tree, after a week of Janos and myself bashing at it. A ton of legacy code has been ripped out, file names normalized, library systems standardized across builds, etc. If you want to work with the scenery tools code, you can now do so without going crazy from the mess of random code floating around.

(You will still go crazy trying to understand how the hell the algorithms work. :-)

Here's another thing that I think looks good:


That's the cleaned version of the brains of "MeshTool".  Having it pulled out means that I can now add usability features, like more automated handling of orthophotos quickly and easily.  In fact, so could you!

One more...


Okay - that one doesn't even make sense to me.  The polygon code in the scenery tools had this horrible hack called "dominance" - Andrew can testify to how ugly it was.  The polygon code uses a DCEL as its data structure for polygons.  This means that for every "edge" (line) in the map, there are actually two "half-edges", lines in opposite directions that overlap.

The problem: which one contains the road data?  The old solution was dominance - exactly one was flagged as "dominant" and held the metadata.  The dominance flag helped code figure out where to look/store the data to avoid double-storage.

What a gross hack.  Dominance has been fully removed from the code.  And the data?  It is now possibly stored on either half-edge.  This isn't just a way to remove dominance, it's necessary. A road segment is now stored on the half-edge that goes in the direction of traffic.  So I can now import one-way street grids and the directional information is preserved.