torsdag 11 juni 2009

Bézier Curves in Mathematica

Picking up Applied Geometry for Computer Graphics and CAD by Duncan March, I read a chapter on Bézier curves. They are polynomial curves defined by control points that in a very intuitive way let a designer shape the curve. Bézier curves are really a killer app for the Manipulate and Locator commands in Mathematica. A cubic polynomial need four Locators (control points) in order to be defined:

You need a cubic polynomial in order to be able to create a loop or a cusp:

Is there any other interesting phenomena that becomes possible if we allow higer order polynomials? I don't know but here's a heart or the contour of a fox head. The LocatorAutoCreate option let us add Locators just by holding the alt key and click in the graphics area.

To do this in Mathematica (version 6 or more), define the Bernstein polynomials and the Bézier curve as on page 131 in March's book. Then in the Manipulate construction, you can make a list of Locators called b. Here's the code:

bernstein[i_, n_, t_] := n! (1 - t)^(n - i) t^i/((n - i)! i!)

bezier[t_, b_List] := 
 Module[{n = Length[b] - 1}, 
  Sum[b[[i + 1]] bernstein[i, n, t], {i, 0, n}]]

Manipulate[
 Module[
  {bez},
  bez[t_] = bezier[t, b];
  ListLinePlot[Table[bez[t], {t, 0, 1, 0.01}], 
   PlotRange -> {{0, 1}, {0, 5}}]
  ],
 {
  {b, Table[{i, 0.0}, {i, 0, 1, 1/3.0}]},
  Locator,
  LocatorAutoCreate -> True
  }
 ]

It is crucial that the bezier function takes an arbitrary length list b as parameter. Otherwise it wouldn't work to use LocatorAutoCreate. Consider doing this in Java, how many cups of coffee you would need. To finish, in version 7 you can use an in-built function called BezierCurve instead of defining your own. But it's not necessary from a performance perspective, the response is immediate with my version on a single-core 1.7 MHz Pentium M.

Inga kommentarer:

Skicka en kommentar