kurbo

Function flatten

source
pub fn flatten(
    path: impl IntoIterator<Item = PathEl>,
    tolerance: f64,
    callback: impl FnMut(PathEl),
)
Expand description

Flatten the path, invoking the callback repeatedly.

Flattening is the action of approximating a curve with a succession of line segments.

The tolerance value controls the maximum distance between the curved input segments and their polyline approximations. (In technical terms, this is the Hausdorff distance). The algorithm attempts to bound this distance between by tolerance but this is not absolutely guaranteed. The appropriate value depends on the use, but for antialiased rendering, a value of 0.25 has been determined to give good results. The number of segments tends to scale as the inverse square root of tolerance.

The callback will be called in order with each element of the generated path. Because the result is made of polylines, these will be straight-line path elements only, no curves.

This algorithm is based on the blog post Flattening quadratic Béziers but with some refinements. For one, there is a more careful approximation at cusps. For two, the algorithm is extended to work with cubic Béziers as well, by first subdividing into quadratics and then computing the subdivision of each quadratic. However, as a clever trick, these quadratics are subdivided fractionally, and their endpoints are not included.

TODO: write a paper explaining this in more detail.