forked from mezox/Efficient-Computation-of-Lighting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ECL.cpp
1520 lines (1200 loc) · 41.1 KB
/
ECL.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
/*
Project: Efficient computation of Lighting
Type: Bachelor's thesis
Author: Tomáš Kubovčík, [email protected]
Supervisor: Ing. Tomáš Milet
School info: Brno Univeristy of Technology (VUT)
Faculty of Information Technology (FIT)
Department of Computer Graphics and Multimedia (UPGM)
Project information
---------------------
The goal of this project is to efficiently compute lighting in scenes
with hundrends to thousands light sources. To handle this there have been
implemented lighting techniques as deferred shading, tiled deferred shading
and tiled forward shading. Application requires GPU supporting OpenGL 3.3+
but may be compatible with older versions. Application logic was implemented
using C/C++ with some external helper libraries to handle basic operations.
File information
-----------------
This file represents main source code file containing function main().
Basically whole important application logic is implemented in this file.
*/
//external
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <GL/freeglut.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <external\AntTweakBar\AntTweakBar.h>
//standard C++ libraries
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <cmath>
#include <string>
#include <locale>
#include <vector>
#include <direct.h>
#include <sstream>
#include "shaders\ShaderProgram.h"
#include "scene\camera\Camera.h"
#include "scene\objloader\Mesh.h"
#include "lighting\lights\PointLight.h"
#include "buffers\g-buffer\Gbuffer.h"
//modules
#include "utils\Utils.h"
#include "lighting\tiled\Grid.h"
#include "buffers\ubo\buffer.h"
#include "configuration\Types.h"
#include "configuration\Enums.h"
#include "utils\timers\PerformanceTimer.h"
// GLOBAL VARIABLES
#pragma region GLOBAL_VARIABLES
std::string windowTitle = "Efficient Computation of Lighting: ";
VENDOR GPUVendor = AMD;
static Matrices transformationMatrices;
static unsigned int technique = AMD_TiledDeferred;
double mouseXold, mouseYold;
unsigned int LIGHT_COUNT = 0;
//lights
Lights pointLights;
double start_time = 0.0f;
bool decFlag = true;
#pragma region Feature_Settings
bool showMRTQuads = false;
bool showBoundingQuads = false;
bool showAffectedTiles = false;
bool showLightHeatMap = false;
bool minMaxPass = true;
#pragma endregion Feature_Settings
#pragma region Performance_Outputs
std::vector<double> fpsVector;
std::vector<double> lightingTime;
std::vector<double> minmaxTime;
std::vector<double> gridTime;
#pragma endregion Performance_Outputs
#pragma region Shader_Programs
shprogram * mrt = NULL;
shprogram * deferredShader = NULL;
shprogram * quadShader = NULL;
shprogram * quadDShader = NULL;
shprogram * minMaxDepthShader = NULL;
shprogram * simpleShader = NULL;
shprogram * tiledDeferredShader = NULL;
shprogram * tiledForwardShader = NULL;
shprogram * lightHeatMapShader = NULL;
shprogram * affectedTilesShader = NULL;
#pragma endregion Shader_Programs
unsigned int lastLightCnt = MAX_LIGHTS;
bool showGBufferQuad[GBuffer::GBUFFER_NUM_TEXTURES] = {false};
bool showDepth = false;
//move position of camera based on WASD keys, and XZ keys for up and down
float moveSpeed = 400.0; //units per second
//camera object
Camera gCamera;
//application window
GLFWwindow * win = NULL;
//meshes
Mesh * m_pMesh = NULL; //scene
Mesh * m_sphere = NULL; //pointlight sphere
//gBuffer object
GBuffer *gBuf = new GBuffer();
//gbuffer textures
GLuint gBufTexIndex = 4;
//VBOs
GLuint quadVBO;
//models of point lights for deferred shading
glm::mat4 lightSpheres[MAX_LIGHTS];
LightGrid lightgrid;
#pragma region Framebuffers
GLuint minMaxDepthFbo; //minMax downsample framebuffer
GLuint forwardFbo; //forward framebuffer
#pragma endregion Framebuffers
#pragma region Queries
GLuint minMaxDepthQuery;
GLuint minMaxDepthQueryTime = 0;
GLuint lightingQuery;
GLuint lightingQueryTime;
#pragma endregion Queries
#pragma region Textures
GLuint gTexDiffuse, gTexNormal, gTexPos, gTexDepth, gTexSpec, gTexAmbient, depthTex; // G-Buffer Textures
GLuint forwardTex;
GLuint minMaxDepthTex;
GLuint lightIDtex = 0; //LightIDs texture for tiled shading
#pragma endregion Textures
#pragma region Unifom_Buffer_Objects
GlBufferObject<int> lightIndicesBuffer;
GlBufferObject<glm::ivec4> countsAndOffsetsBuffer;
GlBufferObject<glm::vec4> posAndRadiusesBuffer;
GlBufferObject<glm::vec4> colorsBuffer;
#pragma endregion Unifom_Buffer_Objects
std::string AMDtechniqueNames[AMD_Max] =
{
"Simple",
"TiledDeferred",
"TiledForward",
"Deferred"
};
std::string NVIDIAtechniqueNames[NVIDIA_Max] =
{
"Simple",
"TiledDeferred",
"TiledForward"
};
#pragma endregion GLOBAL_VARIABLES
/// <summary>
/// Updates transformation matrices.
/// </summary>
static void updateMatrices()
{
transformationMatrices.view = gCamera.view();
transformationMatrices.projection = gCamera.projection();
transformationMatrices.viewProjection = gCamera.projection() * gCamera.view();
transformationMatrices.normal = glm::transpose(glm::inverse(transformationMatrices.view));
transformationMatrices.inverseProjection = glm::inverse(gCamera.projection());
}
/// <summary>
/// Point lights matrices initialization, creates model matrix for sphere mesh,
/// translate to light's world position, scale to light's radius size
/// </summary>
static void initLightSpheres(unsigned count)
{
for (unsigned i = 0; i < count; i++)
{
lightSpheres[i] = glm::scale(glm::translate(glm::mat4(), pointLights[i].position), glm::vec3(pointLights[i].radius));
}
}
/// <summary>
/// Generates lights and their model matrices for deferred shading.
/// </summary>
/// <param name="count">lights' count.</param>
/// <param name="min">minimal radius.</param>
/// <param name="max">maximal radius.</param>
static void generateLights(unsigned short count, float min, float max)
{
pointLights.resize(count);
for (unsigned i = 0; i < count; i++)
{
pointLights[i].color = glm::vec3(randf(0.0, 1.0), randf(0.0, 1.0), randf(0.0, 1.0));
pointLights[i].radius = randf(min, max);
//replace values in randf for another scene boundaries
pointLights[i].position = glm::vec3(randf(-1750.0, 1750.0), randf(0.0, 1550.0), randf(-1000.0, 1000.0));
}
//initialize sphere models to light pos for deferred shading
initLightSpheres(count);
//update light count
LIGHT_COUNT = count;
}
/// <summary>
/// Renders screen space quad.
/// </summary>
/// <param name="shader">The shader.</param>
static void renderQuad(shprogram * shader)
{
shader->use();
// 1st attribute buffer : vertices
glEnableVertexAttribArray(0);
{
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
// Draw the triangles !
// 2*3 indices starting at 0 -> 2 triangles
glDrawArrays(GL_TRIANGLES, 0, 6);
}
glDisableVertexAttribArray(0);
shader->stopUsing();
}
/// <summary>
/// Keyboard callback function.
/// </summary>
/// <param name="window">context window</param>
/// <param name="key">key</param>
/// <param name="scancode">scancode of key</param>
/// <param name="action">action</param>
/// <param name="mods">modifiiers</param>
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS)
{
switch (key)
{
//increase camera movement speed
case GLFW_KEY_KP_ADD:
moveSpeed += 100.0;
break;
//decrease camera movement speed
case GLFW_KEY_KP_SUBTRACT:
moveSpeed -= 100.0;
break;
//show MRT quads
case GLFW_KEY_M:
showMRTQuads = !showMRTQuads;
break;
//generate +/- 128 lights
case GLFW_KEY_G:
{
if (pointLights.size() <= 1024 && decFlag && pointLights.size() >= 256)
{
pointLights.clear();
pointLights.shrink_to_fit();
lastLightCnt -= 128;
}
else
{
decFlag = false;
pointLights.clear();
pointLights.shrink_to_fit();
lastLightCnt += 128;
if (lastLightCnt == 1024)
decFlag = true;
}
generateLights(lastLightCnt, LIGHT_RADIUS_MIN, LIGHT_RADIUS_MAX);
}
break;
//show affected tiles
case GLFW_KEY_6:
{
if (technique)
showAffectedTiles = !showAffectedTiles;
}
break;
//show bounding quads
case GLFW_KEY_B:
{
if (technique != AMD_Simple && technique != AMD_Deferred){
showBoundingQuads = !showBoundingQuads;
}
}
break;
//switch rendering technique
case GLFW_KEY_T:
{
if (GPUVendor == NVIDIA)
{
technique = NVIDIARenderingTechnique((technique + 1) % NVIDIA_Max);
}
else
{
technique = AMDRenderingTechnique((technique + 1) % AMD_Max);
}
}
break;
//depth min max optimization
case GLFW_KEY_U:
{
if (technique == AMD_TiledDeferred || technique == AMD_TiledForward)
minMaxPass = !minMaxPass;
}
break;
//generate new colors for existing lights
case GLFW_KEY_R:
for (unsigned int i = 0; i < pointLights.size(); i++){
pointLights[i].color = glm::vec3(randf(0.0, 1.0), randf(0.0, 1.0), randf(0.0, 1.0));
}
break;
//generate new colors for existing lights
case GLFW_KEY_J:
showLightHeatMap = !showLightHeatMap;
break;
}
}
}
/// <summary>
/// Mouse button callback function for AntTweakBar.
/// </summary>
/// <param name="button">mouse button.</param>
/// <param name="action">action.</param>
static void MouseButtonCB(GLFWwindow*, int button, int action, int mods)
{
TwEventMouseButtonGLFW(button, action);
}
/// <summary>
/// Cursor position callback function for AntTweakBar.
/// </summary>
/// <param name="x">mouse x-coordinate</param>
/// <param name="y">mouse y-coordinate</param>
static void MousePosCB(GLFWwindow*, double x, double y)
{
TwEventMousePosGLFW((int)x, (int)y);
}
/// <summary>
/// Keyboard callback function for AntTweakBar.
/// </summary>
/// <param name="window">graphic context window.</param>
/// <param name="key">key.</param>
/// <param name="scancode">scancode.</param>
/// <param name="action">action.</param>
/// <param name="mods">modifikators.</param>
static void KeyFunCB(GLFWwindow* window, int key, int scancode, int action, int mods)
{
TwEventKeyGLFW(key, action);
TwEventCharGLFW(key, action);
}
/// <summary>
/// Fills view space lights' data into Buffers and binds these buffers as UBOs
/// </summary>
/// <param name="grid">The grid.</param>
static void bindGridBuffers(LightGrid &grid)
{
glm::ivec4 countsAndOffsets[TILES_COUNT];
glm::vec4 posAndRadiuses[MAX_LIGHTS];
glm::vec4 colors[MAX_LIGHTS];
//check validity of global light list
if (grid.getLightListLength())
{
//get viewspace lights from lightgrid
const Lights &lights = grid.getViewSpaceLights();
//fetch position,radiuses and colors into buffers
for (unsigned int i = 0; i < lights.size(); i++)
{
posAndRadiuses[i] = glm::vec4(lights[i].position, lights[i].radius);
colors[i] = glm::vec4(lights[i].color, 1.0f);
}
//get tile light counts and offsets from lightgrid
unsigned int * counts = grid.getCounts();
unsigned int * offsets = grid.getOffsets();
//fetch array
for (unsigned int i = 0; i < TILES_COUNT; i++)
{
countsAndOffsets[i] = glm::ivec4(counts[i], offsets[i], 0, 0);
}
//copy data into buffers
countsAndOffsetsBuffer.copyFromHost(countsAndOffsets, TILES_COUNT);
posAndRadiusesBuffer.copyFromHost(posAndRadiuses, MAX_LIGHTS);
colorsBuffer.copyFromHost(colors, MAX_LIGHTS);
lightIndicesBuffer.copyFromHost(grid.getLightList(), grid.getLightListLength());
//bind buffers to binding slots
countsAndOffsetsBuffer.bindSlot(GL_UNIFORM_BUFFER, TBB_LightGrid);
posAndRadiusesBuffer.bindSlot(GL_UNIFORM_BUFFER, TBB_LightPosAndRadius);
colorsBuffer.bindSlot(GL_UNIFORM_BUFFER, TBB_LightColors);
//bind light's ID texture
glActiveTexture(GL_TEXTURE0 + TDTB_LightIndex);
glBindTexture(GL_TEXTURE_BUFFER, lightIDtex);
}
}
/// <summary>
/// Sets the quad vbo.
/// </summary>
static void createQuadVBO()
{
GLfloat vertices[] =
{
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
-1.0f, 1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
};
glGenBuffers(1, &quadVBO);
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(vertices), vertices, GL_STATIC_DRAW);
}
/// <summary>
/// Renders Multiple Render Targets/debug Quads. We have to check texture type,
/// because we need to bind another shader for linear depth rendering.
/// </summary>
/// <param name="x">x-coord of left bottom corner.</param>
/// <param name="y">y-coord of left bottom corner.</param>
/// <param name="width">quad width.</param>
/// <param name="height">quad height.</param>
/// <param name="tex">rendered texture.</param>
static void renderMRTquad(unsigned x, unsigned y, unsigned width, unsigned height, GLuint tex)
{
shprogram * shader;
//wanna render depth?
if (tex != gTexDepth && tex != minMaxDepthTex)
shader = quadShader;
else
shader = quadDShader;
shader->use();
shader->bindTexToUniform(0, tex, "in_tex");
//change viewport to quad position & size
glViewport(x, y, width, height);
//1st attribute buffer : vertices
glEnableVertexAttribArray(0);
{
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
//draw the triangles !
//2*3 indices starting at 0 -> 2 triangles
glDrawArrays(GL_TRIANGLES, 0, 6);
}
glDisableVertexAttribArray(0);
//restore window viewport
glViewport(0, 0, resolution.x, resolution.y);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
shader->stopUsing();
}
/// <summary>
/// GBuffer/Debug info - renders Multiple Render Targets quads to the screen.
/// </summary>
static void showMRT()
{
//render diffuse,normal,pos,depth textures to quads
if (showMRTQuads && technique != AMD_Simple)
{
if (technique != AMD_TiledForward)
{
renderMRTquad(QUAD_POS, QUAD_HEIGHT * 5, QUAD_WIDTH, QUAD_HEIGHT, minMaxDepthTex);
renderMRTquad(QUAD_POS, QUAD_HEIGHT * 4, QUAD_WIDTH, QUAD_HEIGHT, gTexDiffuse);
renderMRTquad(QUAD_POS, QUAD_HEIGHT * 3, QUAD_WIDTH, QUAD_HEIGHT, gTexNormal);
renderMRTquad(QUAD_POS, QUAD_HEIGHT * 2, QUAD_WIDTH, QUAD_HEIGHT, gTexPos);
renderMRTquad(QUAD_POS, QUAD_HEIGHT, QUAD_WIDTH, QUAD_HEIGHT, gTexSpec);
}
if (technique == AMD_TiledForward)
{
renderMRTquad(QUAD_POS, QUAD_HEIGHT * 2, QUAD_WIDTH, QUAD_HEIGHT, minMaxDepthTex);
}
renderMRTquad(QUAD_POS, 0, QUAD_WIDTH, QUAD_HEIGHT, gTexDepth);
}
//renders depth to application "fullscreen"
if (showDepth)
{
renderMRTquad(0, 0, resolution.x, resolution.y, gTexDepth);
}
}
/// <summary>
/// Unbinds active textures.
/// </summary>
/// <param name="count">active textures count.</param>
static void unbindTextures(unsigned short count)
{
for (unsigned int i = 0; i < count; i++)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, 0);
}
}
/// <summary>
/// Early-Z pass for tiled forward shading.
/// </summary>
static void depthPrePass()
{
glBindFramebuffer(GL_FRAMEBUFFER, forwardFbo);
glDepthFunc(GL_LEQUAL);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_DEPTH_BUFFER_BIT);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
//bind Multiple Render Targets shader program
simpleShader->use();
//set the model view projection uniform
simpleShader->setUniform("MVP", transformationMatrices.viewProjection);
//render meshes
m_pMesh->RenderSimple();
//unbind shader program
simpleShader->stopUsing();
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
/// <summary>
/// Calculates the minimum and maximum depth. Outputs vec4 containing vec2()
/// min/max depth per tile in view space and vec2() min /max clamped to <0.0,1.0>
/// </summary>
/// <param name="tileDepthRanges">vector to store downsampled values.</param>
static void calcMinMaxDepth(std::vector<MinMax> &tileDepthRanges)
{
glBindFramebuffer(GL_FRAMEBUFFER, minMaxDepthFbo);
//clear color buffer
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, grid_size.x, grid_size.y);
//use downsampling shader
minMaxDepthShader->use();
minMaxDepthShader->bindTexToUniform(0, gTexDepth, "depthTex");
minMaxDepthShader->setUniform("inverseProjectionMatrix", transformationMatrices.inverseProjection);
minMaxDepthShader->stopUsing();
//render quad
renderQuad(minMaxDepthShader);
tileDepthRanges.resize((unsigned short)grid_size.x * (unsigned short)grid_size.y);
//read values from pixel buffer and store them in vector
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
glReadPixels(0, 0, grid_size.x, grid_size.y, GL_RG, GL_FLOAT, &tileDepthRanges[0]);
//bind default fbo and restore viewport
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, resolution.x, resolution.y);
}
/// <summary>
/// Geometry pass of deferred shading.
/// - geometry is rendered to G-buffer
/// - stores positions, normals, specular and diffuse textures
/// - updates depth buffer
/// </summary>
void DSgeometryPass()
{
glEnable(GL_DEPTH_TEST);
//bind G-buffer for current pass
gBuf->bindForGeomPass();
//bind Multiple Render Targets shader program and render scene
mrt->use();
mrt->setUniform("projection", transformationMatrices.projection);
mrt->setUniform("view", transformationMatrices.view);
mrt->setUniform("model", glm::mat4());
m_pMesh->Render(mrt->object());
mrt->stopUsing();
//do not update depth buffer
glDisable(GL_DEPTH_TEST);
}
/// <summary>
/// Lighting pass of deferred shading.
/// - applies lights to textures from Gbuffer
/// </summary>
void DSlightPass()
{
//shading pass
gBuf->bindForLightPass();
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
deferredShader->use();
//set transformation positions
for (unsigned int i = 0; i < pointLights.size(); i++)
{
glm::vec4 posRad = transformationMatrices.view * (glm::vec4(pointLights[i].position, 1.0));
posRad.w = pointLights[i].radius;
glm::mat4 MVP = transformationMatrices.viewProjection * lightSpheres[i];
deferredShader->setUniform("MVP", MVP);
deferredShader->setUniform("light.positionRadius", posRad);
deferredShader->setUniform("light.color", glm::vec3(pointLights[i].color));
m_sphere->Render(deferredShader->object());
}
deferredShader->stopUsing();
glCullFace(GL_BACK);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
unbindTextures(DTB_Max);
}
/// <summary>
/// Lighting pass of tiled deferred shading.
/// </summary>
static void TDSlightPass()
{
glViewport(0, 0, resolution.x, resolution.y);
//bind gbuffer for writing to ambient light texture
gBuf->bindForLightPass();
tiledDeferredShader->use();
// 1st attribute buffer : vertices
glEnableVertexAttribArray(0);
{
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
// Draw the triangles !
// 2*3 indices starting at 0 -> 2 triangles
glDrawArrays(GL_TRIANGLES, 0, 6);
}
glDisableVertexAttribArray(0);
tiledDeferredShader->stopUsing();
//unbind bound textures
unbindTextures(TDTB_Max);
}
/// <summary>
/// Rendering function. Uses specific method of shading based on chosen parameters.
/// </summary>
static void Render()
{
//update transformation matrices
updateMatrices();
//timer for light grid build
PerformanceTimer gridTimer;
switch(technique)
{
//simple shading with no lights
#pragma region SIMPLE_SHADING
case AMD_Simple:
{
glEnable(GL_DEPTH_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//bind Multiple Render Targets shader program
simpleShader->use();
//set the model view projection uniform
simpleShader->setUniform("MVP", transformationMatrices.viewProjection);
//render meshes
m_pMesh->RenderSimple();
//unbind shader program
simpleShader->stopUsing();
glDisable(GL_DEPTH_TEST);
}
break;
#pragma endregion SIMPLE_SHADING
//standard deferred shading
#pragma region DEFERRED_SHADING
case AMD_Deferred:
{
//clear G-Buffer textures
gBuf->clearTextures();
//1st pass
DSgeometryPass();
//2nd pass
DSlightPass();
//set texture for final output
gBuf->bindForFinalPass(gBufTexIndex);
glBlitFramebuffer(0, 0, resolution.x, resolution.y, 0, 0, resolution.x, resolution.y, GL_COLOR_BUFFER_BIT, GL_NEAREST);
//render G-buffer textures to main FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//if enabled render G-buffer textures to quads
if (showMRTQuads)
{
showMRT();
}
}
break;
#pragma endregion DEFERRED_SHADING
//tiled deferred shading
#pragma region TILED_DEFERRED_SHADING
case AMD_TiledDeferred:
{
//clear G-buffer textures
gBuf->clearTextures();
//1st pass
DSgeometryPass();
//start grid build timer
//gridTimer.start();
std::vector<MinMax> tileDepthRanges;
if (minMaxPass)
{
//glBeginQuery(GL_TIME_ELAPSED, minMaxDepthQuery);
calcMinMaxDepth(tileDepthRanges);
//glEndQuery(GL_TIME_ELAPSED);
//glGetQueryObjectuiv(minMaxDepthQuery, GL_QUERY_RESULT_NO_WAIT, &minMaxDepthQueryTime);
}
//build light grid
if (pointLights.size() > 0)
{
lightgrid.buildLightGrid(tileDepthRanges, pointLights, gCamera.nearPlane(), transformationMatrices.view, transformationMatrices.projection);
}
//gridTimer.stop();
//bind G-Buffer
glBindFramebuffer(GL_FRAMEBUFFER, gBuf->getFramebufferID());
//bind Uniform buffers
bindGridBuffers(lightgrid);
//render light heat map/affected tiles/lighting
if (showLightHeatMap)
{
renderQuad(lightHeatMapShader);
}
else if (showAffectedTiles)
{
renderQuad(affectedTilesShader);
}
else
{
//glBeginQuery(GL_TIME_ELAPSED, lightingQuery);
//2nd pass
TDSlightPass();
//glEndQuery(GL_TIME_ELAPSED);
//glGetQueryObjectuiv(lightingQuery, GL_QUERY_RESULT_NO_WAIT, &lightingQueryTime);
}
//unbind light's ID tex
glActiveTexture(GL_TEXTURE0 + TDTB_LightIndex);
glBindTexture(GL_TEXTURE_BUFFER, 0);
//set texture for final output
gBuf->bindForFinalPass(gBufTexIndex);
glBlitFramebuffer(0, 0, resolution.x, resolution.y, 0, 0, resolution.x, resolution.y, GL_COLOR_BUFFER_BIT, GL_NEAREST);
//final pass
showMRT();
}
break;
#pragma endregion TILED_DEFERRED_SHADING
//tiled forward shading
#pragma region TILED_FORWARD_SHADING
case AMD_TiledForward:
{
glEnable(GL_DEPTH_TEST);
//do depth pre pass
depthPrePass();
//gridTimer.start();
std::vector<MinMax> tileDepthRanges;
//depth optimization
if (minMaxPass)
{
//glBeginQuery(GL_TIME_ELAPSED, minMaxDepthQuery);
calcMinMaxDepth(tileDepthRanges);
//glEndQuery(GL_TIME_ELAPSED);
//glGetQueryObjectuiv(minMaxDepthQuery, GL_QUERY_RESULT_NO_WAIT, &minMaxDepthQueryTime);
}
//build lightgrid
if (pointLights.size() > 0)
{
lightgrid.buildLightGrid(tileDepthRanges, pointLights, gCamera.nearPlane(), transformationMatrices.view, transformationMatrices.projection);
}
//gridTimer.stop();
//Bind forward FBO
glBindFramebuffer(GL_FRAMEBUFFER, forwardFbo);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, resolution.x, resolution.y);
//Bind uniform buffers
bindGridBuffers(lightgrid);
if (showLightHeatMap)
{
renderQuad(lightHeatMapShader);
}
else if (showAffectedTiles)
{
renderQuad(affectedTilesShader);
}
else
{
//glBeginQuery(GL_TIME_ELAPSED, lightingQuery);
//render scene
tiledForwardShader->use();
tiledForwardShader->setUniform("viewProjection", transformationMatrices.viewProjection);
tiledForwardShader->setUniform("view", transformationMatrices.view);
tiledForwardShader->setUniform("normalMatrix", transformationMatrices.normal);
m_pMesh->Render(tiledForwardShader->object());
tiledForwardShader->stopUsing();
//glEndQuery(GL_TIME_ELAPSED);
//glGetQueryObjectuiv(lightingQuery, GL_QUERY_RESULT_NO_WAIT, &lightingQueryTime);
}
//unbind light's ID tex
glActiveTexture(GL_TEXTURE0 + TDTB_LightIndex);
glBindTexture(GL_TEXTURE_BUFFER, 0);
//set read/write FBOs
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, forwardFbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBlitFramebuffer(0, 0, resolution.x, resolution.y, 0, 0, resolution.x, resolution.y, GL_COLOR_BUFFER_BIT, GL_NEAREST);
//final pass
showMRT();
glDisable(GL_DEPTH_TEST);
}
break;
#pragma endregion TILED_FORWARD_SHADING
default:
break;
}
//Draw bounding quad
if (showBoundingQuads)
{
lightgrid.showLightQuads();
}
//Draw AntTweakBar
TwDraw();
if (GPUVendor == AMD)
calcFPS(win, 0.1, AMDtechniqueNames[technique]);
else
calcFPS(win, 0.1, NVIDIAtechniqueNames[technique]);
//calculate frames per second and writes it to window title once pers 0.5s
/*lightingTime.push_back(lightingQueryTime/1000000);
minmaxTime.push_back(minMaxDepthQueryTime / 1000000);
gridTime.push_back(float(gridTimer.getElapsedTime() * 1000.0));*/
//watch events
glfwPollEvents();
//swap front and back buffers
glfwSwapBuffers(win);
}
/// <summary>
/// Update the scene based on the time elapsed since last update,
/// mostly used for movement in the scene, mouse and camera handle.