mbohun
10/25/2012 - 6:14 AM

OpenGL, libSDL, C++ key events

OpenGL, libSDL, C++ key events

#include <iostream>

#include <GL/gl.h>
#include <SDL/SDL.h>

using namespace std;

bool running =true;

class EventHandler {

private:
    SDL_Event event;

    void (EventHandler::* eventTypeHandler[SDL_NUMEVENTS])();

    void handleKeyDown() { cout << "handleKeyDown" << endl; }
    void handleKeyUp() { cout << "handleKeyUp" << endl; }
    void handleMouseMotion() {}
    void handleMouseButtonDown() {}
    void handleMouseButtonUp() {}
    void handleVideoResize() {}
    void handleQuit() { 
	cout << "handleQuit" << endl; 
	running=false;
    }

    void dummy() { cout << "dummy" << endl; }

public:
    EventHandler() {

	//init the whole jump table to dummy()
	for (int i=0; i<SDL_NUMEVENTS; ++i) {
	    eventTypeHandler[i] =&EventHandler::dummy;
	}

	//register the functions for events we are interested in
	eventTypeHandler[SDL_KEYDOWN]         =&EventHandler::handleKeyDown;
	eventTypeHandler[SDL_KEYUP]           =&EventHandler::handleKeyUp;
	eventTypeHandler[SDL_MOUSEMOTION]     =&EventHandler::handleMouseMotion;
	eventTypeHandler[SDL_MOUSEBUTTONDOWN] =&EventHandler::handleMouseButtonDown;
	eventTypeHandler[SDL_MOUSEBUTTONUP]   =&EventHandler::handleMouseButtonUp;
	eventTypeHandler[SDL_VIDEORESIZE]     =&EventHandler::handleVideoResize;
	eventTypeHandler[SDL_QUIT]            =&EventHandler::handleQuit;
    }
    

public:
    void handle() {
	while( SDL_PollEvent( &event ) ) {
	    (this->*eventTypeHandler[event.type])();	
	}
    }

};

int main(int argc, char* argv ) {

    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_GL_SetAttribute( SDL_GL_RED_SIZE,     5  );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,   5  );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE,    5  );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE,   16 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1  );

    SDL_Surface* scr = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL);

    EventHandler eh;

    while (running) {
	eh.handle();
    }

    SDL_Quit();

    return 0;
}