studies/grafik/Computergrafik-Code8/cgapplication.cpp
⇒
download file
1
2
3
4
5
6
7 #include "cgapplication.h"
8
9
10 static CGApplication* activeCGApplication_ = 0;
11 static CGApplication::MouseButton activeMouseButton_ = CGApplication::LeftMouseButton;
12
13 CGApplication::CGApplication() {
14 assert(!activeCGApplication_);
15 activeCGApplication_ = this;
16 }
17
18 CGApplication::~CGApplication() {
19 activeCGApplication_ = 0;
20 }
21
22
23 void CGApplication::onInit() { }
24 void CGApplication::onButton(MouseButton button, MouseButtonEvent event, int x, int y) { }
25 void CGApplication::onMove(MouseButton buttoin, int x, int y) { }
26 void CGApplication::onKey(unsigned char key) { }
27 void CGApplication::onTimer() { }
28
29
30 static void displayFunc() {
31 assert(activeCGApplication_);
32 activeCGApplication_->onDraw();
33 }
34
35
36 static void reshapeFunc(int newWidth, int newHeight) {
37 assert(activeCGApplication_);
38 activeCGApplication_->onSize(newWidth, newHeight);
39 }
40
41
42 static void mouseFunc(int button, int state, int x, int y) {
43 assert(activeCGApplication_);
44 y = glutGet(GLenum(GLUT_WINDOW_HEIGHT)) - y;
45 activeMouseButton_ = ((button == GLUT_LEFT_BUTTON)
46 ? CGApplication::LeftMouseButton
: CGApplication::RightMouseButton);
47 activeCGApplication_->onButton(activeMouseButton_,
48 ((state == GLUT_DOWN)
49 ? CGApplication::MouseButtonDown
: CGApplication::MouseButtonUp),
50 x, y);
51 }
52
53
54 static void motionFunc(int x, int y) {
55 assert(activeCGApplication_);
56 y = glutGet(GLenum(GLUT_WINDOW_HEIGHT)) - y;
57 activeCGApplication_->onMove(activeMouseButton_, x, y);
58 }
59
60
61 static void keyboardFunc(unsigned char key, int x, int y) {
62 assert(activeCGApplication_);
63 activeCGApplication_->onKey(key);
64 }
65
66
67 static void timerFunc(int msecs) {
68 assert(activeCGApplication_);
69 activeCGApplication_->onTimer();
70 glutTimerFunc(msecs, timerFunc, msecs);
71 }
72
73 void CGApplication::start(int argc, char* argv[],
74 const char* windowTitle,
75 unsigned int buffers, unsigned int msecsTimer,
76 unsigned long width, unsigned long height) {
77 assert(buffers & ColorBuffer);
78
79
80 glutInit(&argc, argv);
81
82
83 glutInitDisplayMode(GLUT_RGB
| ((buffers & DepthBuffer) ? GLUT_DEPTH : 0)
84 | ((buffers & DoubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE)
85 | ((buffers & StencilBuffer) ? GLUT_STENCIL : 0));
86
87
88 glutInitWindowSize(width, height);
89
90
91 glutCreateWindow(windowTitle);
92
93
94
95 glutDisplayFunc(displayFunc);
96 glutReshapeFunc(reshapeFunc);
97 glutMouseFunc(mouseFunc);
98 glutMotionFunc(motionFunc);
99 glutKeyboardFunc(keyboardFunc);
100
101 if(msecsTimer > 0) { glutTimerFunc(msecsTimer, timerFunc, msecsTimer); }
102
103
104 glutShowWindow();
105
106
107 onInit();
108
109
110 glutMainLoop();
111 }
112
113 void CGApplication::needsRedraw() {
114 glutPostRedisplay();
115 }
116
117 void CGApplication::swapBuffers() {
118 glutSwapBuffers();
119 }
120
121