B4J Code Snippet [B4X] Fitting a smooth curved line to a sequence of points

This simple technique was mentioned in this thread
https://www.b4x.com/android/forum/t...lines-any-smoothing-option.143117/post-906813

It was not an appropriate solution for that thread, so I am presenting it here with a couple of examples where it is very effective.

The first is where you want a line drawing based on some image. Sample points on the outline of the drawing and then use the algorithm to fit the line.

screenShot.png



The second example comes from my Virtual Trainset project. It was introduced in this thread.
https://www.b4x.com/android/forum/t...ge-creating-an-impressionistic-effect.143149/
The tracks are sampled from a railway map. The scene shows 4 trains (red, blue, 2 yellow) following the smoothed track.
The image is a moment of time in the animation.

TrainMoment.jpeg




Algorithm:

Imagine three points. They form a corner. Cut the tip off the corner.
You now have four points, and a smoother connection between the end points.

Cutting close to the tip of the corner makes it less round.
Cutting close to the midpoint of each edge makes it more round.

Final smoothness is determined by the number of times the resulting curve is fed back into the smoothing process.
Each iteration increases the number of points. For 3 starting points: 3, 4, 6, 10 ... 2 + 2 * (Ni - 2)
It goes up quickly (I usually repeat it 3 or 4 times), but the process is fast enough to use in animations.

It works on all point lists, even for complex curves that intersect themselves.
The actual sub where the smoothing is done is small, but it depends on a custom type and requires a bit of explanation.
The source code with the smoothing sub is included in the .zip file.
 

Attachments

  • CurveDrawing.zip
    162.7 KB · Views: 165

Star-Dust

Expert
Licensed User
Longtime User
To round I use the Bezier curves or C-spline
 

William Lancee

Well-Known Member
Licensed User
Longtime User
@Star-Dust
At first it appears that this technique is similar to splines, but it is different in that the resulting curve does not need to fit all
specified points. In fact, it rarely fits any of them exactly. The source for this algorithm is age-old. Who invented the wheel?
Wheels are square blanks (wood or stone) with corners cut repeatedly until they are smooth enough to roll.

Splines are based on another age-old tradition, boatbuilding, where points were connected with a thin batten (spline)
to form a fair (smooth, mostly un-undulating) curve. The set of curves define the shape of the boat's hull.
 

Star-Dust

Expert
Licensed User
Longtime User
so just for the sake of conversation, I would have replaced corners with arcs to get a quick and simple algorithm. It would be easy to find the focus of an arc that joins two straight lines. But I repeat it's just to talk about your solution too
 
Top