-
Notifications
You must be signed in to change notification settings - Fork 0
/
Proper.cpp
531 lines (427 loc) · 16.3 KB
/
Proper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <GL/glew.h>
#include <GL/glu.h>
#include <GL/freeglut.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace std;
struct VAO {
GLuint VertexArrayID;
GLuint VertexBuffer;
GLuint ColorBuffer;
GLenum PrimitiveMode;
GLenum FillMode;
int NumVertices;
};
typedef struct VAO VAO;
struct GLMatrices {
glm::mat4 projection;
glm::mat4 model;
glm::mat4 view;
GLuint MatrixID;
} Matrices;
GLuint programID;
/* Function to load Shaders - Use it as it is */
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path) {
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
if(VertexShaderStream.is_open())
{
std::string Line = "";
while(getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
GLint Result = GL_FALSE;
int InfoLogLength;
// Compile Vertex Shader
printf("Compiling shader : %s\n", vertex_file_path);
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
// Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> VertexShaderErrorMessage(InfoLogLength);
glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);
// Compile Fragment Shader
printf("Compiling shader : %s\n", fragment_file_path);
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
glCompileShader(FragmentShaderID);
// Check Fragment Shader
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> FragmentShaderErrorMessage(InfoLogLength);
glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]);
// Link the program
fprintf(stdout, "Linking program\n");
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
// Check the program
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> ProgramErrorMessage( max(InfoLogLength, int(1)) );
glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
/* Generate VAO, VBOs and return VAO handle */
struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertex_buffer_data, const GLfloat* color_buffer_data, GLenum fill_mode=GL_FILL)
{
struct VAO* vao = new struct VAO;
vao->PrimitiveMode = primitive_mode;
vao->NumVertices = numVertices;
vao->FillMode = fill_mode;
// Create Vertex Array Object
glGenVertexArrays(1, &(vao->VertexArrayID)); // VAO
glGenBuffers (1, &(vao->VertexBuffer)); // VBO - vertices
glGenBuffers (1, &(vao->ColorBuffer)); // VBO - colors
glBindVertexArray (vao->VertexArrayID); // Bind the VAO
glBindBuffer (GL_ARRAY_BUFFER, vao->VertexBuffer); // Bind the VBO vertices
glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), vertex_buffer_data, GL_STATIC_DRAW); // Copy the vertices into VBO
glVertexAttribPointer(
0, // attribute 0. Vertices
3, // size (x,y,z)
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
glBindBuffer (GL_ARRAY_BUFFER, vao->ColorBuffer); // Bind the VBO colors
glBufferData (GL_ARRAY_BUFFER, 3*numVertices*sizeof(GLfloat), color_buffer_data, GL_STATIC_DRAW); // Copy the vertex colors
glVertexAttribPointer(
1, // attribute 1. Color
3, // size (r,g,b)
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
return vao;
}
/* Generate VAO, VBOs and return VAO handle - Common Color for all vertices */
struct VAO* create3DObject (GLenum primitive_mode, int numVertices, const GLfloat* vertex_buffer_data, const GLfloat red, const GLfloat green, const GLfloat blue, GLenum fill_mode=GL_FILL)
{
GLfloat* color_buffer_data = new GLfloat [3*numVertices];
for (int i=0; i<numVertices; i++) {
color_buffer_data [3*i] = red;
color_buffer_data [3*i + 1] = green;
color_buffer_data [3*i + 2] = blue;
}
return create3DObject(primitive_mode, numVertices, vertex_buffer_data, color_buffer_data, fill_mode);
}
/* Render the VBOs handled by VAO */
void draw3DObject (struct VAO* vao)
{
// Change the Fill Mode for this object
glPolygonMode (GL_FRONT_AND_BACK, vao->FillMode);
// Bind the VAO to use
glBindVertexArray (vao->VertexArrayID);
// Enable Vertex Attribute 0 - 3d Vertices
glEnableVertexAttribArray(0);
// Bind the VBO to use
glBindBuffer(GL_ARRAY_BUFFER, vao->VertexBuffer);
// Enable Vertex Attribute 1 - Color
glEnableVertexAttribArray(1);
// Bind the VBO to use
glBindBuffer(GL_ARRAY_BUFFER, vao->ColorBuffer);
// Draw the geometry !
glDrawArrays(vao->PrimitiveMode, 0, vao->NumVertices); // Starting from vertex 0; 3 vertices total -> 1 triangle
}
/**************************
* Customizable functions *
**************************/
float triangle_rot_dir = 1;
float rectangle_rot_dir = 1;
bool triangle_rot_status = true;
bool rectangle_rot_status = true;
/* Executed when a regular key is pressed */
void keyboardDown (unsigned char key, int x, int y)
{
switch (key) {
case 'Q':
case 'q':
case 27: //ESC
exit (0);
default:
break;
}
}
/* Executed when a regular key is released */
void keyboardUp (unsigned char key, int x, int y)//movement of buckets
{
switch (key) {
case 'c':
case 'C':
moveleftRedBucket = 1;
break;
case 'p':
case 'P':
triangle_rot_status = !triangle_rot_status;
break;
case 'x':
// do something
break;
default:
break;
}
}
/* Executed when a special key is pressed */
void keyboardSpecialDown (int key, int x, int y)
{
}
/* Executed when a special key is released */
void keyboardSpecialUp (int key, int x, int y)
{
}
/* Executed when a mouse button 'button' is put into state 'state'
at screen position ('x', 'y')
*/
void mouseClick (int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_UP)
triangle_rot_dir *= -1;
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_UP) {
rectangle_rot_dir *= -1;
}
break;
default:
break;
}
}
/* Executed when the mouse moves to position ('x', 'y') */
void mouseMotion (int x, int y)
{
}
/* Executed when window is resized to 'width' and 'height' */
/* Modify the bounds of the screen here in glm::ortho or Field of View in glm::Perspective */
void reshapeWindow (int width, int height)
{
GLfloat fov = 90.0f;
// sets the viewport of openGL renderer
glViewport (0, 0, (GLsizei) width, (GLsizei) height);
// set the projection matrix as perspective/ortho
// Store the projection matrix in a variable for future use
// Perspective projection for 3D views
// Matrices.projection = glm::perspective (fov, (GLfloat) width / (GLfloat) height, 0.1f, 500.0f);
// Ortho projection for 2D views
Matrices.projection = glm::ortho(-4.0f, 4.0f, -4.0f, 4.0f, 0.1f, 500.0f);
}
VAO *triangle, *rectangle;
// Creates the triangle object used in this sample code
void createTriangle ()
{
/* ONLY vertices between the bounds specified in glm::ortho will be visible on screen */
/* Define vertex array as used in glBegin (GL_TRIANGLES) */
static const GLfloat vertex_buffer_data [] = {
0, 1,0, // vertex 0
-1,-1,0, // vertex 1
1,-1,0, // vertex 2
};
static const GLfloat color_buffer_data [] = {
1,0,0, // color 0
0,1,0, // color 1
0,0,1, // color 2
};
// create3DObject creates and returns a handle to a VAO that can be used later
triangle = create3DObject(GL_TRIANGLES, 3, vertex_buffer_data, color_buffer_data, GL_LINE);
}
void createRectangle ()
{
// GL3 accepts only Triangles. Quads are not supported static
const GLfloat vertex_buffer_data [] = {
-1.2,-1,0, // vertex 1
1.2,-1,0, // vertex 2
1.2, 1,0, // vertex 3
1.2, 1,0, // vertex 3
-1.2, 1,0, // vertex 4
-1.2,-1,0 // vertex 1
};
static const GLfloat color_buffer_data [] = {
1,0,0, // color 1
0,0,1, // color 2
0,1,0, // color 3
0,1,0, // color 3
0.3,0.3,0.3, // color 4
1,0,0 // color 1
};
// create3DObject creates and returns a handle to a VAO that can be used later
rectangle = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color_buffer_data, GL_FILL);
}
float camera_rotation_angle = 90;
float rectangle_rotation = 0;
float triangle_rotation = 0;
/* Render the scene with openGL */
/* Edit this function according to your assignment */
void draw ()
{
// clear the color and depth in the frame buffer
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// use the loaded shader program
// Don't change unless you know what you are doing
glUseProgram (programID);
// Eye - Location of camera. Don't change unless you are sure!!
glm::vec3 eye ( 5*cos(camera_rotation_angle*M_PI/180.0f), 0, 5*sin(camera_rotation_angle*M_PI/180.0f) );
// Target - Where is the camera looking at. Don't change unless you are sure!!
glm::vec3 target (0, 0, 0);
// Up - Up vector defines tilt of camera. Don't change unless you are sure!!
glm::vec3 up (0, 1, 0);
// Compute Camera matrix (view)
// Matrices.view = glm::lookAt( eye, target, up ); // Rotating Camera for 3D
// Don't change unless you are sure!!
Matrices.view = glm::lookAt(glm::vec3(0,0,3), glm::vec3(0,0,0), glm::vec3(0,1,0)); // Fixed camera for 2D (ortho) in XY plane
// Compute ViewProject matrix as view/camera might not be changed for this frame (basic scenario)
// Don't change unless you are sure!!
glm::mat4 VP = Matrices.projection * Matrices.view;
// Send our transformation to the currently bound shader, in the "MVP" uniform
// For each model you render, since the MVP will be different (at least the M part)
// Don't change unless you are sure!!
glm::mat4 MVP; // MVP = Projection * View * Model
// Load identity to model matrix
Matrices.model = glm::mat4(1.0f);
/* Render your scene */
glm::mat4 translateTriangle = glm::translate (glm::vec3(-2.0f, 0.0f, 0.0f)); // glTranslatef
glm::mat4 rotateTriangle = glm::rotate((float)(triangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (1,0,0)
glm::mat4 triangleTransform = translateTriangle * rotateTriangle;
Matrices.model *= triangleTransform;
MVP = VP * Matrices.model; // MVP = p * V * M
// Don't change unless you are sure!!
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
// draw3DObject draws the VAO given to it using current MVP matrix
draw3DObject(triangle);
Matrices.model = glm::mat4(1.0f);
glm::mat4 translateRectangle = glm::translate (glm::vec3(2, 0, 0)); // glTranslatef
glm::mat4 rotateRectangle = glm::rotate((float)(rectangle_rotation*M_PI/180.0f), glm::vec3(0,0,1)); // rotate about vector (-1,1,1)
Matrices.model *= (translateRectangle * rotateRectangle);
MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
// draw3DObject draws the VAO given to it using current MVP matrix
draw3DObject(rectangle);
// Swap the frame buffers
glutSwapBuffers ();
// Increment angles
float increments = 1;
//camera_rotation_angle++; // Simulating camera rotation
triangle_rotation = triangle_rotation + increments*triangle_rot_dir*triangle_rot_status;
rectangle_rotation = rectangle_rotation + increments*rectangle_rot_dir*rectangle_rot_status;
}
/* Executed when the program is idle (no I/O activity) */
void idle () {
// OpenGL should never stop drawing
// can draw the same scene or a modified scene
draw (); // drawing same scene
}
/* Initialise glut window, I/O callbacks and the renderer to use */
/* Nothing to Edit here */
void initGLUT (int& argc, char** argv, int width, int height)
{
// Init glut
glutInit (&argc, argv);
// Init glut window
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitContextVersion (3, 3); // Init GL 3.3
glutInitContextFlags (GLUT_CORE_PROFILE); // Use Core profile - older functions are deprecated
glutInitWindowSize (width, height);
glutCreateWindow ("Sample OpenGL3.3 Application");
// Initialize GLEW, Needed in Core profile
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (err != GLEW_OK) {
cout << "Error: Failed to initialise GLEW : "<< glewGetErrorString(err) << endl;
exit (1);
}
// register glut callbacks
glutKeyboardFunc (keyboardDown);
glutKeyboardUpFunc (keyboardUp);
glutSpecialFunc (keyboardSpecialDown);
glutSpecialUpFunc (keyboardSpecialUp);
glutMouseFunc (mouseClick);
glutMotionFunc (mouseMotion);
glutReshapeFunc (reshapeWindow);
glutDisplayFunc (draw); // function to draw when active
glutIdleFunc (idle); // function to draw when idle (no I/O activity)
glutIgnoreKeyRepeat (true); // Ignore keys held down
}
/* Process menu option 'op' */
void menu(int op)
{
switch(op)
{
case 'Q':
case 'q':
exit(0);
}
}
void addGLUTMenus ()
{
// create sub menus
int subMenu = glutCreateMenu (menu);
glutAddMenuEntry ("Do Nothing", 0);
glutAddMenuEntry ("Really Quit", 'q');
// create main "middle click" menu
glutCreateMenu (menu);
glutAddSubMenu ("Sub Menu", subMenu);
glutAddMenuEntry ("Quit", 'q');
glutAttachMenu (GLUT_MIDDLE_BUTTON);
}
/* Initialize the OpenGL rendering properties */
/* Add all the models to be created here */
void initGL (int width, int height)
{
// Create the models
createTriangle (); // Generate the VAO, VBOs, vertices data & copy into the array buffer
// Create and compile our GLSL program from the shaders
programID = LoadShaders( "Sample_GL.vert", "Sample_GL.frag" );
// Get a handle for our "MVP" uniform
Matrices.MatrixID = glGetUniformLocation(programID, "MVP");
reshapeWindow (width, height);
// Background color of the scene
glClearColor (0.3f, 0.3f, 0.3f, 0.0f); // R, G, B, A
glClearDepth (1.0f);
glEnable (GL_DEPTH_TEST);
glDepthFunc (GL_LEQUAL);
createRectangle ();
cout << "VENDOR: " << glGetString(GL_VENDOR) << endl;
cout << "RENDERER: " << glGetString(GL_RENDERER) << endl;
cout << "VERSION: " << glGetString(GL_VERSION) << endl;
cout << "GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;
}
int main (int argc, char** argv)
{
int width = 600;
int height = 600;
initGLUT (argc, argv, width, height);
addGLUTMenus ();
initGL (width, height);
glutMainLoop ();
return 0;
}