Exercises Computer Graphics

Session 9 - Bezier-curves Solutions

Solutions

Exercises:

Useful Links:

Introduction

Solutions for session 9.

Exercises

Source code of the exercises.

Exercise 1: de-Casteljau's algorithm

// implements b^i_n(t)
Point calcBezier(int n, int i, double t) {
  if (n==1) return controls[i];
  Point p1=calcBezier(n-1, i, t);
  Point p2=calcBezier(n-1, i+1, t);
  return new Point((1-t)*p1.x + t*p2.x, (1-t)*p1.y + t*p2.y);
}

// draws a bezier curve with controls.length control points
// control point i is accessible via controls[i]
void drawBezier() {
  Point p1, p2;

  p1=calcBezier(controls.length, 0, 0);
  for (double t=0; t < 1.0025; t+=0.005) {
    p2 = calcBezier(controls.length, 0, t);
    line((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y);
    p1=p2;
  }
}

Exercise 2: Uniform B-Splines

// draws a curve segment of the B-spline, for 4 control points
void drawBSplineCurve(int i) {
  Point p0 = controls[i+0];
  Point p1 = controls[i+1];
  Point p2 = controls[i+2];
  Point p3 = controls[i+3];

  for (double t=0; t < 1.0025; t+=0.005) {
    // apply parametric formula to obtain x and y coordinates
    double x = (1.0/6.0) * ( t*t*t*(-p0.x + 3*p1.x - 3*p2.x +p3.x) +
                             t*t*  (3*p0.x - 6*p1.x + 3*p2.x) +
                             t*    (-3*p0.x + 3*p2.x) +
                                   (p0.x + 4*p1.x + p2.x) );
    double y = (1.0/6.0) * ( t*t*t*(-p0.y + 3*p1.y - 3*p2.y +p3.y) +
                             t*t*  (3*p0.y - 6*p1.y + 3*p2.y) +
                             t*    (-3*p0.y + 3*p2.y) +
            	                   (p0.y + 4*p1.y + p2.y) );
    point((int) x, (int)y);
  }
}

// draws a B-spline with controls.length control points,
// consisting of controls.length - 3 curve segments
void drawBSpline() {
  for (int i=0; i < controls.length-3; i++) {
    // draw the curve for control points [ i, i+1, i+2, i+3 ]
    drawBSplineCurve(i);
  }
}
Valid HTML 4.01 Transitional ©2008-2009 Tom Van Cutsem