-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
805 lines (673 loc) · 24.1 KB
/
Copy pathmain.cpp
File metadata and controls
805 lines (673 loc) · 24.1 KB
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
#pragma clang diagnostic push
#pragma ide diagnostic ignored "cert-err58-cpp"
/**
* Main
*/
// --- Libraries ---
// Normal Lib
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <cctype>
#include <string>
#include <iostream>
// Include GLEW
#include <GL/glew.h>
// Include GLFW
#include <GLFW/glfw3.h>
// image lib (cscd377)
//#include <IL/il.h>
//#include <IL/ilu.h>
//#include <IL/ilut.h>
// Modified GLM (obj file loaders)
#include "GLM.h"
// image lib (glfw)
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
// Math Lib
#define GLM_FORCE_RADIANS
#include <glm/mat4x4.hpp> // glm::mat4
#include <glm/gtc/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective
// h file of this assignment
#include "Cube.h"
#define OPENGL_DEBUG_FOR_GLFW true
// --- Filled's ---
// glfw window id
GLFWwindow* window;
// Bool to know when to exit
bool exitWindowFlag = false;
// title info
#define TITLE_LENGTH 100
// devIL is setup flag
[[maybe_unused]] bool devILIsSetup = false; // DO NOT CHANGE
// Window GL variables
/**
* Aspect ratio <br>
* Proportion between the width and the height of the window
*/
GLfloat aspect = 0.0;
// Booleans for current state
/**
* Flag if to stop the rotate of the camera around the object
*/
bool stop_rotate = true;
/**
* Flag to show the lines (not fill the trinalges)
*/
bool show_line = false;
/**
* Flag to show the lines with GL_CULL_FACE (not fill the trinalges)
*/
bool show_line_new = false;
/**
* Move the camera to look from above and change rotate to rotate the up vector
*/
bool top_view_flag = false;
// GL loc
/**
* The location of the model matrix in the shader
*/
GLint matrix_loc;
/**
* The location of the projection matrix in the shader
*/
GLint projection_matrix_loc;
/**
* The location of the view (Camera) matrix in the shader
*/
GLint view_matrix_loc;
// shader program
/**
* The handle of the shader program object.
*/
GLuint program;
// Matrix's
/**
* Camera matrix <br>
* Use glm::lookAt to make
*/
glm::mat4 view_matrix(1.0f);
/**
* 3d to 2d Matrix <br>
* Normally using glm::perspective to make
*/
glm::mat4 projection_matrix(1.0f);
/**
* matrix to apply to things being dawn <br>
* Often use at less one of these <br>
* - glm::scale <br>
* - glm::translate <br>
* - glm::rotate <br>
*/
glm::mat4 model_matrix(1.0f);
// Add light components
/**
* Vector of where the light position in 3d world
*/
glm::vec4 light_position(10.0, 6.0, 8.0, 1.0);
/**
* Vector of where the light position in 3d canvas from using view (camera) matrix and 3d world position
*/
glm::vec4 light_position_camera;
// uniform indices of light
/**
* The location of the light position in the shader
*/
GLint light_position_loc;
// Angle
/**
* Angle used for rotating the view (camera)
*/
GLfloat rotateAngle = 0.0f;
// --- Pre-Def Methods ---
/**
* Set the window flag to exit window
*/
void tellWindowToClose();
// --- Methods ---
/**
* Read A file and out put a file a char list
* @note code from Yasmin and commit and some modification make by Timbre Freeman
* @param filename path to the file
* @return pointer to a char list (String)
*/
char* ReadFile(const char* filename) {
FILE* infile;
#ifdef WIN32
fopen_s(&infile, filename, "rb");
#else
infile = fopen(filename, "rb");
#endif
if (!infile) {
fprintf(stderr, "Error: ReadFile: Unable to open file %s\n", filename);
return nullptr;
}
fseek(infile, 0, SEEK_END);
int len = static_cast<int>(ftell(infile));
fseek(infile, 0, SEEK_SET);
char* source = (char*)malloc(len + 1);
if (source == nullptr) {
fprintf(stderr, "Error: ReadFile: Unable to get memory to read file %s\n", filename);
tellWindowToClose();
return nullptr;
}
fread(source, 1, len, infile);
fclose(infile);
source[len] = 0;
fprintf(stdout, "Info: ReadFile: \"%s\" is ready\n", filename);
return (source);
}
/**
* Initialize Shaders
* @note code from Yasmin and commit and some modification make by Timbre Freeman
* @param v_shader the vertex shader path
* @param f_shader the fragment shader path
* @return a gl program object
*/
GLuint initShaders(const char* v_shader, const char* f_shader) {
GLuint p = glCreateProgram();
GLuint v = glCreateShader(GL_VERTEX_SHADER);
GLuint f = glCreateShader(GL_FRAGMENT_SHADER);
const char * vs = ReadFile(v_shader);
const char * fs = ReadFile(f_shader);
glShaderSource(v, 1, &vs, nullptr);
glShaderSource(f, 1, &fs, nullptr);
free((char*)vs);
free((char*)fs);
glCompileShader(v);
GLint compiled;
glGetShaderiv(v, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLsizei len;
glGetShaderiv(v, GL_INFO_LOG_LENGTH, &len);
char* log = (char*)malloc(len + 1);
if (log == nullptr) {
fprintf(stderr, "Error: initShaders: Was not able to get memory to get error code for compiled shader\n");
exit(EXIT_FAILURE);
}
glGetShaderInfoLog(v, len, &len, log);
fprintf(stderr, "Error: initShaders: Vertex Shader compilation failed: %s\n", log);
free(log);
tellWindowToClose();
}
glCompileShader(f);
glGetShaderiv(f, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLsizei len;
glGetShaderiv(f, GL_INFO_LOG_LENGTH, &len);
char* log = (char*)malloc(len + 1);
if (log == nullptr) {
fprintf(stderr, "Error: initShaders: Was not able to get memory to get error code for compiled shader\n");
exit(EXIT_FAILURE);
}
glGetShaderInfoLog(f, len, &len, log);
fprintf(stderr, "Error: initShaders: Vertex Shader compilation failed: %s\n", log);
free(log);
tellWindowToClose();
}
glAttachShader(p, v);
glAttachShader(p, f);
glLinkProgram(p);
GLint linked;
glGetProgramiv(p, GL_LINK_STATUS, &linked);
if (!linked) {
GLsizei len;
glGetProgramiv(p, GL_INFO_LOG_LENGTH, &len);
char* log = (char*)malloc(len + 1);
if (log == nullptr) {
fprintf(stderr, "Error: initShaders: Was not able to get memory to get error code for compiled shader\n");
exit(EXIT_FAILURE);
}
glGetProgramInfoLog(p, len, &len, log);
fprintf(stderr, "Error: initShaders: Shader linking failed: %s\n", log);
free(log);
tellWindowToClose();
}
glUseProgram(p);
return p;
}
///**
// * Load Texture
// * @note code from Yasmin and commit and some modification make by Timbre Freeman
// * @note (used devil to load the image)
// * @note do not forget to uncommitted the include lib at the top and uncommitted the setup in main
// * @param filename path to image file
// * @return GL Texture ID
// */
//unsigned int loadTexture(const char* filename) {
// if (devILIsSetup) {
// ILboolean success;
// unsigned int imageID;
// ilGenImages(1, &imageID);
//
// ilBindImage(imageID); /* Binding of DevIL image name */
// ilEnable(IL_ORIGIN_SET);
// ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
// success = ilLoadImage((ILstring)filename);
//
// if (!success) {
// fprintf(stderr, "Error: loadTexture: Couldn't load the following texture file: %s\n", filename);
// // The operation was not sucessfull hence free image and texture
// ilDeleteImages(1, &imageID);
// tellWindowToClose();
// return 0;
// }
//
// ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
//
// GLuint tid;
// glGenTextures(1, &tid);
// glBindTexture(GL_TEXTURE_2D, tid);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0,
// GL_RGBA, GL_UNSIGNED_BYTE, ilGetData());
//
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//
// glBindTexture(GL_TEXTURE_2D, 0);
//
// /* Because we have already copied image data into texture data
// we can release memory used by image. */
//
// ilDeleteImages(1, &imageID);
// fprintf(stdout, "Info: loadTexture: \"%s\" is ready\n", filename);
// return tid;
// } else {
// fprintf(stderr, "Error: loadTexture: DevIL is not setup\n");
// tellWindowToClose();
// return 0;
// }
//}
/**
* Called set setup open gl things (for example making the models)
*/
void Initialize(){
// Create the program for rendering the model
program = initShaders("shader.vert", "shader.frag");
// Check if making the shader work or not // This is not in FreeGLUT as does need an exit flag
if (exitWindowFlag) {
return;
}
// Use the shader program
glUseProgram(program);
// attribute indices
model_matrix = glm::mat4(1.0f);
view_matrix_loc = glGetUniformLocation(program, "view_matrix");
matrix_loc = glGetUniformLocation(program, "model_matrix");
projection_matrix_loc = glGetUniformLocation(program, "projection_matrix");
light_position_loc = glGetUniformLocation(program, "LightPosition");
// Set Clear Color (background color)
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
// setup Cube
createCube();
}
/**
* Called for every frame to draw on the screen
*/
void Display() {
// Clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// Show Lines
// Tell GL to use GL_CULL_FACE
if (show_line_new) {
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
} else {
glDisable(GL_CULL_FACE);
}
// Tell to fill or use Lines (not to fill) for the triangles
if (show_line || show_line_new) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} else {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
// Set Point Size
glPointSize(10);
// Set view matrix
float rotateAngleRadians = glm::radians(rotateAngle);
if (top_view_flag) { // Top View
view_matrix = glm::lookAt(
glm::vec3(0.0, 8.0f, 0.0), // camera is at the top
glm::vec3(0, 0, 0), // look at the center
glm::vec3(
sinf(rotateAngleRadians),
0.0f,
cosf(rotateAngleRadians)
) // rotating the camera
);
} else { // Normal View
view_matrix = glm::lookAt(
glm::vec3(
8.0f * sinf(rotateAngleRadians),
3.0f,
8.0f * cosf(rotateAngleRadians)
), // Moving around the center in a Center
glm::vec3(0, 0, 0), // look at the center
glm::vec3(0, 1, 0) // keeping the camera up
);
}
// Let opengl know about the change
glUniformMatrix4fv(view_matrix_loc, 1, GL_FALSE, (GLfloat*)&view_matrix[0]);
// update light_position_camera base off on both light position and view matrix
light_position_camera = view_matrix * light_position;
glUniform4fv(light_position_loc, 1, (GLfloat*)&light_position_camera[0]);
// update projection matrix (useful when the window resize)
projection_matrix = glm::perspective(glm::radians(45.0f), aspect, 0.3f, 100.0f);
glUniformMatrix4fv(projection_matrix_loc, 1, GL_FALSE, (GLfloat*)&projection_matrix[0]);
// Draw things
// Draw Cube
model_matrix = glm::scale(glm::mat4(1.0f), glm::vec3(2.0f, 2.0f, 2.0f));
glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, (GLfloat*)&model_matrix[0]);
drawCube();
// End of Draw things
glFlush();
}
// ------------------ This is where the code between GLFW and FreeGLUT are Different ---------------------------
/**
* key was pressed on last frame <br>
* - Key is char <br>
* - Value is bool
* @note when key is uppercase it use for normally Special cases like using shift or up arrow
*/
std::map<char, bool> keyPressed;
/**
* key is pressed this frame <br>
* - Key is char <br>
* - Value is bool
* @note when key is uppercase it use for normally Special cases like using shift or up arrow
*/
std::map<char, bool> keyCurrentlyPressed;
/**
* On each frame it check for user input to toggle a flag
*/
void keyboard() {
keyCurrentlyPressed['q'] = glfwGetKey(window, GLFW_KEY_Q ) == GLFW_PRESS;
if (!keyPressed['q'] && keyCurrentlyPressed['q']) {
tellWindowToClose();
}
keyPressed['q'] = keyCurrentlyPressed['q'];
keyCurrentlyPressed['s'] = glfwGetKey(window, GLFW_KEY_S ) == GLFW_PRESS;
if (!keyPressed['s'] && keyCurrentlyPressed['s']) {
show_line = !show_line;
}
keyPressed['s'] = keyCurrentlyPressed['s'];
keyCurrentlyPressed['S'] =
keyCurrentlyPressed['s'] && // glfwGetKey(window, GLFW_KEY_S ) == GLFW_PRESS
(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS ||
glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS);
if (!keyPressed['S'] && keyCurrentlyPressed['S']) {
show_line_new = !show_line_new;
// NOTE that s was press, so it also toggles the show_line flag above
}
keyPressed['S'] = keyCurrentlyPressed['S'];
keyCurrentlyPressed['u'] = glfwGetKey(window, GLFW_KEY_U ) == GLFW_PRESS;
keyCurrentlyPressed['t'] = glfwGetKey(window, GLFW_KEY_T ) == GLFW_PRESS;
if ((!keyPressed['t'] && keyCurrentlyPressed['t']) ||
(!keyPressed['u'] && keyCurrentlyPressed['u'])) {
top_view_flag = !top_view_flag;
}
keyPressed['t'] = keyCurrentlyPressed['t'];
keyPressed['u'] = keyCurrentlyPressed['u'];
keyCurrentlyPressed['r'] = glfwGetKey(window, GLFW_KEY_R ) == GLFW_PRESS;
if (!keyPressed['r'] && keyCurrentlyPressed['r']) {
stop_rotate = !stop_rotate;
}
keyPressed['r'] = keyCurrentlyPressed['r'];
}
/**
* Auto update GL Viewport when window size changes <br>
* This is a callback method for GLFW
* @param thisWindow the window that updated
* @param width the new width
* @param height the new height
*/
void windowSizeChangeCallback([[maybe_unused]] GLFWwindow* thisWindow, int width, int height) {
glViewport(0, 0, width, height);
aspect = float(width) / float(height);
}
/**
* Update Angle on each frame
* @param deltaTime the time between frames
*/
void updateAngle(GLfloat deltaTime) {
if (!stop_rotate) {
rotateAngle += 2.75f * 10 * deltaTime;
}
}
/**
* Set the window flag to exit window
*/
void tellWindowToClose() {
exitWindowFlag = true;
}
#if OPENGL_DEBUG_FOR_GLFW
/**
* OpenGL Debug message callback to output
* @param source Where the error came from
* @param type The type of error
* @param id the id of the error
* @param severity how bad the error was
* @param length Unknown (my guest is the size of message)
* @param message the message of the error
* @param userParam Unknown
* @see https://learnopengl.com/In-Practice/Debugging
* @warning if severity is high tell glfw to close
*/
void APIENTRY glDebugOutput(GLenum source,
GLenum type,
unsigned int id,
GLenum severity,
[[maybe_unused]] GLsizei length,
const char *message,
[[maybe_unused]] const void *userParam)
{
// ignore non-significant error/warning codes
if(id == 131169 || id == 131185 || id == 131218 || id == 131204) return;
std::cout << "Info: OpenGL Debug incoming (ID:" << id << ")" << std::endl;
std::string sourceMessage;
std::string typeMessage;
std::string severityMessage;
switch (source)
{
case GL_DEBUG_SOURCE_API: sourceMessage = "Source: API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: sourceMessage = "Source: Window System"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: sourceMessage = "Source: Shader Compiler"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY: sourceMessage = "Source: Third Party"; break;
case GL_DEBUG_SOURCE_APPLICATION: sourceMessage = "Source: Application"; break;
case GL_DEBUG_SOURCE_OTHER: sourceMessage = "Source: Other"; break;
default: sourceMessage = "Source: Unknown"; break;
}
switch (type)
{
case GL_DEBUG_TYPE_ERROR: typeMessage = "Type: Error"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: typeMessage = "Type: Deprecated Behaviour"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: typeMessage = "Type: Undefined Behaviour"; break;
case GL_DEBUG_TYPE_PORTABILITY: typeMessage = "Type: Portability"; break;
case GL_DEBUG_TYPE_PERFORMANCE: typeMessage = "Type: Performance"; break;
case GL_DEBUG_TYPE_MARKER: typeMessage = "Type: Marker"; break;
case GL_DEBUG_TYPE_PUSH_GROUP: typeMessage = "Type: Push Group"; break;
case GL_DEBUG_TYPE_POP_GROUP: typeMessage = "Type: Pop Group"; break;
case GL_DEBUG_TYPE_OTHER: typeMessage = "Type: Other"; break;
default: typeMessage = "Type: Unknown"; break;
}
FILE* output;
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: severityMessage = "Severity: high"; output = stderr; break;
case GL_DEBUG_SEVERITY_MEDIUM: severityMessage = "Severity: medium"; output = stderr; break;
case GL_DEBUG_SEVERITY_LOW: severityMessage = "Severity: low"; output = stdout; break;
case GL_DEBUG_SEVERITY_NOTIFICATION: severityMessage = "Severity: notification"; output = stdout; break;
default: severityMessage = "Severity: Unknown"; output = stderr; break;
}
fprintf(output, "-------OpenGL Debug--------\n"
"Debug message (ID:%u): %s\n"
"%s\n%s\n%s\n\n",
id, message,
sourceMessage.c_str(),
typeMessage.c_str(),
severityMessage.c_str());
if (severity == GL_DEBUG_SEVERITY_HIGH) {
tellWindowToClose();
}
}
#endif
// ------------------ Main ---------------------------
/**
* Start of the program MAIN <br>
* Has the main loop
* @return Exit code
*/
int main() {
// Initialise GLFW
fprintf(stdout, "Info: Initialise GLFW\n");
if (!glfwInit()) {
fprintf(stderr,"Error: initializing GLFW failed\n");
return EXIT_FAILURE;
}
fprintf(stdout, "Info: Setting window hint's\n");
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make macOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
#if OPENGL_DEBUG_FOR_GLFW
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);
#endif
// Open a window and create its OpenGL context
fprintf(stdout, "Info: Open a window and create its OpenGL context\n");
char orginal_title[TITLE_LENGTH];
strcpy(orginal_title, "GLFW - OpenGL - Basic");
window = glfwCreateWindow(512, 512, orginal_title, nullptr, nullptr);
if (window == nullptr) {
fprintf(stderr,"Error: Failed to open GLFW window\n");
glfwTerminate();
return EXIT_FAILURE;
}
glfwMakeContextCurrent(window);
// resize
fprintf(stdout, "Info: Setup resize (size change callback)\n");
glfwSetWindowSizeCallback(window, windowSizeChangeCallback);
int width, height;
glfwGetWindowSize(window, &width, &height);
windowSizeChangeCallback(window, width, height);
// icon
fprintf(stdout, "Info: Setup icon for the window\n");
GLFWimage icons[1];
icons[0].pixels = stbi_load(
"res/icon/cube.png",
&icons[0].width,
&icons[0].height,
nullptr, 4);
if (icons[0].pixels == nullptr) {
fprintf(stderr, "Error: Unable to load icon\n");
} else {
glfwSetWindowIcon(window, 1, icons);
stbi_image_free(icons[0].pixels);
}
// Initialize devil
// fprintf(stdout,"Info: Initialize DevIL\n");
// ilInit();
// devILIsSetup = true;
// Initialize GLEW
fprintf(stdout,"Info: Initialize GLEW\n");
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Error: Failed to initialize GLEW\n");
glfwTerminate();
return EXIT_FAILURE;
}
#if OPENGL_DEBUG_FOR_GLFW
fprintf(stdout,"Info: Initialize GL Debug Output\n");
int flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
{
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(glDebugOutput, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
} else {
fprintf(stderr, "Error: Opengl Debug not available\n");
}
#endif
fprintf(stdout, "Info: Running Initialize method\n");
Initialize();
// GL info
fprintf(stdout, "Info: GL Vendor : %s\n", glGetString(GL_VENDOR));
fprintf(stdout, "Info: GL Renderer : %s\n", glGetString(GL_RENDERER));
fprintf(stdout, "Info: GL Version (string) : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
fprintf(stdout, "Info: GLSL Version : %s\n", glGetString(GL_VERSION));
// Ensure we can capture the escape key being pressed below and any other keys
fprintf(stdout, "Info: Setup user input mode\n");
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
// List Keys being used
fprintf(stdout, "Info: Current keys being used\n");
// called to set the keys in keyboard map
keyboard();
// Go throw the map and print each key being used
for (std::pair<const char, bool> node: keyPressed) {
if (isupper(node.first)) { // Use uppercase for normally Special cases like using shift or up arrow
fprintf(stdout, "Info: - Special Key: %c\n", node.first);
} else {
fprintf(stdout, "Info: - Key: %c\n", node.first);
}
}
fprintf(stdout, "Info: setting up variables for the loop\n");
// DeltaTime variables
GLfloat lastFrame = 0.0f;
// FPS variables
GLfloat lastTimeFPS = 0.0f;
GLint numberOfFrames = 0;
double fps;
double avgFPS = 0.0;
int qtyFPS = 0;
fprintf(stdout,
"Info: Start window loop with exit:%s and glfwWindowShouldClose(window):%s\n",
exitWindowFlag ? "true" : "false",
glfwWindowShouldClose(window) ? "true" : "false");
while (!exitWindowFlag && !glfwWindowShouldClose(window)) {
// Calculate delta time
GLfloat currentFrame;
currentFrame = static_cast<GLfloat>(glfwGetTime());
GLfloat deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// FPS
{
GLfloat deltaTimeFPS = currentFrame - lastTimeFPS;
numberOfFrames++;
if (deltaTimeFPS >= 1.0f) {
fps = double(numberOfFrames) / deltaTimeFPS;
qtyFPS++;
avgFPS += (fps - avgFPS) / qtyFPS;
char title[TITLE_LENGTH];
snprintf(title, TITLE_LENGTH - 1,
"%s - [FPS: %3.2f]", orginal_title,
fps);
glfwSetWindowTitle(window, title);
//fprintf(stdout, "Info: FPS: %f\n", fps);
numberOfFrames = 0;
lastTimeFPS = currentFrame;
}
}
// Render
Display();
// Swap buffers
glfwSwapBuffers(window);
// Get evens (ex user input)
glfwPollEvents();
// check for user input to exit
exitWindowFlag = glfwGetKey(window, GLFW_KEY_ESCAPE ) == GLFW_PRESS || exitWindowFlag;
// check for user input
keyboard();
// update data (often angles of things)
updateAngle(deltaTime);
}
fprintf(stdout, "Info: Avg FPS: %f\n", avgFPS);
// Close OpenGL window and terminate GLFW
fprintf(stdout, "Info: Close OpenGL window and terminate GLFW\n");
glfwTerminate();
return EXIT_SUCCESS;
}
#pragma clang diagnostic pop