Getting started with OpenGL and C++

Below is a template that shows a fractal plant that you can modify with the keys z,w,s. Getting this to work was not straightforward, but the idea is that now you can just have fun and start your videogame. The code is not meant to be optimized at all, but simple. It’s pretty much self-explanatory, basically you can just replace the call to drawFrac in display to show whatever you want, and you handle key strokes in the idle function. I only tested it on Linux.

``````/*
This is a template to get started with OpenGL (which needs to be installed)
To compile: g++ GLtemplate.c++ -o GLtemplate -lglut -lGLU -lGL
To run: ./GLtemplate

It shows a fractal plant that you can modify with the keys z,w,s

*/

#include <GL/glut.h>
#include <stdio.h>
#include <math.h>

GLfloat userAngle = M_PI/2, userLength = 0.5;

//Keyboard code.  keyStates[x] is true if x is pressed.

bool keyStates[256];     //Key state values

void keyPressed (unsigned char key, int x, int y) { keyStates[key] = true;  }
void keyUp      (unsigned char key, int x, int y) { keyStates[key] = false; }

void idle() {
if (keyStates['z']) {userAngle += 0.01;}
if (keyStates['w']) {userLength += 0.01;}
if (keyStates['s']) {userLength -= 0.01; if (userLength < 0) userLength = 0;}
}

/* Draws a plant from x,y with first piece length l, and angle a
The window has coordinates from (-1,-1) to (1,1).  The center is 0,0.
*/

void drawFrac(GLfloat x,GLfloat y,GLfloat l, GLfloat a) {
if ( l < 0.001 )
return;

glColor3f(0, l*30, 0);
glLineWidth(l*10);  //Must be before glBegin(GL_LINES)

glBegin(GL_LINES);

glVertex2d(x,y);
glVertex2d(x+cos(a)*l,y+sin(a)*l);

glEnd();

drawFrac(x+cos(a)*l*0.3,y+sin(a)*l*0.3,l*0.3,a+M_PI/4);
drawFrac(x+cos(a)*l*0.6,y+sin(a)*l*0.6,l*0.4,a-M_PI/4);

drawFrac(x+cos(a)*l,y+sin(a)*l,l*0.5,a+M_PI/4);
drawFrac(x+cos(a)*l,y+sin(a)*l,l*0.5,a-M_PI/4);
}

//This is the function that draws everything on the screen
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear screen

/* Draw whatever you need here */
drawFrac(0,0,userLength,userAngle);

glutSwapBuffers();
glutPostRedisplay();
}

int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(1000, 1000);
glutInitWindowPosition(0,0);
glutCreateWindow("GLtemplate");
glutDisplayFunc(display);
glutIdleFunc(idle);
glutKeyboardUpFunc(keyUp);
glutKeyboardFunc(keyPressed);

glutMainLoop();
return 0;
}
``````