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
47 : CGApplication::RightMouseButton);
48 activeCGApplication_->onButton(activeMouseButton_,
49 ((state == GLUT_DOWN)
50 ? CGApplication::MouseButtonDown
51 : CGApplication::MouseButtonUp),
52 x, y);
53 }
54
55
56 static void motionFunc(int x, int y) {
57 assert(activeCGApplication_);
58 y = glutGet(GLenum(GLUT_WINDOW_HEIGHT)) - y;
59 activeCGApplication_->onMove(activeMouseButton_, x, y);
60 }
61
62
63 static void keyboardFunc(unsigned char key, int x, int y) {
64 assert(activeCGApplication_);
65 activeCGApplication_->onKey(key);
66 }
67
68
69 static void timerFunc(int msecs) {
70 assert(activeCGApplication_);
71 activeCGApplication_->onTimer();
72 glutTimerFunc(msecs, timerFunc, msecs);
73 }
74
75 void CGApplication::start(int argc, char* argv[],
76 const char* windowTitle,
77 unsigned int buffers, unsigned int msecsTimer,
78 unsigned long width, unsigned long height) {
79 assert(buffers & ColorBuffer);
80
81
82 glutInit(&argc, argv);
83
84
85 glutInitDisplayMode(GLUT_RGB
86 | ((buffers & DepthBuffer) ? GLUT_DEPTH : 0)
87 | ((buffers & DoubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE)
88 | ((buffers & StencilBuffer) ? GLUT_STENCIL : 0));
89
90
91 glutInitWindowSize(width, height);
92
93
94 glutCreateWindow(windowTitle);
95
96
97
98 glutDisplayFunc(displayFunc);
99 glutReshapeFunc(reshapeFunc);
100 glutMouseFunc(mouseFunc);
101 glutMotionFunc(motionFunc);
102 glutKeyboardFunc(keyboardFunc);
103
104 if(msecsTimer > 0) { glutTimerFunc(msecsTimer, timerFunc, msecsTimer); }
105
106
107 glutShowWindow();
108
109
110 onInit();
111
112
113 glutMainLoop();
114 }
115
116 void CGApplication::needsRedraw() {
117 glutPostRedisplay();
118 }
119
120 void CGApplication::swapBuffers() {
121 glutSwapBuffers();
122 }
123