-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1088 lines (874 loc) · 30.4 KB
/
main.cpp
File metadata and controls
1088 lines (874 loc) · 30.4 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
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
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
#include <GL/glew.h>
//#include <OpenGL/gl3.h> // The GL Header File
#include <GLFW/glfw3.h> // The GLFW header
#include <glm/glm.hpp> // GL Math library header
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <map>
#include <ft2build.h>
#include FT_FREETYPE_H
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define BUFFER_OFFSET(i) ((char*)NULL + (i))
using namespace std;
GLuint vao[3];
GLuint gProgram[3];
unsigned int texture;
GLuint mySampler;
int gWidth = 640, gHeight = 480;
bool changeView = false;
bool rotate = true;
double xpos;
double ypos;
double xpos_prev=-1;
double ypos_prev=-1;
#define SCALE_ROT 1
#define MAX_EXPOSURE 10.0
#define MIN_EXPOSURE 0.1
#define SCALE_EXPOSURE 4.0
#define EXPOSURE_STEP 0.1
GLfloat exposure=4.0;
float gammaCorr = 2.2;
bool vsync = true;
enum mode{
TONEMAPPED,
CUBE_ONLY,
MODEL_WORLD_POS,
MODEL_WORLD_NOR,
DEFERRED_LIGHTING,
COMPOSITE,
COMPOSITE_AND_MB
};
mode currMode;
GLint gammaCorrLoc[2];
GLint currModeLoc[2];
GLint modelingMatrixLoc[2];
GLint viewingMatrixLoc[2];
GLint projectionMatrixLoc[2];
GLint eyePosLoc[2];
GLint lightPosLoc[2];
GLint exposureLoc[2];
glm::mat4 projectionMatrix;
glm::mat4 viewingMatrix;
glm::mat4 modelingMatrix;
glm::mat4 modelingMatrix_quad;
glm::mat4 viewingMatrix_quad;
bool initModelingMatrix_quad = false;
glm::vec3 eyePos(0, 0, 0);
glm::vec3 lightPosInit(10,7, 10);
glm::vec3 lightPos(0, 0, -8);
glm::vec3 eyeGaze(0, 0, -1);
glm::vec3 eyeUp(0, 1, 0);
/// Holds all state information relevant to a character as loaded using FreeType
struct Character {
GLuint TextureID; // ID handle of the glyph texture
glm::ivec2 Size; // Size of glyph
glm::ivec2 Bearing; // Offset from baseline to left/top of glyph
GLuint Advance; // Horizontal offset to advance to next glyph
};
std::map<GLchar, Character> Characters;
struct Vertex
{
Vertex(GLfloat inX, GLfloat inY, GLfloat inZ) : x(inX), y(inY), z(inZ) {}
GLfloat x, y, z;
Vertex operator+(const Vertex& other) const {
return Vertex(x + other.x, y + other.y, z + other.z);
}
Vertex operator-(const Vertex& other) const {
return Vertex(x - other.x, y - other.y, z - other.z);
}
Vertex operator*(GLfloat scalar) const {
return Vertex(x * scalar, y * scalar, z * scalar);
}
friend Vertex operator*(GLfloat scalar, const Vertex& v) {
return Vertex(v.x * scalar, v.y * scalar, v.z * scalar);
}
friend Vertex operator/(const Vertex& v,GLfloat scalar) {
return Vertex(v.x / scalar, v.y / scalar, v.z / scalar);
}
GLfloat dot_product(const Vertex& other) const {
return x * other.x + y * other.y + z * other.z;
}
Vertex cross_product(const Vertex& other) const {
return Vertex(
y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
);
}
GLfloat mag(){
return sqrt(x*x+y*y+z*z);
}
};
struct Texture
{
Texture(GLfloat inU, GLfloat inV) : u(inU), v(inV) {}
GLfloat u, v;
};
struct Normal
{
Normal(GLfloat inX, GLfloat inY, GLfloat inZ) : x(inX), y(inY), z(inZ) {}
GLfloat x, y, z;
Normal operator+(const Normal& other) const {
return Normal(x + other.x, y + other.y, z + other.z);
}
Normal operator-(const Normal& other) const {
return Normal(x - other.x, y - other.y, z - other.z);
}
Normal operator*(GLfloat scalar) const {
return Normal(x * scalar, y * scalar, z * scalar);
}
friend Normal operator*(GLfloat scalar, const Normal& v) {
return Normal(v.x * scalar, v.y * scalar, v.z * scalar);
}
friend Normal operator/(const Normal& v,GLfloat scalar) {
return Normal(v.x / scalar, v.y / scalar, v.z / scalar);
}
GLfloat dot_product(const Normal& other) const {
return x * other.x + y * other.y + z * other.z;
}
Normal cross_product(const Normal& other) const {
return Normal(
y * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
);
}
int mag(){
return sqrt(x*x+y*y+z*z);
}
};
struct Face
{
Face(int v[], int t[], int n[]) {
vIndex[0] = v[0];
vIndex[1] = v[1];
vIndex[2] = v[2];
tIndex[0] = t[0];
tIndex[1] = t[1];
tIndex[2] = t[2];
nIndex[0] = n[0];
nIndex[1] = n[1];
nIndex[2] = n[2];
}
GLuint vIndex[3], tIndex[3], nIndex[3];
};
vector<Vertex> gVertices[2];
vector<Texture> gTextures[2];
vector<Normal> gNormals[2];
vector<Face> gFaces[2];
GLuint gVertexAttribBuffer[2], gIndexBuffer[2], gTextVBO;
GLint gInVertexLoc[2], gInNormalLoc[2];
int gVertexDataSizeInBytes[2], gNormalDataSizeInBytes[2], gTextureDataSizeInBytes[2];
bool ParseObj(const string& fileName, int objId)
{
fstream myfile;
// Open the input
myfile.open(fileName.c_str(), std::ios::in);
if (myfile.is_open())
{
string curLine;
while (getline(myfile, curLine))
{
stringstream str(curLine);
GLfloat c1, c2, c3;
GLuint index[9];
string tmp;
if (curLine.length() >= 2)
{
if (curLine[0] == 'v')
{
if (curLine[1] == 't') // texture
{
str >> tmp; // consume "vt"
str >> c1 >> c2;
gTextures[objId].push_back(Texture(c1, c2));
}
else if (curLine[1] == 'n') // normal
{
str >> tmp; // consume "vn"
str >> c1 >> c2 >> c3;
gNormals[objId].push_back(Normal(c1, c2, c3));
}
else // vertex
{
str >> tmp; // consume "v"
str >> c1 >> c2 >> c3;
gVertices[objId].push_back(Vertex(c1, c2, c3));
}
}
else if (curLine[0] == 'f') // face
{
str >> tmp; // consume "f"
char c;
int vIndex[3], nIndex[3], tIndex[3];
str >> vIndex[0]; str >> c >> c; // consume "//"
str >> nIndex[0];
str >> vIndex[1]; str >> c >> c; // consume "//"
str >> nIndex[1];
str >> vIndex[2]; str >> c >> c; // consume "//"
str >> nIndex[2];
assert(vIndex[0] == nIndex[0] &&
vIndex[1] == nIndex[1] &&
vIndex[2] == nIndex[2]); // a limitation for now
// make indices start from 0
for (int c = 0; c < 3; ++c)
{
vIndex[c] -= 1;
nIndex[c] -= 1;
tIndex[c] -= 1;
}
gFaces[objId].push_back(Face(vIndex, tIndex, nIndex));
}
else
{
cout << "Ignoring unidentified line in obj file: " << curLine << endl;
}
}
//data += curLine;
if (!myfile.eof())
{
//data += "\n";
}
}
myfile.close();
}
else
{
return false;
}
std::cout << "gVertices[objId].size():" << gVertices[objId].size() << std::endl;
assert(gVertices[objId].size() == gNormals[objId].size());
return true;
}
bool ReadDataFromFile(
const string& fileName, ///< [in] Name of the shader file
string& data) ///< [out] The contents of the file
{
fstream myfile;
// Open the input
myfile.open(fileName.c_str(), std::ios::in);
if (myfile.is_open())
{
string curLine;
while (getline(myfile, curLine))
{
data += curLine;
if (!myfile.eof())
{
data += "\n";
}
}
myfile.close();
}
else
{
return false;
}
return true;
}
GLuint createVS(const char* shaderName)
{
string shaderSource;
string filename(shaderName);
if (!ReadDataFromFile(filename, shaderSource))
{
cout << "Cannot find file name: " + filename << endl;
exit(-1);
}
GLint length = shaderSource.length();
const GLchar* shader = (const GLchar*)shaderSource.c_str();
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &shader, &length);
glCompileShader(vs);
char output[1024] = { 0 };
glGetShaderInfoLog(vs, 1024, &length, output);
printf("VS compile log: %s\n", output);
return vs;
}
GLuint createFS(const char* shaderName)
{
string shaderSource;
string filename(shaderName);
if (!ReadDataFromFile(filename, shaderSource))
{
cout << "Cannot find file name: " + filename << endl;
exit(-1);
}
GLint length = shaderSource.length();
const GLchar* shader = (const GLchar*)shaderSource.c_str();
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &shader, &length);
glCompileShader(fs);
char output[1024] = { 0 };
glGetShaderInfoLog(fs, 1024, &length, output);
printf("FS compile log: %s\n", output);
return fs;
}
void initFonts(int windowWidth, int windowHeight)
{
// Set OpenGL options
//glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
std::cout << "windowWidth = " << windowWidth << std::endl;
std::cout << "windowHeight = " << windowHeight << std::endl;
glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(windowWidth), 0.0f, static_cast<GLfloat>(windowHeight));
glUseProgram(gProgram[2]);
glUniformMatrix4fv(glGetUniformLocation(gProgram[2], "projection"), 1, GL_FALSE, glm::value_ptr(projection));
// FreeType
FT_Library ft;
// All functions return a value different than 0 whenever an error occurred
if (FT_Init_FreeType(&ft))
{
std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl;
}
// Load font as face
FT_Face face;
if (FT_New_Face(ft, "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", 0, &face))
//if (FT_New_Face(ft, "/usr/share/fonts/truetype/gentium-basic/GenBkBasR.ttf", 0, &face))
{
std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl;
}
// Set size to load glyphs as
FT_Set_Pixel_Sizes(face, 0, 48);
// Disable byte-alignment restriction
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Load first 128 characters of ASCII set
for (GLubyte c = 0; c < 128; c++)
{
// Load character glyph
if (FT_Load_Char(face, c, FT_LOAD_RENDER))
{
std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
continue;
}
// Generate texture
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
face->glyph->bitmap.width,
face->glyph->bitmap.rows,
0,
GL_RED,
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer
);
// Set texture options
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Now store character for later use
Character character = {
texture,
glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
(GLuint) face->glyph->advance.x
};
Characters.insert(std::pair<GLchar, Character>(c, character));
}
glBindTexture(GL_TEXTURE_2D, 0);
// Destroy FreeType once we're finished
FT_Done_Face(face);
FT_Done_FreeType(ft);
//
// Configure VBO for texture quads
//
GLuint vaoLocal, vbo;
glGenVertexArrays(1, &vaoLocal);
assert(vaoLocal > 0);
vao[2] = vaoLocal;
glBindVertexArray(vaoLocal);
glGenBuffers(1, &gTextVBO);
glBindBuffer(GL_ARRAY_BUFFER, gTextVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void initCubemap(){
glGenTextures(1,&texture);
//glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
const char* images[] = {"cubemap/px.hdr",
"cubemap/nx.hdr",
"cubemap/py.hdr",
"cubemap/ny.hdr",
"cubemap/pz.hdr",
"cubemap/nz.hdr"};
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for (int i=0; i<6; ++i){
int w,h, nrChannels;
float* data = stbi_loadf(images[i], &w, &h, &nrChannels,3);
if(data){
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,
GL_RGB32F, w,h,0,
GL_RGB, GL_FLOAT, data);
stbi_set_flip_vertically_on_load(false);
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
glGenSamplers(1,&mySampler);
glBindSampler(0,mySampler);
}
GLuint fs1=0;
void bindShader(std::string filename_vert,std::string filename_frag, int programId){
fs1 = createFS(filename_frag.c_str());
glAttachShader(gProgram[programId], fs1);
GLuint vs1 = createVS(filename_vert.c_str());
glAttachShader(gProgram[programId], vs1);
glLinkProgram(gProgram[programId]);
GLint status;
glGetProgramiv(gProgram[programId], GL_LINK_STATUS, &status);
if (status != GL_TRUE)
{
cout << "Program link failed for " << programId << endl;
exit(-1);
}
}
void initShaders()
{
// Create the programs
gProgram[0] = glCreateProgram(); //for armadillo
gProgram[1] = glCreateProgram(); //for background quad
gProgram[2] = glCreateProgram(); //for text rendering
// Create the shaders for both programs
bindShader("vert.glsl","frag.glsl",0); //for armadillo
bindShader("vert_quad.glsl","frag_quad.glsl",1); //for background quad
bindShader("vert_text.glsl","frag_text.glsl",2); //for text
// Link the programs
// Get the locations of the uniform variables from both programs
for (int i = 0; i < 2; ++i)
{
glUseProgram(gProgram[i]);
exposureLoc[i] = glGetUniformLocation(gProgram[i], "exposure");
modelingMatrixLoc[i] = glGetUniformLocation(gProgram[i], "modelingMatrix");
viewingMatrixLoc[i] = glGetUniformLocation(gProgram[i], "viewingMatrix");
projectionMatrixLoc[i] = glGetUniformLocation(gProgram[i], "projectionMatrix");
eyePosLoc[i] = glGetUniformLocation(gProgram[i], "eyePos");
lightPosLoc[i] = glGetUniformLocation(gProgram[i], "lightPos");
currModeLoc[i] = glGetUniformLocation(gProgram[i], "currMode");
gammaCorrLoc[i] = glGetUniformLocation(gProgram[i],"gammaCorr");
}
}
void initVBO()
{
for (size_t t = 0; t < 2; t++) // 2 objects. t=0 is armadillo, t=1 is background quad.
{
glGenVertexArrays(1, &vao[t]);
assert(vao[t] > 0);
glBindVertexArray(vao[t]);
cout << "vao = " << vao[t] << endl;
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
assert(glGetError() == GL_NONE);
glGenBuffers(1, &gVertexAttribBuffer[t]);
glGenBuffers(1, &gIndexBuffer[t]);
assert(gVertexAttribBuffer[t] > 0 && gIndexBuffer[t] > 0);
glBindBuffer(GL_ARRAY_BUFFER, gVertexAttribBuffer[t]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gIndexBuffer[t]);
gVertexDataSizeInBytes[t] = gVertices[t].size() * 3 * sizeof(GLfloat);
gNormalDataSizeInBytes[t] = gNormals[t].size() * 3 * sizeof(GLfloat);
gTextureDataSizeInBytes[t] = gTextures[t].size() * 2 * sizeof(GLfloat);
int indexDataSizeInBytes = gFaces[t].size() * 3 * sizeof(GLuint);
GLfloat* vertexData = new GLfloat[gVertices[t].size() * 3];
GLfloat* normalData = new GLfloat[gNormals[t].size() * 3];
GLfloat* textureData = new GLfloat[gTextures[t].size() * 2];
GLuint* indexData = new GLuint[gFaces[t].size() * 3];
float minX = 1e6, maxX = -1e6;
float minY = 1e6, maxY = -1e6;
float minZ = 1e6, maxZ = -1e6;
for (int i = 0; i < gVertices[t].size(); ++i)
{
vertexData[3 * i] = gVertices[t][i].x;
vertexData[3 * i + 1] = gVertices[t][i].y;
vertexData[3 * i + 2] = gVertices[t][i].z;
minX = std::min(minX, gVertices[t][i].x);
maxX = std::max(maxX, gVertices[t][i].x);
minY = std::min(minY, gVertices[t][i].y);
maxY = std::max(maxY, gVertices[t][i].y);
minZ = std::min(minZ, gVertices[t][i].z);
maxZ = std::max(maxZ, gVertices[t][i].z);
}
std::cout << "minX = " << minX << std::endl;
std::cout << "maxX = " << maxX << std::endl;
std::cout << "minY = " << minY << std::endl;
std::cout << "maxY = " << maxY << std::endl;
std::cout << "minZ = " << minZ << std::endl;
std::cout << "maxZ = " << maxZ << std::endl;
for (int i = 0; i < gNormals[t].size(); ++i)
{
normalData[3 * i] = gNormals[t][i].x;
normalData[3 * i + 1] = gNormals[t][i].y;
normalData[3 * i + 2] = gNormals[t][i].z;
}
for (int i = 0; i < gTextures[t].size(); ++i)
{
textureData[2 * i] = gTextures[t][i].u;
textureData[2 * i + 1] = gTextures[t][i].v;
}
for (int i = 0; i < gFaces[t].size(); ++i)
{
indexData[3 * i] = gFaces[t][i].vIndex[0];
indexData[3 * i + 1] = gFaces[t][i].vIndex[1];
indexData[3 * i + 2] = gFaces[t][i].vIndex[2];
}
glBufferData(GL_ARRAY_BUFFER, gVertexDataSizeInBytes[t] + gNormalDataSizeInBytes[t] + gTextureDataSizeInBytes[t], 0, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, gVertexDataSizeInBytes[t], vertexData);
glBufferSubData(GL_ARRAY_BUFFER, gVertexDataSizeInBytes[t], gNormalDataSizeInBytes[t], normalData);
glBufferSubData(GL_ARRAY_BUFFER, gVertexDataSizeInBytes[t] + gNormalDataSizeInBytes[t], gTextureDataSizeInBytes[t], textureData);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexDataSizeInBytes, indexData, GL_STATIC_DRAW);
// done copying; can free now
delete[] vertexData;
delete[] normalData;
delete[] textureData;
delete[] indexData;
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(gVertexDataSizeInBytes[t]));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(gVertexDataSizeInBytes[t] + gNormalDataSizeInBytes[t]));
}
}
void init()
{
ParseObj("armadillo.obj", 0);
ParseObj("quad.obj", 1);
glEnable(GL_DEPTH_TEST);
//initTexture();
initCubemap();
initShaders();
initVBO();
//initFonts(gWidth, gHeight);
}
void renderText(const std::string& text, GLfloat x, GLfloat y, GLfloat scale, glm::vec3 color)
{
// Activate corresponding render state
glUseProgram(gProgram[2]);
glUniform3f(glGetUniformLocation(gProgram[2], "textColor"), color.x, color.y, color.z);
glActiveTexture(GL_TEXTURE0);
// Iterate through all characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character ch = Characters[*c];
GLfloat xpos = x + ch.Bearing.x * scale;
GLfloat ypos = y - (ch.Size.y - ch.Bearing.y) * scale;
GLfloat w = ch.Size.x * scale;
GLfloat h = ch.Size.y * scale;
// Update VBO for each character
GLfloat vertices[6][4] = {
{ xpos, ypos + h, 0.0, 0.0 },
{ xpos, ypos, 0.0, 1.0 },
{ xpos + w, ypos, 1.0, 1.0 },
{ xpos, ypos + h, 0.0, 0.0 },
{ xpos + w, ypos, 1.0, 1.0 },
{ xpos + w, ypos + h, 1.0, 0.0 }
};
// Render glyph texture over quad
glBindTexture(GL_TEXTURE_2D, ch.TextureID);
glBindVertexArray(vao[2]);
// Update content of VBO memory
glBindBuffer(GL_ARRAY_BUFFER, gTextVBO);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); // Be sure to use glBufferSubData and not glBufferData
//glBindBuffer(GL_ARRAY_BUFFER, 0);
// Render quad
glDrawArrays(GL_TRIANGLES, 0, 6);
// Now advance cursors for next glyph (note that advance is number of 1/64 pixels)
x += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64 (divide amount of 1/64th pixels by 64 to get amount of pixels))
}
glBindTexture(GL_TEXTURE_2D, 0);
}
void drawScene()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
for (size_t t = 0; t < 2; t++)
{
// Set the active program and the values of its uniform variables
if(t==0 && currMode== CUBE_ONLY) continue;
if(t==1 && (currMode!= CUBE_ONLY) && (currMode!= TONEMAPPED) && (currMode!= COMPOSITE) ) continue;
glUseProgram(gProgram[t]);
glUniformMatrix4fv(projectionMatrixLoc[t], 1, GL_FALSE, glm::value_ptr(projectionMatrix));
glUniformMatrix4fv(viewingMatrixLoc[t], 1, GL_FALSE, glm::value_ptr(viewingMatrix));
glUniform1i(currModeLoc[t], currMode);
if(t!=1) { glUniformMatrix4fv(modelingMatrixLoc[t], 1, GL_FALSE, glm::value_ptr(modelingMatrix));
glUniform1f(exposureLoc[t],exposure/SCALE_EXPOSURE);
}
else { glUniformMatrix4fv(modelingMatrixLoc[t], 1, GL_FALSE, glm::value_ptr(modelingMatrix_quad));
glUniform1f(exposureLoc[t],exposure);
}
glUniform1f(gammaCorrLoc[t], gammaCorr);
glUniform3fv(eyePosLoc[t], 1, glm::value_ptr(eyePos));
glUniform3fv(lightPosLoc[t], 1, glm::value_ptr(lightPos));
glBindVertexArray(vao[t]);
if (t == 1) {
glDisable(GL_CULL_FACE);
glDepthMask(GL_FALSE);
glDepthFunc(GL_LEQUAL);
}
glDrawElements(GL_TRIANGLES, gFaces[t].size() * 3, GL_UNSIGNED_INT, 0);
if (t == 1) {
glEnable(GL_CULL_FACE);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
}
}
}
void writeText(){
// render the text
std::string exposureText = "exposure = " + std::to_string(exposure);
std::string vsyncText = "vsync = " + std::to_string(vsync);
//std::string motionBlurText = "motionblur = " + std::to_string(motionBlur);
//std::string keyText = "key = " + std::to_string(key);
std::string gammaCorrText = "gamma = " + std::to_string(gammaCorr);
// std::string fpsText = "FPS: " + std::to_string(fps);
glDisable(GL_DEPTH_TEST);
renderText("Test", 0, gHeight - 25, 0.6, glm::vec3(1, 1, 0));
// values
renderText(exposureText, 0, gHeight - 25, 0.6, glm::vec3(1, 1, 0));
// modes
int modeTextHeight = gHeight - 25;
int modeTextWidth = 0.6;
glm::vec3 textVec = glm::vec3(1, 1, 0);
if(currMode == TONEMAPPED) renderText("TONEMAPPED", 0, modeTextHeight, modeTextWidth, textVec);
else if(currMode == CUBE_ONLY) renderText("CUBE_ONLY", 0, modeTextHeight, modeTextWidth, textVec);
else if(currMode == MODEL_WORLD_POS) renderText("MODEL_WORLD_POS", 0, modeTextHeight, modeTextWidth, textVec);
else if(currMode == MODEL_WORLD_NOR) renderText("MODEL_WORLD_NOR", 0, modeTextHeight, modeTextWidth, textVec);
else if(currMode == DEFERRED_LIGHTING) renderText("MODEL_WORLD_NOR", 0, modeTextHeight, modeTextWidth, textVec);
else if(currMode == COMPOSITE) renderText("MODEL_WORLD_NOR", 0, modeTextHeight, modeTextWidth,textVec);
glEnable(GL_DEPTH_TEST);
}
GLfloat getFPS(){
static struct timespec prevTime;
static int initialized = 0;
struct timespec currTime;
clock_gettime(CLOCK_MONOTONIC, &currTime);
if (!initialized) {
prevTime = currTime;
initialized = 1;
return 0.0f; // No FPS yet
}
double elapsed = (currTime.tv_sec - prevTime.tv_sec) +
(currTime.tv_nsec - prevTime.tv_nsec) / 1e9;
prevTime = currTime;
if (elapsed > 0.0)
return 1.0f / elapsed;
else
return 0.0f;
}
void display(GLFWwindow *window)
{
glClearColor(0, 0, 0, 1);
glClearDepth(1.0f);
glClearStencil(0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// Compute the modeling matrix
glm::mat4 matT = glm::translate(glm::mat4(1.0), glm::vec3(-0.0f, -0.3f, -3.0f));
modelingMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f));
// Let's make some pitch rotation
static float pitchDeg = 0;
static float changePitch = 1;
float pitchRad = (float)(pitchDeg / 180.f) * M_PI;
if(rotate) pitchDeg += changePitch;
glm::quat pitchQuat(cos(pitchRad / 2), 0, 1 * sin(pitchRad / 2), 0);
modelingMatrix = matT * glm::toMat4(pitchQuat);
if(changeView){
xpos_prev = xpos;
ypos_prev = ypos;
glfwGetCursorPos(window, &xpos, &ypos);
// gotta change the viewing matrix here
// xpos ve ypos var elimizde
int windowWidth, windowHeight;
glfwGetFramebufferSize(window, &windowWidth, &windowHeight);
GLfloat rotx = -(((GLfloat) xpos-xpos_prev)/windowWidth ) * M_PI / SCALE_ROT;
GLfloat roty = -((GLfloat) ypos-ypos_prev)/windowHeight * M_PI/ SCALE_ROT;
glm::vec3 right = glm::normalize(glm::cross(eyeGaze, eyeUp));
glm::quat viewX = glm::angleAxis(rotx, eyeUp);
glm::quat viewY = glm::angleAxis(roty, right);
glm::quat viewQuat = viewY * viewX;
eyeGaze = glm::normalize(viewQuat * eyeGaze);
eyeUp = glm::normalize(viewQuat * eyeUp);
right = glm::normalize(glm::cross(eyeGaze, eyeUp));
eyeUp = glm::normalize(glm::cross(right, eyeGaze));
viewingMatrix = glm::lookAt(eyePos, eyePos + eyeGaze, eyeUp);
//lightPos = glm::vec3(modelingMatrix * glm::vec4(lightPos,1.0f));
}
// Draw the scene
if(!initModelingMatrix_quad){
modelingMatrix_quad = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f));
initModelingMatrix_quad = true;
//lightPos = glm::vec3(modelingMatrix_quad * glm::vec4(lightPos, 1));
}
lightPos= glm::vec3( viewingMatrix * modelingMatrix_quad * glm::vec4(lightPosInit, 1));
drawScene();
writeText();
}
void reshape(GLFWwindow* window, int w, int h)
{
w = w < 1 ? 1 : w;
h = h < 1 ? 1 : h;
gWidth = w;
gHeight = h;
glViewport(0, 0, w, h);
//glMatrixMode(GL_PROJECTION);
//glLoadIdentity();
//glOrtho(-10, 10, -10, 10, -10, 10);
//gluPerspective(45, 1, 1, 100);
// Use perspective projection
float fovyRad = (float)(90.0 / 180.0) * M_PI;
projectionMatrix = glm::perspective(fovyRad, 1.0f, 1.0f, 1000.0f);
// Assume a camera position and orientation (camera is at
// (0, 0, 0) with looking at -z direction and its up vector pointing
// at +y direction)
viewingMatrix = glm::lookAt(eyePos, eyePos + eyeGaze, eyeUp);
//glMatrixMode(GL_MODELVIEW);
//glLoadIdentity();
}
///////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////// KEYBOARD & MOUSE /////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
void keyboard(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_Q && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
else if (key == GLFW_KEY_KP_ADD && action == GLFW_PRESS)
{
if(exposure < MAX_EXPOSURE) exposure += EXPOSURE_STEP;
std::cout << "Exposure: " << exposure << std::endl;
}
else if (key == GLFW_KEY_KP_SUBTRACT && action == GLFW_PRESS)
{
if(exposure > MIN_EXPOSURE) exposure -= EXPOSURE_STEP;
std::cout << "Exposure: " << exposure << std::endl;
}
else if (key == GLFW_KEY_0 && action == GLFW_PRESS)
{
currMode = TONEMAPPED;
}
else if (key == GLFW_KEY_R && action == GLFW_PRESS)
{
rotate = !rotate;
}
else if (key == GLFW_KEY_1 && action == GLFW_PRESS)
{
currMode = CUBE_ONLY;
}
else if (key == GLFW_KEY_2 && action == GLFW_PRESS)
{
currMode = MODEL_WORLD_POS;
}
else if (key == GLFW_KEY_3 && action == GLFW_PRESS)
{
currMode = MODEL_WORLD_NOR;
}
else if (key == GLFW_KEY_4 && action == GLFW_PRESS)
{
currMode = DEFERRED_LIGHTING;
}
else if (key == GLFW_KEY_5 && action == GLFW_PRESS)
{
currMode = COMPOSITE;
}
else if (key == GLFW_KEY_G && action == GLFW_PRESS)
{
if(gammaCorr==1.0) gammaCorr = 2.2;
else gammaCorr = 1.0;
}