CPSC170A
Fundamentals of Computer Science II

Lab 30

Inheritance

Drawing Shapes

Create the class Polygon that represents a two-dimensional polygon that can be drawn using OpenGL. It should have the following functions:

// create a polygon at the specified location
Polygon::Polygon(float x, float y);

// change where a polygon is located by the specified ammount
// in the x and y directions
void Polygon::move(float delta_x, float delta_y);

Create the class Triangle that extends Polygon and the class Square that also extends Polygon. They should have the following functions:

// create a triangle at the specified location
Triangle::Triangle(float x, float y);

// use OpenGL to draw the triangle
// it doesn't matter what size or color
void Triangle::render() const;

// create a square at the specified location
Square::Square(float x, float y);

// use OpenGL to draw the square
// it doesn't matter what size or color
void Square::render() const;

The following code is an example of how the classes could be used:

#include <cstdlib>
#include <GLFW/glfw3.h>

// create a random floating-point number between -1.0f and 1.0f
float rand_float() {
  return rand() / (RAND_MAX / 2.0f) - 1.0f;
}

int main() {
  if (!glfwInit()) {
    return -1;
  }
  int width = 640;
  int height = 480;
  GLFWwindow* window = glfwCreateWindow(width, height, "Shapes", NULL, NULL);
  if (!window) {
    glfwTerminate();
    return -1;
  }
  glfwMakeContextCurrent(window);
  
  // create a triangle and square
  float triangle_x = rand_float();
  float triangle_y = rand_float();
  float triangle_delta_x = rand_float() / 100.0f;
  float triangle_delta_y = rand_float() / 100.0f;
  Triangle triangle(triangle_x, triangle_y);
  float square_x = rand() / (RAND_MAX / 2.0f) - 1.0f;
  float square_y = rand() / (RAND_MAX / 2.0f) - 1.0f;
  float square_delta_x = rand_float() / 100.0f;
  float square_delta_y = rand_float() / 100.0f;
  Square square(square_x, square_y);
  
  while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
         !glfwWindowShouldClose(window)) {
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    float ratio = width / (float) height;
    glOrtho(-ratio, ratio, -1.0f, 1.0f, 1.0f, -1.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    // update and render the triangle and square
    triangle.move(triangle_delta_x, triangle_delta_y);
    square.move(square_delta_x, square_delta_y);
    triangle.render();
    square.render();
    
    glfwSwapBuffers(window);
    glfwPollEvents();
  }
  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}