-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
2216 lines (1804 loc) · 86.6 KB
/
main.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
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Marysha Brown
* CS330 Computer Graphic and Visualization
* Final Project
*/
#include <iostream> // cout, cerr
#include <cstdlib> // EXIT_FAILURE
#include <GLEW/glew.h> // GLEW library
#include <GLFW/glfw3.h> // GLFW library
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h> // Image loading Utility functions
// GLM Math Header inclusions
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <numbers>
#include <camera.h> // Camera class
using namespace std; // Standard namespace
/*Shader program Macro*/
#ifndef GLSL
#define GLSL(Version, Source) "#version " #Version " core \n" #Source
#endif
// Unnamed namespace
namespace
{
const char* const WINDOW_TITLE = "Marysha Brown - CS330 Final Project"; // Macro for window title
// Variables for window width and height
const int WINDOW_WIDTH = 1200;
const int WINDOW_HEIGHT = 900;
// Stores the GL data relative to a given mesh
struct GLMesh
{
GLuint vao; // Handle for the vertex array object
GLuint vbos[2]; // Handle for the vertex buffer object
GLuint nVertices; // Number of indices of the mesh
};
// Main GLFW window
GLFWwindow* gWindow = nullptr;
// Triangle mesh data
GLMesh gMesh;
GLMesh gLightMesh;
GLMesh gAmbMesh;
GLMesh gTableMesh;
GLMesh gBookMesh;
GLMesh gNotebookMesh;
GLMesh gFluoriteMesh;
GLMesh gBallMesh;
GLMesh gScentBaseMesh;
GLMesh gScentTopMesh;
GLMesh gCoasterMesh;
GLMesh gLightBaseMesh;
GLMesh gLightTopMesh;
// Texture
GLuint gTextureId;
GLuint gTableTextureId;
GLuint gBookTextureId;
GLuint gNotebookTextureId;
GLuint gFluoriteTextureId;
GLuint gBallTextureId;
GLuint gScentBaseTextureId;
GLuint gScentTopTextureId;
GLuint gCoasterTextureId;
GLuint gLightBaseTextureId;
GLuint gLightTopTextureId;
glm::vec2 gUVScale(1.0f, 1.0f); //Texture Scale
GLint gTexWrapMode = GL_REPEAT; //Texture wrapping
// Shader programs
GLuint gProgramId;
GLuint gLampProgramId;
//Camera
Camera gCamera(glm::vec3(0.0f, 10.0f, 30.0f)); //Camera location
float gLastX = WINDOW_WIDTH / 2.0f;
float gLastY = WINDOW_HEIGHT / 2.0f;
bool gFirstMouse = true;
//Timing
float gDeltaTime = 0.0f; // time between current frame and last frame
float gLastFrame = 0.0f;
//Objects color
glm::vec3 gObjectColor(1.f, 1.0f, 1.0f);
//Spotlight color, position, scale
glm::vec3 gLightColor(1.0f, 1.0f, 1.0f); //White
glm::vec3 gLightPosition(10.f, 20.f, 20.0f);
glm::vec3 gLightScale(0.5f);
//Ambient light color, position, scale
glm::vec3 gAmbLightColor(0.780f, 0.082f, 0.522f); //Light Salmon
glm::vec3 gAmbLightPosition(-10.f, 20.f, 20.0f);
glm::vec3 gAmbLightScale(0.5f);
// Lamp animation
bool gIsLampOrbiting = false;
//View
bool gOrthoView = false;
}
/* User-defined Function prototypes to:
* initialize the program, set the window size,
* redraw graphics on the window when resized,
* and render graphics on the screen
*/
bool UInitialize(int, char* [], GLFWwindow** window);
void UResizeWindow(GLFWwindow* window, int width, int height);
void UProcessInput(GLFWwindow* window);
void UMousePositionCallback(GLFWwindow* window, double xpos, double ypos);
void UMouseScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
void UMouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
void UCreateCubeMesh(GLMesh& mesh);
void UCreatePyramidMesh(GLMesh& mesh);
void UCreatePlaneMesh(GLMesh& mesh);
void UCreateFluoriteMesh(GLMesh& mesh);
void UCreateCylinderMesh(GLMesh& mesh);
void UCreateSphereMesh(GLMesh& mesh);
void UDestroyMesh(GLMesh& mesh);
bool UCreateTexture(const char* filename, GLuint& textureId);
void UDestroyTexture(GLuint textureId);
void URender();
bool UCreateShaderProgram(const char* vtxShaderSource, const char* fragShaderSource, GLuint& programId);
void UDestroyShaderProgram(GLuint programId);
//----------------------
//VERTEX SHADER SOURCE CODE
//----------------------
const GLchar* vertexShaderSource = GLSL(440,
layout(location = 0) in vec3 position; // VAP position 0 for vertex position data
layout(location = 1) in vec3 normal; // VAP position 1 for normals
layout(location = 2) in vec2 textureCoordinate;
//back
out vec3 vertexNormal; // For outgoing normals to fragment shader
out vec3 vertexFragmentPos; // For outgoing color / pixels to fragment shader
out vec2 vertexTextureCoordinate; //For outgoing texture
//Uniform / Global variables for the transform matrices
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(position, 1.0f); // Transforms vertices into clip coordinates
vertexFragmentPos = vec3(model * vec4(position, 1.0f)); // Gets fragment / pixel position in world space only (exclude view and projection)
vertexNormal = mat3(transpose(inverse(model))) * normal; // get normal vectors in world space only and exclude normal translation properties
vertexTextureCoordinate = textureCoordinate;
}
);
//----------------------
//FRAGMENT SHADER SOURCE CODE
//----------------------
const GLchar* fragmentShaderSource = GLSL(440,
in vec3 vertexNormal; // For incoming normals
in vec3 vertexFragmentPos; // For incoming fragment position
in vec2 vertexTextureCoordinate;//For incoming texture coordinates
out vec4 fragmentColor; // For outgoing color to the GPU
// Uniform / Global variables for object color, light color, light position, and camera/view position
uniform vec3 objectColor;
uniform vec3 lightColor;
uniform vec3 ambientLightColor;
uniform vec3 lightPos;
uniform vec3 ambientLightPos;
uniform vec3 viewPosition;
uniform vec3 ambViewPosition;
uniform sampler2D uTexture; // Useful when working with multiple textures
uniform vec2 uvScale;
void main()
{
/*Phong lighting model calculations to generate ambient, diffuse, and specular components*/
//Calculate Spotlight lighting
float spotStrength = 0.1f; // Set ambient or global lighting strength
vec3 spot = spotStrength * lightColor; // Generate ambient light color
//Calculate Ambient lighting
float ambientStrength = 0.2f; // Set ambient or global lighting strength
vec3 ambient = ambientStrength * ambientLightColor; // Generate key light color
//Calculate Diffuse lighting
vec3 norm = normalize(vertexNormal); // Normalize vectors to 1 unit
vec3 lightDirection = normalize(lightPos - vertexFragmentPos); // Calculate distance (light direction) between light source and fragments/pixels on pyramid
vec3 ambientLightDirection = normalize(ambientLightPos - vertexFragmentPos); // Calculate distance (light direction) between light source and fragments/pixels on pyramid
float impact = max(dot(norm, lightDirection), 0.0);// Calculate diffuse impact by generating dot product of normal and light
float ambientImpact = max(dot(norm, ambientLightDirection), 0.0);// Calculate key impact by generating dot product of normal and light
vec3 diffuse = impact * lightColor; // Generate diffuse light color
vec3 ambientDiffuse = ambientImpact * ambientLightColor; // Generate key light color
//Calculate Specular lighting
float specularIntensity = 0.1f; // Set specular light strength
float highlightSize = 10.0f; // Set specular highlight size
vec3 viewDir = normalize(viewPosition - vertexFragmentPos); // Calculate view direction
vec3 ambViewDir = normalize(ambViewPosition - vertexFragmentPos); // Calculate ambient view direction
vec3 reflectDir = reflect(-lightDirection, norm);// Calculate reflection vector
vec3 ambReflectDir = reflect(-ambientLightDirection, norm);// Calculate ambient reflection vector
//Calculate specular components
float specularComponent = pow(max(dot(viewDir, reflectDir), 0.0), highlightSize);
float ambSpecularComponent = pow(max(dot(ambViewDir, ambReflectDir), 0.0), highlightSize);
vec3 specular = specularIntensity * specularComponent * lightColor;
vec3 ambientSpecular = specularIntensity * ambSpecularComponent * ambientLightColor;
// Texture holds the color to be used for all three components
vec4 textureColor = texture(uTexture, vertexTextureCoordinate * uvScale);
// Calculate phong result
vec3 phong = (spot + ambient + diffuse + specular) * textureColor.xyz;
fragmentColor = vec4(phong, 1.0); // Send lighting results to GPU
}
);
//----------------------
//LAMP SHADER SOURCE CODE
//----------------------
const GLchar* lampVertexShaderSource = GLSL(440,
layout(location = 0) in vec3 position; // VAP position 0 for vertex position data
//Uniform / Global variables for the transform matrices
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
gl_Position = projection * view * model * vec4(position, 1.0f); // Transforms vertices into clip coordinates
}
);
//----------------------
//LAMP FRAGMENT SHADER SOURCE CODE
//----------------------
const GLchar* lampFragmentShaderSource = GLSL(440,
out vec4 fragmentColor; // For outgoing lamp color (smaller cube) to the GPU
void main()
{
fragmentColor = vec4(1.0f); // Set color to white (1.0f,1.0f,1.0f) with alpha 1.0
}
);
// Images are loaded with Y axis going down, but OpenGL's Y axis goes up, so let's flip it
void flipImageVertically(unsigned char* image, int width, int height, int channels)
{
for (int j = 0; j < height / 2; ++j)
{
int index1 = j * width * channels;
int index2 = (height - 1 - j) * width * channels;
for (int i = width * channels; i > 0; --i)
{
unsigned char tmp = image[index1];
image[index1] = image[index2];
image[index2] = tmp;
++index1;
++index2;
}
}
}
//----------------------
//MAIN FUNCTION
//----------------------
int main(int argc, char* argv[])
{
if (!UInitialize(argc, argv, &gWindow)) {
return EXIT_FAILURE;
}
//----------------------
//CREATE THE MESHES
//----------------------
//UCreateMesh(gMesh); // Calls the function to create the Vertex Buffer Object
//UCreatePyramidMesh(gPyramidMesh); //Pyramid
UCreateCubeMesh(gLightMesh); //Spotlight
UCreateCubeMesh(gAmbMesh); //Ambient light
UCreatePlaneMesh(gTableMesh); //Tabletop
UCreateCubeMesh(gBookMesh); //Book
UCreateCubeMesh(gNotebookMesh); //Notebook
UCreateFluoriteMesh(gFluoriteMesh); //Fluorite
UCreateSphereMesh(gBallMesh); //Lacrosse Ball
UCreateCylinderMesh(gScentBaseMesh); //Scent Base
UCreateCylinderMesh(gScentTopMesh); //Scent Top
UCreateCubeMesh(gCoasterMesh); //Coaster
UCreateCylinderMesh(gLightBaseMesh); //Light Base
UCreateSphereMesh(gLightTopMesh); //Light Top
//----------------------
//CREATE THE SHADER PROGRAMS
//----------------------
//if (!UCreateShaderProgram(cubeVertexShaderSource, cubeFragmentShaderSource, gCubeProgramId))
if (!UCreateShaderProgram(vertexShaderSource, fragmentShaderSource, gProgramId)) {
cout << "ERROR CREATING SHADER." << endl;
return EXIT_FAILURE;
}
if (!UCreateShaderProgram(lampVertexShaderSource, lampFragmentShaderSource, gLampProgramId)) {
cout << "ERROR CREATING LAMP SHADER." << endl;
return EXIT_FAILURE;
}
//----------------------
//LOAD TEXTURES
//----------------------
//TABLETOP TEXTURE
//----------------
const char* texFilename = "include/table.jpg";
if (!UCreateTexture(texFilename, gTableTextureId)) {
cout << "ERROR LOADING TABLETOP TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "tableTexture"), 0);
//BOOK TEXTURE
//----------------
texFilename = "include/bluebook.png";
if (!UCreateTexture(texFilename, gBookTextureId)) {
cout << "ERROR LOADING BOOK TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "bookTexture"), 0);
//NOTEBOOK TEXTURE
//----------------
texFilename = "include/notebook.png";
if (!UCreateTexture(texFilename, gNotebookTextureId)) {
cout << "ERROR LOADING NOTEBOOK TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "notebookTexture"), 0);
//FLUORITE TEXTURE
//----------------
texFilename = "include/fluorite.png";
if (!UCreateTexture(texFilename, gFluoriteTextureId)) {
cout << "ERROR LOADING FLUORITE TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "fluoriteTexture"), 0);
//LACROSSE BALL TEXTURE
//----------------
texFilename = "include/ball.png";
if (!UCreateTexture(texFilename, gBallTextureId)) {
cout << "ERROR LOADING LAX BALL TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "ballTexture"), 0);
//SCENT BASE TEXTURE
//----------------
texFilename = "include/green.png";
if (!UCreateTexture(texFilename, gScentBaseTextureId)) {
cout << "ERROR LOADING SCENT BASE TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "scentBaseTexture"), 0);
//SCENT TOP TEXTURE
//----------------
texFilename = "include/cap.png";
if (!UCreateTexture(texFilename, gScentTopTextureId)) {
cout << "ERROR LOADING SCENT TOP TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "scentTopTexture"), 0);
//COASTER TEXTURE
//----------------
texFilename = "include/coaster.png";
if (!UCreateTexture(texFilename, gCoasterTextureId)) {
cout << "ERROR LOADING COASTER TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "coasterTexture"), 0);
//LIGHT BASE TEXTURE
//----------------
texFilename = "include/lightbottom.png";
if (!UCreateTexture(texFilename, gLightBaseTextureId)) {
cout << "ERROR LOADING LIGHT BASE TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "lightBaseTexture"), 0);
//LIGHT TOP TEXTURE
//----------------
texFilename = "include/lighttop.png";
if (!UCreateTexture(texFilename, gLightTopTextureId)) {
cout << "ERROR LOADING LIGHT TOP TEXTURE." << texFilename << endl;
return EXIT_FAILURE;
}
//Tell opengl for each sampler to which texture unit it belongs to
glUseProgram(gProgramId);
//Set the texture as texture unit 0
glUniform1i(glGetUniformLocation(gProgramId, "lightTopTexture"), 0);
//Sets the background color of the window to black (it will be implicitely used by glClear)
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
//Render loop
//-----------
while (!glfwWindowShouldClose(gWindow))
{
//Per-frame timing
// --------------------
float currentFrame = glfwGetTime();
gDeltaTime = currentFrame - gLastFrame;
gLastFrame = currentFrame;
// input
// -----
UProcessInput(gWindow);
// Render this frame
URender();
glfwPollEvents();
}
// Release mesh data
UDestroyMesh(gLightMesh); //Spotlight
UDestroyMesh(gAmbMesh); //Ambient light
UDestroyMesh(gTableMesh); //Tabletop
UDestroyMesh(gBookMesh); //Book
UDestroyMesh(gNotebookMesh); //Notebook
UDestroyMesh(gFluoriteMesh); //Fluorite
UDestroyMesh(gBallMesh); //Lacrosse Ball
UDestroyMesh(gScentBaseMesh); //Scent Base
UDestroyMesh(gScentTopMesh); //Scent Top
UDestroyMesh(gCoasterMesh); //Coaster
UDestroyMesh(gLightBaseMesh); //Light Base
UDestroyMesh(gLightTopMesh); //Light Top
// Release texture
UDestroyTexture(gTableTextureId); //Tabletop
UDestroyTexture(gBookTextureId); //Book
UDestroyTexture(gNotebookTextureId); //Notebook
UDestroyTexture(gFluoriteTextureId); //Fluorite
UDestroyTexture(gBallTextureId); //Lacrosse Ball
UDestroyTexture(gScentBaseTextureId); //Scent Base
UDestroyTexture(gScentTopTextureId); //Scent Top
UDestroyTexture(gCoasterTextureId); //Coaster
UDestroyTexture(gLightBaseTextureId); //Light Base
UDestroyTexture(gLightTopTextureId); //Light Top
// Release shader programs
UDestroyShaderProgram(gProgramId);
UDestroyShaderProgram(gLampProgramId);
exit(EXIT_SUCCESS); // Terminates the program successfully
}
// Initialize GLFW, GLEW, and create a window
bool UInitialize(int argc, char* argv[], GLFWwindow** window)
{
// GLFW: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// GLFW: window creation
// ---------------------
* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, NULL, NULL);
if (*window == NULL)
{
std::cout << "ERROR CREATING GLFW WINDOW" << std::endl;
glfwTerminate();
return false;
}
glfwMakeContextCurrent(*window);
glfwSetFramebufferSizeCallback(*window, UResizeWindow);
glfwSetCursorPosCallback(*window, UMousePositionCallback);
glfwSetScrollCallback(*window, UMouseScrollCallback);
glfwSetMouseButtonCallback(*window, UMouseButtonCallback);
// tell GLFW to capture our mouse
glfwSetInputMode(*window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// GLEW: initialize
// ----------------
// Note: if using GLEW version 1.13 or earlier
glewExperimental = GL_TRUE;
GLenum GlewInitResult = glewInit();
if (GLEW_OK != GlewInitResult)
{
std::cerr << glewGetErrorString(GlewInitResult) << std::endl;
return false;
}
// Displays GPU OpenGL version
cout << "OpenGL Version Info: " << glGetString(GL_VERSION) << endl;
return true;
}
//----------------------
//KEYBOARD INPUT PROCESSING
//Query GLFW whether relevant keys are pressed/released this frame and react accordingly
//----------------------
void UProcessInput(GLFWwindow* window)
{
static const float cameraSpeed = 2.5f;
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
gCamera.ProcessKeyboard(FORWARD, gDeltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
gCamera.ProcessKeyboard(BACKWARD, gDeltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
gCamera.ProcessKeyboard(LEFT, gDeltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
gCamera.ProcessKeyboard(RIGHT, gDeltaTime);
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
{
gCamera.ProcessKeyboard(UP, gDeltaTime);
}
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
{
gCamera.ProcessKeyboard(DOWN, gDeltaTime);
}
//Repeat texture wraping
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS && gTexWrapMode != GL_REPEAT)
{
glBindTexture(GL_TEXTURE_2D, gTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindTexture(GL_TEXTURE_2D, 0);
gTexWrapMode = GL_REPEAT;
cout << "Current Texture Wrapping Mode: REPEAT" << endl;
}
//Mirrored repeat texture wraping
else if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS && gTexWrapMode != GL_MIRRORED_REPEAT)
{
glBindTexture(GL_TEXTURE_2D, gTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
glBindTexture(GL_TEXTURE_2D, 0);
gTexWrapMode = GL_MIRRORED_REPEAT;
cout << "Current Texture Wrapping Mode: MIRRORED REPEAT" << endl;
}
//Clamp to edge texture wraping
else if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS && gTexWrapMode != GL_CLAMP_TO_EDGE)
{
glBindTexture(GL_TEXTURE_2D, gTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
gTexWrapMode = GL_CLAMP_TO_EDGE;
cout << "Current Texture Wrapping Mode: CLAMP TO EDGE" << endl;
}
//Clamp to border texture wraping
else if (glfwGetKey(window, GLFW_KEY_4) == GLFW_PRESS && gTexWrapMode != GL_CLAMP_TO_BORDER)
{
float color[] = { 1.0f, 0.0f, 1.0f, 1.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);
glBindTexture(GL_TEXTURE_2D, gTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glBindTexture(GL_TEXTURE_2D, 0);
gTexWrapMode = GL_CLAMP_TO_BORDER;
cout << "Current Texture Wrapping Mode: CLAMP TO BORDER" << endl;
}
if (glfwGetKey(window, GLFW_KEY_RIGHT_BRACKET) == GLFW_PRESS)
{
gUVScale += 0.1f;
cout << "Current scale (" << gUVScale[0] << ", " << gUVScale[1] << ")" << endl;
}
else if (glfwGetKey(window, GLFW_KEY_LEFT_BRACKET) == GLFW_PRESS)
{
gUVScale -= 0.1f;
cout << "Current scale (" << gUVScale[0] << ", " << gUVScale[1] << ")" << endl;
}
//Ortho vs projection
if (glfwGetKey(window, GLFW_KEY_Y) == GLFW_PRESS && !gOrthoView) {
gOrthoView = true;
cout << "Switched to orthographic view" << endl;
}
else if (glfwGetKey(window, GLFW_KEY_U) == GLFW_PRESS && gOrthoView) {
gOrthoView = false;
cout << "Switched to projection view" << endl;
}
// Pause and resume lamp orbiting
static bool isLKeyDown = false;
if (glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS && !gIsLampOrbiting) {
gIsLampOrbiting = true;
}
else if (glfwGetKey(window, GLFW_KEY_K) == GLFW_PRESS && gIsLampOrbiting) {
gIsLampOrbiting = false;
}
}
// GLFW: whenever the window size changed (by OS or user resize) this callback function executes
void UResizeWindow(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
//----------------------
//MOUSE FUNCTIONS
//----------------------
// GLFW: whenever the mouse moves, this callback is called
void UMousePositionCallback(GLFWwindow* window, double xpos, double ypos)
{
if (gFirstMouse)
{
gLastX = xpos;
gLastY = ypos;
gFirstMouse = false;
}
float xoffset = xpos - gLastX;
float yoffset = gLastY - ypos; // reversed since y-coordinates go from bottom to top
gLastX = xpos;
gLastY = ypos;
gCamera.ProcessMouseMovement(xoffset, yoffset);
}
// GLFW: whenever the mouse scroll wheel scrolls, this callback is called
void UMouseScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
gCamera.ProcessMouseScroll(yoffset);
}
// GLFW: handle mouse button events
void UMouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
switch (button)
{
case GLFW_MOUSE_BUTTON_LEFT:
{
if (action == GLFW_PRESS)
cout << "Left mouse button pressed" << endl;
else
cout << "Left mouse button released" << endl;
}
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
{
if (action == GLFW_PRESS)
cout << "Middle mouse button pressed" << endl;
else
cout << "Middle mouse button released" << endl;
}
break;
case GLFW_MOUSE_BUTTON_RIGHT:
{
if (action == GLFW_PRESS)
cout << "Right mouse button pressed" << endl;
else
cout << "Right mouse button released" << endl;
}
break;
default:
cout << "Unhandled mouse button event" << endl;
break;
}
}
//----------------------
//RENDER A FRAME
//----------------------
void URender()
{
//----------------------
//LAMP ORBIT:
//Orbit or Un-orbit by pressing L or K keys
//Lamp orbits around the origin
//----------------------
const float angularVelocity = glm::radians(45.0f);
if (gIsLampOrbiting)
{
glm::vec4 newPosition0 = glm::rotate(angularVelocity * gDeltaTime, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec4(gLightPosition, 1.0f);
gLightPosition.x = newPosition0.x;
gLightPosition.y = newPosition0.y;
gLightPosition.z = newPosition0.z;
glm::vec4 newPosition1 = glm::rotate(angularVelocity * gDeltaTime, glm::vec3(0.0f, 1.0f, 0.0f)) * glm::vec4(gLightPosition, 1.0f);
gLightPosition.x = newPosition1.x;
gLightPosition.y = newPosition1.y;
gLightPosition.z = newPosition1.z;
}
// Enable z-depth
glEnable(GL_DEPTH_TEST);
// Clear the frame and z buffers
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//RENDERING VARIABLES
//----------------
glm::vec2 uvScale;
const glm::vec3 cameraPosition = gCamera.Position; //Get camera position
glm::mat4 scale, translation, rotation, model, view, projection;
//CAMERA MODES
//----------------
if (gOrthoView)
{
//Camera view transformation
view = gCamera.GetViewMatrix();
//Orthographic (2D) projection
projection = glm::ortho(-(GLfloat)WINDOW_WIDTH * 0.01f, (GLfloat)WINDOW_WIDTH * 0.01f, -(GLfloat)WINDOW_HEIGHT * 0.01f, (GLfloat)WINDOW_HEIGHT * 0.01f, 0.1f, 100.0f);
}
else
{
//Camera view transformation
view = gCamera.GetViewMatrix();
//Perspective (3D) projection
projection = glm::perspective(glm::radians(gCamera.Zoom), (GLfloat)WINDOW_WIDTH / (GLfloat)WINDOW_HEIGHT, 0.1f, 100.0f);
}
//----------------------
// LAMP (SPOTLIGHT):
// DRAW LAMP - CUBE SHAPE
//----------------------
// Activate the cube VAO (used by cube and lamp)
glBindVertexArray(gLightMesh.vao);
// Set the shader to be used
glUseProgram(gLampProgramId);
//Transform the smaller cube used as a visual que for the light source
model = glm::translate(gLightPosition) * glm::scale(gLightScale);
// Reference matrix uniforms from the Lamp Shader program
GLint modelLoc = glGetUniformLocation(gLampProgramId, "model");
GLint viewLoc = glGetUniformLocation(gLampProgramId, "view");
GLint projLoc = glGetUniformLocation(gLampProgramId, "projection");
// Pass matrix data to the Lamp Shader program's matrix uniforms
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
glDrawArrays(GL_TRIANGLES, 0, gLightMesh.nVertices);
//----------------------
// AMBIENT LIGHT:
// DRAW AMBIENT LIGHT - CUBE SHAPE
//----------------------
// Activate the cube VAO (used by cube and lamp)
glBindVertexArray(gAmbMesh.vao);
// Set the shader to be used
glUseProgram(gLampProgramId);
//Transform the smaller cube used as a visual que for the light source
model = glm::translate(gAmbLightPosition) * glm::scale(gAmbLightScale);
// Reference matrix uniforms from the Lamp Shader program
modelLoc = glGetUniformLocation(gLampProgramId, "model");
viewLoc = glGetUniformLocation(gLampProgramId, "view");
projLoc = glGetUniformLocation(gLampProgramId, "projection");
// Pass matrix data to the Lamp Shader program's matrix uniforms
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
glDrawArrays(GL_TRIANGLES, 0, gAmbMesh.nVertices);
//----------------------
// TABLE TOP:
// DRAW TABLE - PLANE SHAPE
//----------------------
// Activate the table VAO
glBindVertexArray(gTableMesh.vao);
// Set the shader to be used
glUseProgram(gProgramId);
//Set scale, rotation, and translation
translation = glm::translate(glm::vec3(0.0f, 0.0f, 0.0f)); //Move
scale = glm::scale(glm::vec3(9.0f, 1.0f, 10.0f)); //Scale
model = translation * scale; //Creates transform matrix
// Retrieves and passes transform matrices to the Shader program
modelLoc = glGetUniformLocation(gProgramId, "model");
viewLoc = glGetUniformLocation(gProgramId, "view");
projLoc = glGetUniformLocation(gProgramId, "projection");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
//REFERENCE MATRIX UNIFORMS
//----------------
//Object
GLint objectColorLoc = glGetUniformLocation(gProgramId, "objectColor");
//Spotlight
GLint lightColorLoc = glGetUniformLocation(gProgramId, "lightColor");
GLint lightPositionLoc = glGetUniformLocation(gProgramId, "lightPos");
//Ambient Light
GLint ambientLightColorLoc = glGetUniformLocation(gProgramId, "ambientLightColor");
GLint ambientLightPositionLoc = glGetUniformLocation(gProgramId, "ambientLightPos");
//Camera
GLint viewPositionLoc = glGetUniformLocation(gProgramId, "viewPosition");
GLint ambViewPositionLoc = glGetUniformLocation(gProgramId, "ambViewPosition");
//Pass color, light, and camera data to the Cube Shader program's corresponding uniforms
//----------------
//Object
glUniform3f(objectColorLoc, gObjectColor.r, gObjectColor.g, gObjectColor.b);
//Spotlight
glUniform3f(lightColorLoc, gLightColor.r, gLightColor.g, gLightColor.b);
glUniform3f(lightPositionLoc, gLightPosition.x, gLightPosition.y, gLightPosition.z);
//Ambient Light
glUniform3f(ambientLightColorLoc, gAmbLightColor.r, gAmbLightColor.g, gAmbLightColor.b);
glUniform3f(ambientLightPositionLoc, gAmbLightPosition.x, gAmbLightPosition.y, gAmbLightPosition.z);
//Camera
glUniform3f(viewPositionLoc, cameraPosition.x, cameraPosition.y, cameraPosition.z);
glUniform3f(ambViewPositionLoc, cameraPosition.x, cameraPosition.y, cameraPosition.z);
//TEXTURES
//----------------
//Texture scale
uvScale = glm::vec2(1.0f, 1.0f);
GLint UVScaleLoc = glGetUniformLocation(gProgramId, "uvScale");
glUniform2fv(UVScaleLoc, 1, glm::value_ptr(uvScale));
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gTableTextureId);
// Draws the triangles
glDrawElements(GL_TRIANGLES, gTableMesh.nVertices, GL_UNSIGNED_SHORT, NULL);
//glDrawArrays(GL_TRIANGLES, 0, gTableMesh.nVertices);
//----------------------
// BOOK:
// DRAW BOOK - CUBE SHAPE
//----------------------
// Activate the book VAO
glBindVertexArray(gBookMesh.vao);
// Set the shader to be used
glUseProgram(gProgramId);
//Set scale, rotation, and translation
translation = glm::translate(glm::vec3(-7.0f, 2.1f, -2.5f)); //Move
rotation = glm::rotate(glm::radians(15.0f), glm::vec3(0.0f, 0.5f, 0.0f)); //Rotate
scale = glm::scale(glm::vec3(15.f, 2.f, 10.f)); //Scale
model = translation * rotation * scale; //Creates transform matrix
// Retrieves and passes transform matrices to the Shader program
modelLoc = glGetUniformLocation(gProgramId, "model");
viewLoc = glGetUniformLocation(gProgramId, "view");
projLoc = glGetUniformLocation(gProgramId, "projection");
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
//REFERENCE MATRIX UNIFORMS
//----------------
//Object
objectColorLoc = glGetUniformLocation(gProgramId, "objectColor");
//Spotlight
lightColorLoc = glGetUniformLocation(gProgramId, "lightColor");
lightPositionLoc = glGetUniformLocation(gProgramId, "lightPos");
//Ambient Light
ambientLightColorLoc = glGetUniformLocation(gProgramId, "ambientLightColor");
ambientLightPositionLoc = glGetUniformLocation(gProgramId, "ambientLightPos");
//Camera
viewPositionLoc = glGetUniformLocation(gProgramId, "viewPosition");
ambViewPositionLoc = glGetUniformLocation(gProgramId, "ambViewPosition");
//Pass color, light, and camera data to the Cube Shader program's corresponding uniforms
//----------------
//Object
glUniform3f(objectColorLoc, gObjectColor.r, gObjectColor.g, gObjectColor.b);
//Spotlight
glUniform3f(lightColorLoc, gLightColor.r, gLightColor.g, gLightColor.b);
glUniform3f(lightPositionLoc, gLightPosition.x, gLightPosition.y, gLightPosition.z);
//Ambient Light
glUniform3f(ambientLightColorLoc, gAmbLightColor.r, gAmbLightColor.g, gAmbLightColor.b);
glUniform3f(ambientLightPositionLoc, gAmbLightPosition.x, gAmbLightPosition.y, gAmbLightPosition.z);
//Camera
glUniform3f(viewPositionLoc, cameraPosition.x, cameraPosition.y, cameraPosition.z);
glUniform3f(ambViewPositionLoc, cameraPosition.x, cameraPosition.y, cameraPosition.z);