Exercises Computer Graphics

Session 10 - OpenGL Intro

Solutions

Exercises:

Useful Links:

Introduction

Solutions for session 10.

Exercises

Source code of the exercises.

Exercise 1: Spinning Cube

/*************************
 * Extra motion variables
 *************************/
float scalefactor = 1.0; // zooming factor
float a = 0; // rotation parameter

void draw() {
  // ...
 
  /**********************************
   * make cube turn counterclockwise
   **********************************/
  translate(0,-cos(a),sin(a));
  a += 0.01;

  /*******************
   * make cube rotate
   *******************/
  rotateX(cos(a)*radius);
  rotateY(sin(a)*radius);
  rotateZ(cos(tiltspeed * angle) * tilt);

  /*********************
   * Zooming in and out
   *********************/
  scale(cos(scalefactor), cos(scalefactor), cos(scalefactor));
  scalefactor += 0.01;

  drawCube();
}

Exercise 2: 3D Sierpinski Triangle

void recursive_tri(int i) {
  if (i <= 1) {  /* Base case: draw a pyramid */
    beginShape(TRIANGLES);
      fill(1.0f, 0.0f, 0.0f);
      vertex(-80.0, -80.0, 80.0);
      fill(0.0f, 1.0f, 0.0f);
      vertex(80.0, -80.0, 80.0);
      fill(0.0f, 0.0f, 1.0f);
      vertex(0.0, 80.0, 0.0);

      fill(1.0f, 0.0f, 0.0f);
      vertex(80.0, -80.0, 80.0);
      fill(0.0f, 1.0f, 0.0f);
      vertex(0.0, -80.0, -80.0);
      fill(0.0f, 0.0f, 1.0f);
      vertex(0.0, 80.0, 0.0);

      fill(1.0f, 0.0f, 0.0f);
      vertex(0.0, -80.0, -80.0);
      fill(0.0f, 1.0f, 0.0f);
      vertex(-80.0, -80.0, 80.0);
      fill(0.0f, 0.0f, 1.0f);
      vertex(0.0, 80.0, 0.0);

      fill(1.0f, 0.0f, 0.0f);
      vertex(-80.0, -80.0, 80.0);
      fill(0.0f, 1.0f, 0.0f);
      vertex(80.0, -80.0, 80.0);
      fill(0.0f, 0.0f, 1.0f);
      vertex(0.0, -80.0, -80.0);
    endShape();
  } else {
    --i;
    pushMatrix(); /* draw lower front left */
    translate(-40.0, -40.0, 40.0);
    scale(0.5, 0.5, 0.5);
    recursive_tri(i);
    popMatrix();

    pushMatrix();	 /* draw lower front right */
    translate(40.0, -40.0, 40.0);
    scale(0.5, 0.5, 0.5);
    recursive_tri(i);
    popMatrix();

    pushMatrix();	 /* draw lower back middle */
    translate(0.0, -40.0, -40.0);
    scale(0.5, 0.5, 0.5);
    recursive_tri(i);
    popMatrix();

    pushMatrix();	 /* draw top-middle */
    translate(0.0, 40.0, 0.0);
    scale(0.5, 0.5, 0.5);
    recursive_tri(i);
    popMatrix();
  }
}

The solutions to the C exercises can be found here.

Valid HTML 4.01 Transitional ©2008-2009 Tom Van Cutsem