Thursday, August 21, 2008

3. Spline Interpolation

I have been away from this pages for a long time. Though, in the period passed, I red a lot of Cocoa and Objective-C tutorials and guides (expecially the Apple official guides).


One of the mandatory features of the software I want to develop is smoothing of strokes I paint with the tablet (or mouse).


Why smoothing algorithm is needed?

Tablet input data is sent to computer at a fixed sampling rate (it depends on the hardware features). Tablet hardware read pen position every n milliseconds, software takes position data and connects each position with a stright line. This means that, if the artist draws a curve fast enough, the curve will be a poly-line (i.e. a sequence of points connected by stright lines).

smooth_disabled.png
A curve stroke with the smooth disabled.
smooth_active.png
A curve stroke with the smooth enabled.


As you can see it is not natural.


To resolve this problem, professional painting softwares (like Painter or Photoshop) implemet a smoothing algorithm to grow programmatically detail between two subsequent pen positions, and give the curve a more natural appearance. These algorithms (there are several variants) are based on math functions that guarantee a good approximation and fast computing performances.


To draw curves Cocoa provides only Bezier Splines, either in the AppKit framework, using NSBezierPath methods and in the Quatz 2D functions for the CGContext.


Bezier Splines are special case of Cubic Splines where you have to know 2 points (the start and the end point of the curve) and 2 control points (computer artists, who know vector applications like Illustrator, Freehand or Inkscape, use to call them "handles" because they move them to control the bias and the orientation of the curve).

bezier_curves.png
2 different oriented Bezier curves.

Though, Tablet input events do not carry any control points data. Those events pass only data about the points that stay on curve path.
This means that Bezier paths are not the solution to our problems.

Then I started searching the Web, looking for documentation about Spline Interpolation algorithms.

The mathematics, I should be proficient to actually understand deeply the theory beneath the Spline Interpolation, involve Derivatives, Integrals and many other complex things. Unfortunatelly my mathematics reminds in this fields have blanks, and so, I am currently not able to indipendently implement the algorithm starting from a math text.

Then, I browsed the Web looking for some examples that could help me to understand how to actually implement this algorithm.

And I found some...