January 21, 2014

OpenGL: Messing with input

Thought I would try my hand at messing with input.  So what this code does is record all of the points on the screen that the user clicked and displays them.

I'm realizing that functions like display(), mykey, mymouse are what my C teacher was talking about (function pointers) and I didn't really understand them at the time.  I guess C# makes it easier with delegates, but it's nice to see what it is on a lower level.

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glext.h>

struct vertex {
double x;
double y;
};

std::vector<vertex> vertices;

//////////////////////////////////////////////////////

void display()
{
glClearColor(0,0,0,1); 
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); 

glPointSize(10);
glBegin(GL_POINTS); 

glVertex3f(-1,-1,0);

glColor3f(1, .0784, .576);
for (size_t i = 0; i < vertices.size(); i++) {
vertex temp = vertices[i];
glVertex3f((temp.x/600)* 2 - 1, -1*((temp.y/600) * 2 - 1), 0);
}
glEnd(); 

glutSwapBuffers(); 
}

///////////////////////////////////////////////////////////

void mymouse(int button, int state, int x, int y)
{
if (state == GLUT_DOWN) {
vertex new_vertex;
new_vertex.x = (double)x;
new_vertex.y = (double)y;
vertices.push_back(new_vertex);
}

glutPostRedisplay();
}

///////////////////////////////////////////////////////////////

void mykey(unsigned char key, int x, int y)
{
 switch(key) {
case 'q': exit(1);
break; 

case 'w':
for (size_t i = 0; i < vertices.size(); i++) {
printf("%d %d, ", vertices[i].x, vertices[i].y);
}
printf("\n\n");
break;
}
}
///////////////////////////////////////////////////////////////

int main(int argc, char** argv) 
{
glutInit(&argc, argv); 
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE); 
glutInitWindowSize(600,600); 

glutCreateWindow("Record mouse clicks"); 
glutDisplayFunc(display); 
glutMouseFunc(mymouse); 
glutKeyboardFunc(mykey); 
glutMainLoop(); 
}




I'm doing a bunch of small things right now, but I'm hoping they are all building blocks to something cool I'll be able to do in the future.