-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathGlslProgram.cpp
More file actions
1298 lines (1155 loc) · 45.4 KB
/
GlslProgram.cpp
File metadata and controls
1298 lines (1155 loc) · 45.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
//
// Copyright Contributors to the MaterialX Project
// SPDX-License-Identifier: Apache-2.0
//
#include <MaterialXRenderGlsl/External/Glad/glad.h>
#include <MaterialXRenderGlsl/GlslProgram.h>
#include <MaterialXRenderGlsl/GLTextureHandler.h>
#include <MaterialXRenderGlsl/GLUtil.h>
#include <MaterialXRender/LightHandler.h>
#include <MaterialXRender/ShaderRenderer.h>
#include <MaterialXGenHw/HwConstants.h>
#include <MaterialXTrace/Tracing.h>
#include <iostream>
MATERIALX_NAMESPACE_BEGIN
namespace
{
const float PI = std::acos(-1.0f);
} // anonymous namespace
// OpenGL Constants
unsigned int GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID = 0;
int GlslProgram::UNDEFINED_OPENGL_PROGRAM_LOCATION = -1;
int GlslProgram::Input::INVALID_OPENGL_TYPE = -1;
//
// GlslProgram methods
//
GlslProgram::GlslProgram() :
_programId(UNDEFINED_OPENGL_RESOURCE_ID),
_shader(nullptr),
_vertexArray(UNDEFINED_OPENGL_RESOURCE_ID)
{
}
GlslProgram::~GlslProgram()
{
clearBuiltData();
}
void GlslProgram::setStages(ShaderPtr shader)
{
if (!shader)
{
throw ExceptionRenderError("Cannot set stages using null hardware shader");
}
// Clear existing stages and built data
_stages.clear();
clearBuiltData();
// Extract out the shader code per stage
_shader = shader;
for (size_t i = 0; i < shader->numStages(); ++i)
{
const ShaderStage& stage = shader->getStage(i);
addStage(stage.getName(), stage.getSourceCode());
}
}
void GlslProgram::addStage(const string& stage, const string& sourceCode)
{
_stages[stage] = sourceCode;
}
const string& GlslProgram::getStageSourceCode(const string& stage) const
{
auto it = _stages.find(stage);
if (it != _stages.end())
{
return it->second;
}
return EMPTY_STRING;
}
void GlslProgram::build()
{
MX_TRACE_FUNCTION(Tracing::Category::Render);
clearBuiltData();
GLint glStatus = GL_FALSE;
int glInfoLogLength = 0;
StringVec errors;
unsigned int stagesBuilt = 0;
unsigned int desiredStages = 0;
for (const auto& it : _stages)
{
if (!it.second.empty())
{
desiredStages++;
}
}
// Compile vertex shader, if any
GLuint vertexShaderId = UNDEFINED_OPENGL_RESOURCE_ID;
const string& vertexShaderSource = _stages[Stage::VERTEX];
if (!vertexShaderSource.empty())
{
vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
// Compile vertex shader
const char* vertexChar = vertexShaderSource.c_str();
glShaderSource(vertexShaderId, 1, &vertexChar, nullptr);
glCompileShader(vertexShaderId);
// Check vertex shader
glGetShaderiv(vertexShaderId, GL_COMPILE_STATUS, &glStatus);
if (glStatus == GL_FALSE)
{
errors.push_back("Error in compiling vertex shader:");
glGetShaderiv(vertexShaderId, GL_INFO_LOG_LENGTH, &glInfoLogLength);
if (glInfoLogLength > 0)
{
std::vector<char> vsErrorMessage((size_t) glInfoLogLength + 1);
glGetShaderInfoLog(vertexShaderId, glInfoLogLength, nullptr, &vsErrorMessage[0]);
errors.push_back(&vsErrorMessage[0]);
}
}
else
{
stagesBuilt++;
}
}
// Compile fragment shader, if any
GLuint fragmentShaderId = UNDEFINED_OPENGL_RESOURCE_ID;
const string& fragmentShaderSource = _stages[Stage::PIXEL];
if (!fragmentShaderSource.empty())
{
fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
// Compile fragment shader
const char* fragmentChar = fragmentShaderSource.c_str();
glShaderSource(fragmentShaderId, 1, &fragmentChar, nullptr);
glCompileShader(fragmentShaderId);
// Check fragment shader
glGetShaderiv(fragmentShaderId, GL_COMPILE_STATUS, &glStatus);
if (glStatus == GL_FALSE)
{
errors.push_back("Error in compiling fragment shader:");
glGetShaderiv(fragmentShaderId, GL_INFO_LOG_LENGTH, &glInfoLogLength);
if (glInfoLogLength > 0)
{
std::vector<char> fsErrorMessage((size_t) glInfoLogLength + 1);
glGetShaderInfoLog(fragmentShaderId, glInfoLogLength, nullptr, &fsErrorMessage[0]);
errors.push_back(&fsErrorMessage[0]);
}
}
else
{
stagesBuilt++;
}
}
// Link the shader program
if (stagesBuilt == desiredStages)
{
_programId = glCreateProgram();
glAttachShader(_programId, vertexShaderId);
glAttachShader(_programId, fragmentShaderId);
glLinkProgram(_programId);
// Check the program
glGetProgramiv(_programId, GL_LINK_STATUS, &glStatus);
if (glStatus == GL_FALSE)
{
errors.push_back("Error in linking program:");
glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &glInfoLogLength);
if (glInfoLogLength > 0)
{
std::vector<char> ProgramErrorMessage(glInfoLogLength + 1);
glGetProgramInfoLog(_programId, glInfoLogLength, nullptr, &ProgramErrorMessage[0]);
errors.push_back(&ProgramErrorMessage[0]);
}
}
}
// Cleanup
if (vertexShaderId != UNDEFINED_OPENGL_RESOURCE_ID)
{
if (_programId != UNDEFINED_OPENGL_RESOURCE_ID)
{
glDetachShader(_programId, vertexShaderId);
}
glDeleteShader(vertexShaderId);
}
if (fragmentShaderId != UNDEFINED_OPENGL_RESOURCE_ID)
{
if (_programId != UNDEFINED_OPENGL_RESOURCE_ID)
{
glDetachShader(_programId, fragmentShaderId);
}
glDeleteShader(fragmentShaderId);
}
// If we encountered any errors while trying to create return list
// of all errors. That is we collect all errors per stage plus any
// errors during linking and throw one exception for them all so that
// if there is a failure a complete set of issues is returned. We do
// this after cleanup so keep GL state clean.
if (!errors.empty() || stagesBuilt != desiredStages)
{
throw ExceptionRenderError("GLSL compilation error", errors);
}
}
bool GlslProgram::hasBuiltData()
{
return _programId != UNDEFINED_OPENGL_RESOURCE_ID;
}
void GlslProgram::clearBuiltData()
{
if (_programId != UNDEFINED_OPENGL_RESOURCE_ID)
{
glDeleteProgram(_programId);
_programId = UNDEFINED_OPENGL_RESOURCE_ID;
}
_uniformList.clear();
_attributeList.clear();
}
bool GlslProgram::bind()
{
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
return false;
}
glUseProgram(_programId);
checkGlErrors("after program bind");
return true;
}
void GlslProgram::bindAttribute(const GlslProgram::InputMap& inputs, MeshPtr mesh)
{
if (!mesh)
{
throw ExceptionRenderError("No geometry set to bind");
}
for (const auto& input : inputs)
{
int location = input.second->location;
unsigned int index = input.second->value ? input.second->value->asA<int>() : 0;
unsigned int stride = 0;
MeshStreamPtr stream = mesh->getStream(input.first);
if (!stream)
{
throw ExceptionRenderError("Geometry buffer could not be retrieved for binding: " + input.first + ". Index: " + std::to_string(index));
}
MeshFloatBuffer& attributeData = stream->getData();
stride = stream->getStride();
if (attributeData.empty() || (stride == 0))
{
throw ExceptionRenderError("Geometry buffer could not be retrieved for binding: " + input.first + ". Index: " + std::to_string(index));
}
if (_attributeBufferIds.find(input.first) == _attributeBufferIds.end())
{
const float* bufferData = &attributeData[0];
size_t bufferSize = attributeData.size() * sizeof(float);
// Create a buffer based on attribute type.
unsigned int bufferId = GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID;
glGenBuffers(1, &bufferId);
glBindBuffer(GL_ARRAY_BUFFER, bufferId);
glBufferData(GL_ARRAY_BUFFER, bufferSize, bufferData, GL_STATIC_DRAW);
_attributeBufferIds[input.first] = bufferId;
}
else
{
glBindBuffer(GL_ARRAY_BUFFER, _attributeBufferIds[input.first]);
}
glEnableVertexAttribArray(location);
_enabledStreamLocations.insert(location);
if (input.second->gltype != GL_INT)
{
glVertexAttribPointer(location, stride, GL_FLOAT, GL_FALSE, 0, nullptr);
}
else
{
glVertexAttribIPointer(location, stride, GL_INT, 0, nullptr);
}
}
}
void GlslProgram::bindPartition(MeshPartitionPtr part)
{
if (!part || part->getFaceCount() == 0)
{
throw ExceptionRenderError("Cannot bind geometry partition");
}
if (_indexBufferIds.find(part) != _indexBufferIds.end())
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferIds[part]);
}
else
{
MeshIndexBuffer& indexData = part->getIndices();
size_t indexBufferSize = indexData.size();
unsigned int indexBuffer = GlslProgram::UNDEFINED_OPENGL_RESOURCE_ID;
glGenBuffers(1, &indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferSize * sizeof(uint32_t), &indexData[0], GL_STATIC_DRAW);
_indexBufferIds[part] = indexBuffer;
}
}
void GlslProgram::bindMesh(MeshPtr mesh)
{
_enabledStreamLocations.clear();
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
throw ExceptionRenderError("Cannot bind geometry without a valid program");
}
if (!mesh)
{
throw ExceptionRenderError("No mesh to bind");
}
if (mesh != _boundMesh)
{
unbindGeometry();
}
GlslProgram::InputMap foundList;
const GlslProgram::InputMap& attributeList = getAttributesList();
if (_vertexArray == UNDEFINED_OPENGL_RESOURCE_ID)
{
// Set up vertex arrays
glGenVertexArrays(1, &_vertexArray);
}
glBindVertexArray(_vertexArray);
// Bind positions
findInputs(HW::IN_POSITION, attributeList, foundList, true);
if (foundList.size())
{
bindAttribute(foundList, mesh);
}
// Bind normals
findInputs(HW::IN_NORMAL, attributeList, foundList, true);
if (foundList.size())
{
bindAttribute(foundList, mesh);
}
// Bind tangents
findInputs(HW::IN_TANGENT, attributeList, foundList, true);
if (foundList.size())
{
bindAttribute(foundList, mesh);
}
// Bind bitangents
findInputs(HW::IN_BITANGENT, attributeList, foundList, true);
if (foundList.size())
{
bindAttribute(foundList, mesh);
}
// Bind colors
// Search for anything that starts with the color prefix
findInputs(HW::IN_COLOR + "_", attributeList, foundList, false);
if (foundList.size())
{
bindAttribute(foundList, mesh);
}
// Bind texture coordinates
// Search for anything that starts with the texcoord prefix
findInputs(HW::IN_TEXCOORD + "_", attributeList, foundList, false);
if (foundList.size())
{
bindAttribute(foundList, mesh);
}
// Bind any named varying geometric property information
findInputs(HW::IN_GEOMPROP + "_", attributeList, foundList, false);
if (foundList.size())
{
bindAttribute(foundList, mesh);
}
// Bind any named uniform geometric property information
const GlslProgram::InputMap& uniformList = getUniformsList();
findInputs(HW::GEOMPROP + "_", uniformList, foundList, false);
for (const auto& input : foundList)
{
// Only handle float1-4 types for now
switch (input.second->gltype)
{
case GL_INT:
glUniform1i(input.second->location, 1);
break;
case GL_FLOAT:
glUniform1f(input.second->location, 0.0f);
break;
case GL_FLOAT_VEC2:
glUniform2f(input.second->location, 0.0f, 0.0f);
break;
case GL_FLOAT_VEC3:
glUniform3f(input.second->location, 0.0f, 0.0f, 0.0f);
break;
case GL_FLOAT_VEC4:
glUniform4f(input.second->location, 0.0f, 0.0f, 0.0f, 1.0f);
break;
default:
break;
}
}
// Store the bound mesh.
_boundMesh = mesh;
checkGlErrors("after program bind mesh");
}
void GlslProgram::unbindGeometry()
{
if (!_boundMesh)
{
return;
}
// Unbind all geometry buffers.
glBindVertexArray(UNDEFINED_OPENGL_RESOURCE_ID);
glBindBuffer(GL_ARRAY_BUFFER, UNDEFINED_OPENGL_RESOURCE_ID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, UNDEFINED_OPENGL_RESOURCE_ID);
_enabledStreamLocations.clear();
// Release attribute buffers.
for (const auto& attributeBufferId : _attributeBufferIds)
{
unsigned int bufferId = attributeBufferId.second;
if (bufferId > 0)
{
glDeleteBuffers(1, &bufferId);
}
}
_attributeBufferIds.clear();
// Release vertex array.
if (_vertexArray != UNDEFINED_OPENGL_RESOURCE_ID)
{
glDeleteVertexArrays(1, &_vertexArray);
_vertexArray = UNDEFINED_OPENGL_RESOURCE_ID;
}
// Release index buffers.
for (const auto& indexBufferId : _indexBufferIds)
{
unsigned int bufferId = indexBufferId.second;
if (bufferId > 0)
{
glDeleteBuffers(1, &bufferId);
}
}
_indexBufferIds.clear();
// Clear the bound mesh.
_boundMesh = nullptr;
checkGlErrors("after program unbind geometry");
}
ImagePtr GlslProgram::bindTexture(unsigned int uniformType, int uniformLocation, const FilePath& filePath,
ImageHandlerPtr imageHandler, const ImageSamplingProperties& samplingProperties)
{
if (uniformLocation >= 0 &&
uniformType >= GL_SAMPLER_1D && uniformType <= GL_SAMPLER_CUBE)
{
// Acquire the image.
ImagePtr image = imageHandler->acquireImage(filePath, samplingProperties.defaultColor);
if (imageHandler->bindImage(image, samplingProperties))
{
GLTextureHandlerPtr textureHandler = std::static_pointer_cast<GLTextureHandler>(imageHandler);
int textureLocation = textureHandler->getBoundTextureLocation(image->getResourceId());
if (textureLocation >= 0)
{
glUniform1i(uniformLocation, textureLocation);
}
}
checkGlErrors("after program bind texture");
return image;
}
return nullptr;
}
MaterialX::ConstValuePtr GlslProgram::findUniformValue(const string& uniformName, const GlslProgram::InputMap& uniformList)
{
auto uniform = uniformList.find(uniformName);
if (uniform != uniformList.end())
{
int location = uniform->second->location;
if (location >= 0)
{
return uniform->second->value;
}
}
return nullptr;
}
void GlslProgram::bindTextures(ImageHandlerPtr imageHandler)
{
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
throw ExceptionRenderError("Cannot bind textures without a valid program");
}
if (!imageHandler)
{
throw ExceptionRenderError("Cannot bind textures without an image handler");
}
// Bind textures based on uniforms found in the program
const GlslProgram::InputMap& uniformList = getUniformsList();
const VariableBlock& publicUniforms = _shader->getStage(Stage::PIXEL).getUniformBlock(HW::PUBLIC_UNIFORMS);
for (const auto& uniform : uniformList)
{
GLenum uniformType = uniform.second->gltype;
GLint uniformLocation = uniform.second->location;
if (uniformLocation >= 0 &&
uniformType >= GL_SAMPLER_1D && uniformType <= GL_SAMPLER_CUBE)
{
const string fileName(uniform.second->value ? uniform.second->value->getValueString() : "");
// Always bind a texture unless it is a lighting texture.
// Lighting textures are handled in the bindLighting() call.
// If no texture can be loaded then the default color defined in
// "samplingProperties" will be used to create a fallback texture.
if (uniform.first != HW::ENV_RADIANCE &&
uniform.first != HW::ENV_IRRADIANCE)
{
ImageSamplingProperties samplingProperties;
samplingProperties.setProperties(uniform.first, publicUniforms);
bindTexture(uniformType, uniformLocation, fileName, imageHandler, samplingProperties);
}
}
}
}
void GlslProgram::bindLighting(LightHandlerPtr lightHandler, ImageHandlerPtr imageHandler)
{
if (!lightHandler)
{
// Nothing to bind if a light handler is not used. This is a valid condition
// for shaders that don't need lighting, so just exit silently.
return;
}
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
throw ExceptionRenderError("Cannot bind without a valid program");
}
// Bind environment lighting properties.
Matrix44 envRotation = Matrix44::createRotationY(PI) * lightHandler->getLightTransform().getTranspose();
bindUniform(HW::ENV_MATRIX, Value::createValue(envRotation), false);
bindUniform(HW::ENV_RADIANCE_SAMPLES, Value::createValue(lightHandler->getEnvSampleCount()), false);
bindUniform(HW::ENV_LIGHT_INTENSITY, Value::createValue(lightHandler->getEnvLightIntensity()), false);
ImagePtr envRadiance = nullptr;
if (lightHandler->getIndirectLighting())
{
envRadiance = lightHandler->getUsePrefilteredMap() ?
lightHandler->getEnvPrefilteredMap() :
lightHandler->getEnvRadianceMap();
}
else
{
envRadiance = imageHandler->getZeroImage();
}
ImageMap envImages =
{
{ HW::ENV_RADIANCE, envRadiance },
{ HW::ENV_IRRADIANCE, lightHandler->getIndirectLighting() ? lightHandler->getEnvIrradianceMap() : imageHandler->getZeroImage() }
};
for (const auto& env : envImages)
{
std::string uniform = env.first;
ImagePtr image = env.second;
if (image && hasUniform(env.first))
{
ImageSamplingProperties samplingProperties;
samplingProperties.uaddressMode = ImageSamplingProperties::AddressMode::PERIODIC;
samplingProperties.vaddressMode = ImageSamplingProperties::AddressMode::CLAMP;
samplingProperties.filterType = ImageSamplingProperties::FilterType::LINEAR;
// Bind the environment image.
if (imageHandler->bindImage(image, samplingProperties))
{
GLTextureHandlerPtr textureHandler = std::static_pointer_cast<GLTextureHandler>(imageHandler);
int textureLocation = textureHandler->getBoundTextureLocation(image->getResourceId());
if (textureLocation >= 0)
{
bindUniform(uniform, Value::createValue(textureLocation));
}
// Bind any associated uniforms.
if (uniform == HW::ENV_RADIANCE)
{
bindUniform(HW::ENV_RADIANCE_MIPS, Value::createValue((int) image->getMaxMipCount()), false);
}
}
}
}
bindUniform(HW::REFRACTION_TWO_SIDED, Value::createValue(lightHandler->getRefractionTwoSided()), false);
// Bind direct lighting properties.
if (hasUniform(HW::NUM_ACTIVE_LIGHT_SOURCES))
{
int lightCount = lightHandler->getDirectLighting() ? (int) lightHandler->getLightSources().size() : 0;
bindUniform(HW::NUM_ACTIVE_LIGHT_SOURCES, Value::createValue(lightCount));
LightIdMap idMap = lightHandler->computeLightIdMap(lightHandler->getLightSources());
size_t index = 0;
for (NodePtr light : lightHandler->getLightSources())
{
auto nodeDef = light->getNodeDef();
if (!nodeDef)
{
continue;
}
const std::string prefix = HW::LIGHT_DATA_INSTANCE + "[" + std::to_string(index) + "]";
// Set light type id
std::string lightType(prefix + ".type");
if (hasUniform(lightType))
{
unsigned int lightTypeValue = idMap[nodeDef->getName()];
bindUniform(lightType, Value::createValue((int) lightTypeValue));
}
// Set all inputs
for (const auto& input : light->getInputs())
{
// Make sure we have a value to set
if (input->hasValue())
{
std::string inputName(prefix + "." + input->getName());
if (hasUniform(inputName))
{
if (input->getName() == "direction" && input->hasValue() && input->getValue()->isA<Vector3>())
{
Vector3 dir = input->getValue()->asA<Vector3>();
dir = lightHandler->getLightTransform().transformVector(dir);
bindUniform(inputName, Value::createValue(dir));
}
else
{
bindUniform(inputName, input->getValue());
}
}
}
}
++index;
}
}
// Bind the directional albedo table, if needed.
ImagePtr albedoTable = lightHandler->getAlbedoTable();
if (albedoTable && hasUniform(HW::ALBEDO_TABLE))
{
ImageSamplingProperties samplingProperties;
samplingProperties.uaddressMode = ImageSamplingProperties::AddressMode::CLAMP;
samplingProperties.vaddressMode = ImageSamplingProperties::AddressMode::CLAMP;
samplingProperties.filterType = ImageSamplingProperties::FilterType::LINEAR;
if (imageHandler->bindImage(albedoTable, samplingProperties))
{
GLTextureHandlerPtr textureHandler = std::static_pointer_cast<GLTextureHandler>(imageHandler);
int textureLocation = textureHandler->getBoundTextureLocation(albedoTable->getResourceId());
if (textureLocation >= 0)
{
bindUniform(HW::ALBEDO_TABLE, Value::createValue(textureLocation));
}
}
}
}
bool GlslProgram::hasUniform(const string& name)
{
const GlslProgram::InputMap& uniformList = getUniformsList();
return uniformList.find(name) != uniformList.end();
}
void GlslProgram::bindUniform(const string& name, ConstValuePtr value, bool errorIfMissing)
{
const GlslProgram::InputMap& uniformList = getUniformsList();
auto input = uniformList.find(name);
if (input != uniformList.end())
{
int location = input->second->location;
if (location < 0)
{
if (errorIfMissing)
{
throw ExceptionRenderError("Unknown uniform: " + name);
}
return;
}
bindUniformLocation(location, value);
}
}
void GlslProgram::bindUniformLocation(int location, ConstValuePtr value)
{
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
throw ExceptionRenderError("Cannot bind without a valid program");
}
if (location >= 0 && value->getValueString() != EMPTY_STRING)
{
if (value->getTypeString() == "float")
{
float v = value->asA<float>();
glUniform1f(location, v);
}
else if (value->getTypeString() == "integer")
{
int v = value->asA<int>();
glUniform1i(location, v);
}
else if (value->getTypeString() == "boolean")
{
bool v = value->asA<bool>();
glUniform1i(location, v ? 1 : 0);
}
else if (value->getTypeString() == "color3")
{
Color3 v = value->asA<Color3>();
glUniform3f(location, v[0], v[1], v[2]);
}
else if (value->getTypeString() == "color4")
{
Color4 v = value->asA<Color4>();
glUniform4f(location, v[0], v[1], v[2], v[3]);
}
else if (value->getTypeString() == "vector2")
{
Vector2 v = value->asA<Vector2>();
glUniform2f(location, v[0], v[1]);
}
else if (value->getTypeString() == "vector3")
{
Vector3 v = value->asA<Vector3>();
glUniform3f(location, v[0], v[1], v[2]);
}
else if (value->getTypeString() == "vector4")
{
Vector4 v = value->asA<Vector4>();
glUniform4f(location, v[0], v[1], v[2], v[3]);
}
else if (value->getTypeString() == "matrix33")
{
Matrix33 m = value->asA<Matrix33>();
glUniformMatrix3fv(location, 1, GL_FALSE, m.data());
}
else if (value->getTypeString() == "matrix44")
{
Matrix44 m = value->asA<Matrix44>();
glUniformMatrix4fv(location, 1, GL_FALSE, m.data());
}
else
{
throw ExceptionRenderError("Unsupported data type when setting uniform value");
}
}
}
void GlslProgram::bindViewInformation(CameraPtr camera)
{
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
throw ExceptionRenderError("Cannot bind without a valid program");
}
if (!camera)
{
throw ExceptionRenderError("Cannot bind without a camera");
}
// View position and direction
bindUniform(HW::VIEW_POSITION, Value::createValue(camera->getViewPosition()), false);
bindUniform(HW::VIEW_DIRECTION, Value::createValue(camera->getViewDirection()), false);
// World matrices
Matrix44 worldInv = camera->getWorldMatrix().getInverse();
bindUniform(HW::WORLD_MATRIX, Value::createValue(camera->getWorldMatrix()), false);
bindUniform(HW::WORLD_TRANSPOSE_MATRIX, Value::createValue(camera->getWorldMatrix().getTranspose()), false);
bindUniform(HW::WORLD_INVERSE_MATRIX, Value::createValue(worldInv), false);
bindUniform(HW::WORLD_INVERSE_TRANSPOSE_MATRIX, Value::createValue(worldInv.getTranspose()), false);
// View matrices
Matrix44 viewInv = camera->getViewMatrix().getInverse();
bindUniform(HW::VIEW_MATRIX, Value::createValue(camera->getViewMatrix()), false);
bindUniform(HW::VIEW_TRANSPOSE_MATRIX, Value::createValue(camera->getViewMatrix().getTranspose()), false);
bindUniform(HW::VIEW_INVERSE_MATRIX, Value::createValue(viewInv), false);
bindUniform(HW::VIEW_INVERSE_TRANSPOSE_MATRIX, Value::createValue(viewInv.getTranspose()), false);
// Projection matrices
Matrix44 projInv = camera->getProjectionMatrix().getInverse();
bindUniform(HW::PROJ_MATRIX, Value::createValue(camera->getProjectionMatrix()), false);
bindUniform(HW::PROJ_TRANSPOSE_MATRIX, Value::createValue(camera->getProjectionMatrix().getTranspose()), false);
bindUniform(HW::PROJ_INVERSE_MATRIX, Value::createValue(projInv), false);
bindUniform(HW::PROJ_INVERSE_TRANSPOSE_MATRIX, Value::createValue(projInv.getTranspose()), false);
// View-projection matrix
Matrix44 viewProj = camera->getViewMatrix() * camera->getProjectionMatrix();
bindUniform(HW::VIEW_PROJECTION_MATRIX, Value::createValue(viewProj), false);
// View-projection-world matrix
Matrix44 worldViewProj = camera->getWorldViewProjMatrix();
bindUniform(HW::WORLD_VIEW_PROJECTION_MATRIX, Value::createValue(worldViewProj), false);
}
void GlslProgram::bindTimeAndFrame(float time, float frame)
{
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
throw ExceptionRenderError("Cannot bind time/frame without a valid program");
}
bindUniform(HW::TIME, Value::createValue(time), false);
bindUniform(HW::FRAME, Value::createValue(frame), false);
}
bool GlslProgram::hasActiveAttributes() const
{
GLint activeAttributeCount = 0;
if (_programId != UNDEFINED_OPENGL_RESOURCE_ID)
{
glGetProgramiv(_programId, GL_ACTIVE_ATTRIBUTES, &activeAttributeCount);
}
return activeAttributeCount > 0;
}
void GlslProgram::unbind() const
{
glUseProgram(UNDEFINED_OPENGL_RESOURCE_ID);
}
const GlslProgram::InputMap& GlslProgram::getUniformsList()
{
return updateUniformsList();
}
const GlslProgram::InputMap& GlslProgram::getAttributesList()
{
return updateAttributesList();
}
const GlslProgram::InputMap& GlslProgram::updateUniformsList()
{
if (_uniformList.size() > 0)
{
return _uniformList;
}
if (_programId == UNDEFINED_OPENGL_RESOURCE_ID)
{
throw ExceptionRenderError("Cannot parse for uniforms without a valid program");
}
// Scan for textures
int uniformCount = -1;
int uniformSize = -1;
GLenum uniformType = 0;
int maxNameLength = 0;
glGetProgramiv(_programId, GL_ACTIVE_UNIFORMS, &uniformCount);
glGetProgramiv(_programId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxNameLength);
char* uniformName = new char[maxNameLength];
for (int i = 0; i < uniformCount; i++)
{
glGetActiveUniform(_programId, GLuint(i), maxNameLength, nullptr, &uniformSize, &uniformType, uniformName);
GLint uniformLocation = glGetUniformLocation(_programId, uniformName);
if (uniformLocation >= 0)
{
InputPtr inputPtr = std::make_shared<Input>(uniformLocation, uniformType, uniformSize, EMPTY_STRING);
_uniformList[string(uniformName)] = inputPtr;
}
}
delete[] uniformName;
if (_shader)
{
StringVec errors;
// Check for any type mismatches between the program and the h/w shader.
// i.e the type indicated by the HwShader does not match what was generated.
bool uniformTypeMismatchFound = false;
const ShaderStage& ps = _shader->getStage(Stage::PIXEL);
const ShaderStage& vs = _shader->getStage(Stage::VERTEX);
// Process constants
const VariableBlock& constants = ps.getConstantBlock();
for (size_t i = 0; i < constants.size(); ++i)
{
const ShaderPort* v = constants[i];
// There is no way to match with an unnamed variable
if (v->getVariable().empty())
{
continue;
}
// TODO: Should we really create new ones here each update?
InputPtr inputPtr = std::make_shared<Input>(-1, -1, int(v->getType().getSize()), EMPTY_STRING);
_uniformList[v->getVariable()] = inputPtr;
inputPtr->isConstant = true;
inputPtr->value = v->getValue();
inputPtr->typeString = v->getType().getName();
inputPtr->path = v->getPath();
}
// Process pixel stage uniforms
for (const auto& uniformMap : ps.getUniformBlocks())
{
const VariableBlock& uniforms = *uniformMap.second;
if (uniforms.getName() == HW::LIGHT_DATA)
{
// Need to go through LightHandler to match with uniforms
continue;
}
for (size_t uniformIndex = 0; uniformIndex < uniforms.size(); ++uniformIndex)
{
const ShaderPort* v = uniforms[uniformIndex];
const auto& variablePath = v->getPath();
const auto& variableUnit = v->getUnit();
const auto& variableColorspace = v->getColorSpace();
const auto& variableSemantic = v->getSemantic();
const auto populateUniformInput =
[this, variablePath, variableUnit, variableColorspace, variableSemantic, &errors, uniforms, &uniformTypeMismatchFound]
(TypeDesc typedesc, const string& variableName, ConstValuePtr variableValue) -> void
{
auto populateUniformInput_impl =
[this, variablePath, variableUnit, variableColorspace, variableSemantic, &errors, uniforms, &uniformTypeMismatchFound]
(TypeDesc typedesc_impl, const string& variableName_impl, ConstValuePtr variableValue_impl, auto& populateUniformInput_ref) -> void
{
if (!typedesc_impl.isStruct())
{
// Handle non-struct types
int glType = mapTypeToOpenGLType(typedesc_impl);
// There is no way to match with an unnamed variable
if (variableName_impl.empty())
{
return;
}
// Ignore types which are unsupported in GLSL.
if (glType == Input::INVALID_OPENGL_TYPE)
{
return;
}
auto inputIt = _uniformList.find(variableName_impl);
if (inputIt != _uniformList.end())
{
Input* input = inputIt->second.get();
input->path = variablePath;
input->unit = variableUnit;
input->colorspace = variableColorspace;
input->value = variableValue_impl;
if (input->gltype == glType)
{
input->typeString = typedesc_impl.getName();
}
else
{
errors.push_back(
"Pixel shader uniform block type mismatch [" + uniforms.getName() + "]. "
+ "Name: \"" + variableName_impl
+ "\". Type: \"" + typedesc_impl.getName()