44 #include <ACG/GL/acg_glew.hh> 45 #include "ShaderGenerator.hh" 52 #include <QTextStream> 60 std::vector<ShaderModifier*> ShaderProgGenerator::registeredModifiers_;
70 ShaderGenerator::Keywords::Keywords()
72 : macro_requestPosVS(
"#define SG_REQUEST_POSVS"),
73 macro_requestPosOS(
"#define SG_REQUEST_POSOS"),
74 macro_requestTexcoord(
"#define SG_REQUEST_TEXCOORD"),
75 macro_requestVertexColor(
"#define SG_REQUEST_VERTEXCOLOR"),
76 macro_requestNormalVS(
"#define SG_REQUEST_NORMALVS"),
77 macro_requestNormalOS(
"#define SG_REQUEST_NORMALOS"),
81 macro_inputPosVS(
"SG_INPUT_POSVS"),
82 macro_inputPosOS(
"SG_INPUT_POSOS"),
83 macro_inputPosCS(
"SG_INPUT_POSCS"),
84 macro_inputNormalVS(
"SG_INPUT_NORMALVS"),
85 macro_inputNormalOS(
"SG_INPUT_NORMALOS"),
86 macro_inputTexcoord(
"SG_INPUT_TEXCOORD"),
87 macro_inputVertexColor(
"SG_INPUT_VERTEXCOLOR"),
89 macro_outputPosVS(
"SG_OUTPUT_POSVS"),
90 macro_outputPosOS(
"SG_OUTPUT_POSOS"),
91 macro_outputPosCS(
"SG_OUTPUT_POSCS"),
92 macro_outputNormalVS(
"SG_OUTPUT_NORMALVS"),
93 macro_outputNormalOS(
"SG_OUTPUT_NORMALOS"),
94 macro_outputTexcoord(
"SG_OUTPUT_TEXCOORD"),
95 macro_outputVertexColor(
"SG_OUTPUT_VERTEXCOLOR"),
100 ioNormalVS(
"NormalVS"),
101 ioNormalOS(
"NormalOS"),
102 ioTexcoord(
"TexCoord"),
105 vs_inputPrefix(
"in"),
106 vs_outputPrefix(
"outVertex"),
107 tcs_outputPrefix(
"outTc"),
108 tes_outputPrefix(
"outTe"),
109 gs_outputPrefix(
"outGeometry"),
110 fs_outputPrefix(
"outFragment"),
112 vs_inputPosition(vs_inputPrefix +
"Position"),
113 vs_inputNormal(vs_inputPrefix +
"Normal"),
114 vs_inputTexCoord(vs_inputPrefix + ioTexcoord),
115 vs_inputColor(vs_inputPrefix + ioColor),
117 vs_outputPosCS(vs_outputPrefix + ioPosCS),
118 vs_outputPosVS(vs_outputPrefix + ioPosVS),
119 vs_outputPosOS(vs_outputPrefix + ioPosOS),
120 vs_outputTexCoord(vs_outputPrefix + ioTexcoord),
121 vs_outputNormalVS(vs_outputPrefix + ioNormalVS),
122 vs_outputNormalOS(vs_outputPrefix + ioNormalOS),
123 vs_outputVertexColor(vs_outputPrefix + ioColor),
124 fs_outputFragmentColor(fs_outputPrefix)
128 const ShaderGenerator::Keywords ShaderGenerator::keywords;
131 ShaderGenerator::ShaderGenerator()
132 : version_(150), inputArrays_(false), outputArrays_(false)
136 ShaderGenerator::~ShaderGenerator()
145 inputArrays_ =
false;
146 outputArrays_ =
false;
147 inputPrefix_ = keywords.vs_inputPrefix;
148 outputPrefix_ = keywords.vs_outputPrefix;
150 addInput(
"vec4", keywords.vs_inputPosition);
151 addOutput(
"vec4", keywords.vs_outputPosCS);
153 if (_iodesc->inputNormal_)
154 addInput(
"vec3", keywords.vs_inputNormal);
156 if (_desc->textured())
158 std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = _desc->textureTypes().begin();
161 if (iter->second.type == GL_TEXTURE_3D) {
162 addInput(
"vec3", keywords.vs_inputTexCoord);
163 addOutput(
"vec3", keywords.vs_outputTexCoord);
165 addInput(
"vec2", keywords.vs_inputTexCoord);
166 addOutput(
"vec2", keywords.vs_outputTexCoord);
170 if (_iodesc->inputColor_)
171 addInput(
"vec4", keywords.vs_inputColor);
173 if (_iodesc->passNormalVS_)
176 if (_iodesc->passNormalOS_)
184 if (_desc->shadeMode == SG_SHADE_FLAT)
186 if (!_desc->geometryTemplateFile.isEmpty())
187 strColorOut = keywords.vs_outputVertexColor;
191 addStringToList(
"vec4 " + keywords.vs_outputVertexColor, &outputs_,
"flat out ",
"; ");
194 else if (_desc->shadeMode == SG_SHADE_GOURAUD || _desc->vertexColors || _iodesc->inputColor_)
195 strColorOut = keywords.vs_outputVertexColor;
197 if (strColorOut.size())
198 addOutput(
"vec4", strColorOut);
201 addStringToList(
"vec4 " + keywords.vs_outputVertexColor, &outputs_, _desc->vertexColorsInterpolator +
" out ",
";");
207 if (_iodesc->passPosVS_)
208 addOutput(
"vec4", keywords.vs_outputPosVS);
210 if (_iodesc->passPosOS_)
211 addOutput(
"vec4", keywords.vs_outputPosOS);
213 if (_iodesc->passTexCoord_ && !_desc->textured())
218 if (_desc->texGenMode && _desc->texGenDim > 0 && _desc->texGenDim <= 4 && !_desc->texGenPerFragment)
219 texdim = _desc->texGenDim;
221 QString texcoordType;
223 texcoordType =QString(
"vec%1").arg(texdim);
225 texcoordType =
"float";
227 addInput(texcoordType, keywords.vs_inputTexCoord);
228 addOutput(texcoordType, keywords.vs_outputTexCoord);
232 defineIOAbstraction(_iodesc,
true,
false);
239 outputArrays_ =
true;
241 outputPrefix_ = keywords.tcs_outputPrefix;
243 matchInputs(_prevStage,
true, inputPrefix_, outputPrefix_);
245 defineIOAbstraction(_iodesc,
false,
false);
252 outputArrays_ =
false;
254 outputPrefix_ = keywords.tes_outputPrefix;
256 matchInputs(_prevStage,
true, inputPrefix_, outputPrefix_);
258 defineIOAbstraction(_iodesc,
false,
false);
265 outputArrays_ =
false;
267 outputPrefix_ = keywords.gs_outputPrefix;
269 matchInputs(_prevStage,
true, inputPrefix_, outputPrefix_);
271 defineIOAbstraction(_iodesc,
false,
false);
279 inputArrays_ =
false;
280 outputArrays_ =
false;
282 outputPrefix_ = keywords.fs_outputPrefix;
284 matchInputs(_prevStage,
false);
285 addOutput(
"vec4", keywords.fs_outputFragmentColor);
287 defineIOAbstraction(_iodesc,
false,
true);
297 addIODefine(keywords.macro_inputPosOS, keywords.vs_inputPosition);
300 addIODefine(keywords.macro_inputTexcoord, keywords.vs_inputTexCoord);
302 if (_iodesc->inputNormal_)
303 addIODefine(keywords.macro_inputNormalOS, keywords.vs_inputNormal);
305 if (_iodesc->inputColor_)
306 addIODefine(keywords.macro_inputVertexColor, keywords.vs_inputColor);
312 addIODefine(keywords.macro_outputPosCS, keywords.vs_outputPosCS);
315 addIODefine(keywords.macro_outputPosVS, keywords.vs_outputPosVS);
317 if (_iodesc->passPosOS_)
318 addIODefine(keywords.macro_outputPosOS, keywords.vs_outputPosOS);
320 if (_iodesc->passTexCoord_)
321 addIODefine(keywords.macro_outputTexcoord, keywords.vs_outputTexCoord);
323 if (_iodesc->passNormalVS_)
324 addIODefine(keywords.macro_outputNormalVS, keywords.vs_outputNormalVS);
326 if (_iodesc->passNormalOS_)
327 addIODefine(keywords.macro_outputNormalOS, keywords.vs_outputNormalOS);
329 if (_iodesc->passColor_)
330 addIODefine(keywords.macro_outputVertexColor, keywords.vs_outputVertexColor);
336 addIODefine(keywords.macro_inputPosVS, inputPrefix_ + keywords.ioPosVS);
338 addIODefine(keywords.macro_outputPosVS, outputPrefix_ + keywords.ioPosVS);
341 if (_iodesc->passPosOS_)
343 addIODefine(keywords.macro_inputPosOS, inputPrefix_ + keywords.ioPosOS);
345 addIODefine(keywords.macro_outputPosOS, outputPrefix_ + keywords.ioPosOS);
348 addIODefine(keywords.macro_inputPosCS, inputPrefix_ + keywords.ioPosCS);
350 addIODefine(keywords.macro_outputPosCS, outputPrefix_ + keywords.ioPosCS);
352 if (_iodesc->passNormalVS_)
354 addIODefine(keywords.macro_inputNormalVS, inputPrefix_ + keywords.ioNormalVS);
356 addIODefine(keywords.macro_outputNormalVS, outputPrefix_ + keywords.ioNormalVS);
359 if (_iodesc->passNormalOS_)
361 addIODefine(keywords.macro_inputNormalOS, inputPrefix_ + keywords.ioNormalOS);
363 addIODefine(keywords.macro_outputNormalOS, outputPrefix_ + keywords.ioNormalOS);
366 if (_iodesc->passTexCoord_)
368 addIODefine(keywords.macro_inputTexcoord, inputPrefix_ + keywords.ioTexcoord);
370 addIODefine(keywords.macro_outputTexcoord, outputPrefix_ + keywords.ioTexcoord);
373 if (_iodesc->passColor_)
375 addIODefine(keywords.macro_inputVertexColor, inputPrefix_ + keywords.ioColor);
377 addIODefine(keywords.macro_outputVertexColor, outputPrefix_ + keywords.ioColor);
388 addUniform(
"mat4 g_mWVP" ,
" // Projection * Modelview");
389 addUniform(
"mat4 g_mWV" ,
" // Modelview matrix");
390 addUniform(
"mat3 g_mWVIT" ,
" // Modelview inverse transposed");
391 addUniform(
"mat4 g_mP",
" // Projection matrix");
393 addUniform(
"vec3 g_vCamPos");
394 addUniform(
"vec3 g_vCamDir");
396 addUniform(
"vec3 g_cDiffuse");
397 addUniform(
"vec3 g_cAmbient");
398 addUniform(
"vec3 g_cEmissive");
399 addUniform(
"vec3 g_cSpecular");
400 addUniform(
"vec4 g_vMaterial");
401 addUniform(
"vec3 g_cLightModelAmbient");
405 #define ADDLIGHT(x) addUniform( QString( QString(x) + "_%1").arg(lightIndex_) ) 411 QTextStream stream(&sz);
413 ADDLIGHT(
"vec3 g_cLightDiffuse");
414 ADDLIGHT(
"vec3 g_cLightAmbient");
415 ADDLIGHT(
"vec3 g_cLightSpecular");
417 if (_light == SG_LIGHT_POINT ||
418 _light == SG_LIGHT_SPOT)
420 ADDLIGHT(
"vec3 g_vLightPos");
421 ADDLIGHT(
"vec3 g_vLightAtten");
424 if (_light == SG_LIGHT_DIRECTIONAL ||
425 _light == SG_LIGHT_SPOT)
426 ADDLIGHT(
"vec3 g_vLightDir");
429 if (_light == SG_LIGHT_SPOT)
430 ADDLIGHT(
"vec2 g_vLightAngleExp");
443 if (!_str.startsWith(_prefix))
446 if (!_str.endsWith(_postfix))
451 tmp = tmp.simplified();
454 if (!_arr->contains(tmp))
455 _arr->push_back(tmp);
462 addStringToList(_input, &inputs_,
"in ",
";");
468 addStringToList(_output, &outputs_,
"out ",
";");
474 addStringToList(_def, &genDefines_,
"#define ");
480 addDefine(_macroName + QString(
" ") + _resolvedName);
488 typedef std::reverse_iterator<QStringList::const_iterator> QStringListReverseIterator;
489 QStringListReverseIterator rbegin( _macros.end() ), rend( _macros.begin() );
491 for (QStringListReverseIterator it = rbegin; it != rend; ++it)
492 genDefines_.push_front(*it);
497 if (genDefines_.contains(_define))
502 QString trimmedDef = _define.trimmed();
504 for (QStringList::const_iterator it = genDefines_.constBegin(); it != genDefines_.constEnd(); ++it)
506 QString trimmedRef = it->trimmed();
508 if (trimmedRef.startsWith(trimmedDef))
513 for (QStringList::const_iterator it = rawIO_.constBegin(); it != rawIO_.constEnd(); ++it)
515 QString trimmedRef = it->trimmed();
517 if (trimmedRef.startsWith(trimmedDef))
526 addStringToList(_def, &layouts_);
533 if (!_uniform.startsWith(
"uniform ") && !_uniform.contains(
" uniform "))
536 addStringToList(_uniform, &uniforms_, prefix,
"; " + _comment );
549 if (!it.contains(
";"))
550 code_.back().append(
";");
558 QString glslversion = QString(
"#version %1").arg(version_);
560 code_.push_back(glslversion);
565 foreach(it, genDefines_)
569 foreach(it, layouts_)
573 addIOToCode(inputs_);
574 addIOToCode(outputs_);
575 addIOToCode(uniforms_);
578 bool requiresLightingCode =
false;
581 foreach(it, imports_)
583 if (it.contains(
"LitDirLight") || it.contains(
"LitPointLight") || it.contains(
"LitSpotLight"))
584 requiresLightingCode =
true;
587 if (requiresLightingCode)
589 foreach(it, _defaultLightingFunctions)
594 foreach(it, imports_)
600 if (!requiresLightingCode)
602 foreach(it, (*_pMainCode))
604 if (it.contains(
"LitDirLight") || it.contains(
"LitPointLight") || it.contains(
"LitSpotLight"))
605 requiresLightingCode =
true;
608 if (requiresLightingCode)
610 foreach(it, _defaultLightingFunctions)
617 code_.append(rawIO_);
621 foreach(it, (*_pMainCode))
629 QFile file(_fileName);
631 if (file.open(QIODevice::ReadOnly | QIODevice::Text))
633 QTextStream fileStream(&file);
637 imports_.push_back(
"// ==============================================================================");
638 imports_.push_back(QString(
"// ShaderGenerator - begin of imported file: ") + _fileName);
641 while (!fileStream.atEnd())
643 QString tmpLine = fileStream.readLine();
645 imports_.push_back(tmpLine.simplified());
651 imports_.push_back(QString(
"// ShaderGenerator - end of imported file #include \"") + _fileName);
652 imports_.push_back(
"// ==============================================================================");
662 QFile file(_fileName);
663 if (file.open(QIODevice::WriteOnly | QIODevice::Text))
665 QTextStream fileStream(&file);
669 fileStream << it <<
'\n';
686 bool _passToNextStage,
687 QString _inputPrefix,
688 QString _outputPrefix)
690 if (!_previousShaderStage)
692 std::cout <<
"error: ShaderGenerator::matchInputs called without providing input stage" << std::endl;
697 foreach(it, _previousShaderStage->outputs_)
701 QString outKeyword =
"out ";
702 QString inKeyword =
"in ";
705 input.replace(input.indexOf(outKeyword), outKeyword.size(), inKeyword);
711 QRegExp alphaNum(
"[a-zA-Z0-9]");
712 int lastNameChar = input.lastIndexOf(alphaNum);
713 input.insert(lastNameChar+1,
"[]");
719 addStringToList(input, &inputs_);
721 if (_passToNextStage)
725 QString output = input;
726 output.replace(output.indexOf(_inputPrefix), _inputPrefix.size(), _outputPrefix);
727 output.replace(output.indexOf(inKeyword), inKeyword.size(), outKeyword);
730 if (inputArrays_ && !outputArrays_)
732 int bracketStart = output.indexOf(
"[");
733 int bracketEnd = output.indexOf(
"]");
734 output.remove(bracketStart, bracketEnd-bracketStart+1);
736 else if (!inputArrays_ && outputArrays_)
738 QRegExp alphaNum(
"[a-zA-Z0-9]");
739 int lastNameChar = output.lastIndexOf(alphaNum);
740 output.insert(lastNameChar+1,
"[]");
746 addStringToList(output, &outputs_);
753 return outputs_.size();
758 QString output = outputs_.at(_id);
761 output.remove(
"out ");
763 int bracketStart = output.indexOf(
"[");
764 int bracketEnd = output.lastIndexOf(
"]");
766 if (bracketStart >= 0)
767 output.remove(bracketStart, bracketEnd-bracketStart+1);
770 QStringList decompOutput = output.split(
" ");
771 return decompOutput.last();
776 return inputs_.size();
781 QString input = inputs_.at(_id);
784 input.remove(
"out ");
786 int bracketStart = input.indexOf(
"[");
787 int bracketEnd = input.lastIndexOf(
"]");
789 if (bracketStart >= 0)
790 input.remove(bracketStart, bracketEnd-bracketStart+1);
793 QStringList decompInput = input.split(
" ");
794 return decompInput.last();
799 QString inputName = getInputName(_inId);
802 QString outputName = inputName;
803 outputName.replace(outputName.indexOf(inputPrefix_), inputPrefix_.size(), outputPrefix_);
809 ShaderGenerator::DefaultIODesc::DefaultIODesc()
810 : inputTexCoord_(
false),
813 passPosVS_(
false), passPosOS_(
false),
814 passTexCoord_(
false),
816 passNormalVS_(
false), passNormalOS_(
false)
823 QString ShaderProgGenerator::shaderDir_;
824 QStringList ShaderProgGenerator::lightingCode_;
828 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
834 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
836 init(_desc, _modifierIDs, _numActiveMods);
840 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
842 init(_desc, _modifierIDs.empty() ? 0 : &_modifierIDs[0], (
unsigned int)_modifierIDs.size());
846 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
848 unsigned int numMods = !_modifierIDs || _modifierIDs->empty() ? 0 : (
unsigned int)_modifierIDs->size();
849 init(_desc, numMods ? &((*_modifierIDs)[0]) : 0, numMods);
853 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
855 init(_desc, _modifiers, _numActiveMods);
859 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
861 init(_desc, _modifierIDs.empty() ? 0 : &(_modifierIDs[0]), (
unsigned int)_modifierIDs.size());
865 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0)
867 unsigned int numMods = !_modifierIDs || _modifierIDs->empty() ? 0 : (
unsigned int)_modifierIDs->size();
868 init(_desc, numMods ? &((*_modifierIDs)[0]) : 0, numMods);
874 if (_modifierIDs && _numActiveMods)
876 activeMods_.resize(_numActiveMods);
878 for (
unsigned int i = 0; i < _numActiveMods; ++i)
879 activeMods_[i] = registeredModifiers_[ _modifierIDs[i] ];
890 size_t numDescMods = _desc->shaderMods.size();
891 size_t numTotalMods = _numActiveMods + numDescMods;
894 activeMods_.resize(numTotalMods);
896 for (
size_t i = 0; i < numDescMods; ++i)
898 unsigned int modID = _desc->shaderMods[i];
899 activeMods_[i] = registeredModifiers_[modID];
902 if (_modifiers && _numActiveMods)
904 for (
unsigned int i = 0; i < _numActiveMods; ++i)
905 activeMods_[i + numDescMods] = _modifiers[i];
912 if (shaderDir_.isEmpty())
913 std::cout <<
"error: call ShaderProgGenerator::setShaderDir() first!" << std::endl;
921 if (!desc_.geometryTemplateFile.isEmpty())
922 std::cerr <<
"Warning: removing geometry shader from ShaderDesc" << std::endl;
924 desc_.geometryTemplateFile.clear();
930 if (!desc_.tessControlTemplateFile.isEmpty() || !desc_.tessEvaluationTemplateFile.isEmpty())
931 std::cerr <<
"Warning: removing tessellation shader from ShaderDesc" << std::endl;
933 desc_.tessControlTemplateFile.clear();
934 desc_.tessEvaluationTemplateFile.clear();
939 if (!desc_.geometryTemplateFile.isEmpty())
940 desc_.version = std::max(desc_.version, 150);
942 if (!desc_.tessControlTemplateFile.isEmpty() || !desc_.tessEvaluationTemplateFile.isEmpty())
943 desc_.version = std::max(desc_.version, 400);
946 loadLightingFunctions();
953 ShaderProgGenerator::~ShaderProgGenerator(
void)
966 bool success =
false;
971 QFile file(absFilename);
973 if (file.open(QIODevice::ReadOnly | QIODevice::Text))
975 if (!file.isReadable())
976 std::cout <<
"error: unreadable file -> \"" << absFilename.toStdString() <<
"\"" << std::endl;
979 QTextStream filestream(&file);
981 while (!filestream.atEnd())
983 QString szLine = filestream.readLine();
984 _out->push_back(szLine.trimmed());
993 std::cout <<
"error: " << file.errorString().toStdString() <<
" -> \"" << absFilename.toStdString() <<
"\"" << std::endl;
999 void ShaderProgGenerator::loadLightingFunctions()
1001 if (lightingCode_.size())
return;
1003 static const QString lightingCodeFile =
"ShaderGen/SG_LIGHTING.GLSL";
1005 QString fileName = shaderDir_ + QDir::separator() + QString(lightingCodeFile);
1007 lightingCode_.push_back(
"// ==============================================================================");
1008 lightingCode_.push_back(QString(
"// ShaderGenerator - default lighting functions imported from file: ") + fileName);
1014 lightingCode_.push_back(QString(
"// ShaderGenerator - end of default lighting functions"));
1015 lightingCode_.push_back(
"// ==============================================================================");
1022 switch (desc_.shadeMode)
1024 case SG_SHADE_GOURAUD:
1028 case SG_SHADE_UNLIT:
1030 case SG_SHADE_PHONG:
1034 std::cout << __FUNCTION__ <<
" -> unknown shade mode: " << desc_.shadeMode << std::endl;
1037 if (desc_.twoSidedLighting)
1038 _gen->
addDefine(
"TWO_SIDED_LIGHTING 1");
1040 if (desc_.textured())
1043 if (desc_.vertexColors)
1057 QString strNumLights = QString(
"SG_NUM_LIGHTS %1").arg(desc_.numLights);
1061 const char* lightTypeNames[] = {
"SG_LIGHT_DIRECTIONAL",
1062 "SG_LIGHT_POINT",
"SG_LIGHT_SPOT"};
1064 for (
int i = 0; i < 3; ++i)
1068 for (
int i = 0; i < desc_.numLights; ++i) {
1069 _gen->
addDefine( QString (
"SG_LIGHT_TYPE_%1 %2").arg(i).arg(lightTypeNames[desc_.lightTypes[i]]) );
1072 _gen->
addDefine(
"SG_ALPHA g_vMaterial.y");
1073 _gen->
addDefine(
"SG_MINALPHA g_vMaterial.z");
1082 void ShaderProgGenerator::buildVertexShader()
1094 if (desc_.texGenDim && (desc_.texGenMode == GL_OBJECT_LINEAR || desc_.texGenMode == GL_EYE_LINEAR) && !desc_.texGenPerFragment)
1097 QString uniformDecl =
"vec4 g_vTexGenPlane";
1098 if (desc_.texGenDim > 1)
1099 uniformDecl +=
"[" + QString::number(desc_.texGenDim) +
"]";
1100 vertex_->
addUniform(uniformDecl,
" // texture projection planes");
1105 for (
size_t i = 0; i < activeMods_.size(); ++i)
1106 activeMods_[i]->modifyVertexIO(vertex_);
1116 if (desc_.shadeMode == SG_SHADE_GOURAUD ||
1117 desc_.shadeMode == SG_SHADE_FLAT)
1119 for (
int i = 0; i < desc_.numLights; ++i)
1120 vertex_->
addLight(i, desc_.lightTypes[i]);
1125 QStringList mainCode;
1127 if (!vertexTemplate_.size())
1129 mainCode.push_back(
"void main()");
1130 mainCode.push_back(
"{");
1132 addVertexBeginCode(&mainCode);
1133 addVertexEndCode(&mainCode);
1135 mainCode.push_back(
"}");
1143 foreach(it,vertexTemplate_)
1150 if (it.contains(
"SG_VERTEX_BEGIN"))
1151 addVertexBeginCode(&mainCode);
1154 if (it.contains(
"SG_VERTEX_END"))
1155 addVertexEndCode(&mainCode);
1159 mainCode.push_back(it);
1173 void ShaderProgGenerator::addVertexBeginCode(QStringList* _code)
1177 _code->push_back(QString(
"vec4 sg_vPosPS = g_mWVP * ") + ShaderGenerator::keywords.macro_inputPosOS + QString(
";"));
1178 _code->push_back(
"vec4 sg_vPosVS = g_mWV * inPosition;");
1179 _code->push_back(
"vec3 sg_vNormalVS = vec3(0.0, 1.0, 0.0);");
1180 _code->push_back(
"vec3 sg_vNormalOS = vec3(0.0, 1.0, 0.0);");
1182 if (desc_.vertexColors && (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE))
1183 _code->push_back(QString(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * ")
1184 + ShaderGenerator::keywords.macro_inputVertexColor
1185 + QString(
".rgb, SG_ALPHA * ")
1186 + ShaderGenerator::keywords.macro_inputVertexColor
1189 _code->push_back(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * g_cAmbient, SG_ALPHA);");
1193 _code->push_back(
"sg_vNormalVS = normalize(g_mWVIT * inNormal);");
1194 _code->push_back(
"sg_vNormalOS = normalize(inNormal);");
1197 if (
ioDesc_.inputColor_ && (desc_.shadeMode == SG_SHADE_UNLIT || desc_.colorMaterialMode == GL_EMISSION))
1198 _code->push_back(QString(
"sg_cColor = ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(
";"));
1205 for (
size_t i = 0; i < activeMods_.size(); ++i)
1206 activeMods_[i]->modifyVertexBeginCode(_code);
1210 void ShaderProgGenerator::addVertexEndCode(QStringList* _code)
1212 if (desc_.shadeMode == SG_SHADE_GOURAUD ||
1213 desc_.shadeMode == SG_SHADE_FLAT)
1220 _code->push_back(
"gl_Position = sg_vPosPS;");
1221 _code->push_back(
"outVertexPosCS = sg_vPosPS;");
1224 _code->push_back(
"outVertexTexCoord = sg_vTexCoord;");
1227 _code->push_back(
"outVertexColor = sg_cColor;");
1230 _code->push_back(ShaderGenerator::keywords.macro_outputNormalVS + QString(
" = sg_vNormalVS;"));
1233 _code->push_back(ShaderGenerator::keywords.macro_outputNormalOS + QString(
" = sg_vNormalOS;"));
1236 _code->push_back(ShaderGenerator::keywords.macro_outputPosVS + QString(
" = sg_vPosVS;"));
1239 _code->push_back(ShaderGenerator::keywords.macro_outputPosOS + QString(
" = ") + ShaderGenerator::keywords.macro_inputPosOS + QString(
";"));
1244 for (
size_t i = 0; i < activeMods_.size(); ++i)
1245 activeMods_[i]->modifyVertexEndCode(_code);
1251 if (_str.contains(
"#include "))
1253 QString strIncludeFile = _str.remove(
"#include ").remove(
'\"').remove(
'<').remove(
'>').trimmed();
1255 if (strIncludeFile.isEmpty())
1256 std::cout <<
"wrong include syntax: " << _str.toStdString() << std::endl;
1259 QString fullPathToIncludeFile = _includePath + QDir::separator() + strIncludeFile;
1272 if (_str.contains(
"#include "))
1274 QString strIncludeFile = _str.remove(
"#include ").remove(
'\"').remove(
'<').remove(
'>').trimmed();
1276 if (strIncludeFile.isEmpty())
1277 std::cout <<
"wrong include syntax: " << _str.toStdString() << std::endl;
1280 QString fullPathToIncludeFile = _includePath + QDir::separator() + strIncludeFile;
1283 fullPathToIncludeFile.replace(
'\\',
'/');
1286 QString cleanFilepath = QDir::cleanPath(fullPathToIncludeFile);
1297 void ShaderProgGenerator::buildTessControlShader()
1300 if ( desc_.tessControlTemplateFile.isEmpty() )
1310 delete tessControl_;
1328 for (
size_t i = 0; i < activeMods_.size(); ++i)
1329 activeMods_[i]->modifyTessControlIO(tessControl_);
1336 QStringList mainCode;
1342 mainCode.push_back(
"#define sg_MapIO(inIdx) do {\\");
1345 mainCode.push_back(
"gl_out[gl_InvocationID].gl_Position = gl_in[inIdx].gl_Position;\\");
1353 QString outputAssignCode = outputName + QString(
"[gl_InvocationID] = ") + inputName + QString(
"[inIdx];\\");
1355 mainCode.push_back(outputAssignCode);
1359 mainCode.push_back(
"} while(false)");
1365 foreach(it,tessControlTemplate_)
1370 mainCode.push_back(it);
1377 void ShaderProgGenerator::buildTessEvalShader()
1380 if ( desc_.tessEvaluationTemplateFile.isEmpty() )
1401 prevStage = vertex_;
1408 foreach(itLayout, tessEvalLayout_)
1412 for (
size_t i = 0; i < activeMods_.size(); ++i)
1413 activeMods_[i]->modifyTessControlIO(tessEval_);
1419 QStringList mainCode;
1426 mainCode.push_back(
"void sg_MapIOBarycentric()");
1427 mainCode.push_back(
"{");
1430 mainCode.push_back(
"gl_Position = gl_TessCoord.x * gl_in[0].gl_Position + gl_TessCoord.y * gl_in[1].gl_Position + gl_TessCoord.z * gl_in[2].gl_Position;");
1438 QString outputAssignCode = outputName + QString(
" = ") +
1439 QString(
"gl_TessCoord.x*") + inputName + QString(
"[0] + ") +
1440 QString(
"gl_TessCoord.y*") + inputName + QString(
"[1] + ") +
1441 QString(
"gl_TessCoord.z*") + inputName + QString(
"[2];");
1443 mainCode.push_back(outputAssignCode);
1446 mainCode.push_back(
"}");
1451 mainCode.push_back(
"void sg_MapIOBilinear()");
1452 mainCode.push_back(
"{");
1455 mainCode.push_back(
"gl_Position = mix( mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x), mix(gl_in[2].gl_Position, gl_in[3].gl_Position, gl_TessCoord.x), gl_TessCoord.y);");
1463 QString outputAssignCode = outputName + QString(
" = mix( ") +
1464 QString(
"mix(") + inputName + QString(
"[0], ") + inputName + QString(
"[1], gl_TessCoord.x), ") +
1465 QString(
"mix(") + inputName + QString(
"[2], ") + inputName + QString(
"[3], gl_TessCoord.x), gl_TessCoord.y); ");
1467 mainCode.push_back(outputAssignCode);
1470 mainCode.push_back(
"}");
1476 QStringList::iterator it;
1477 for (it = tessEvalTemplate_.begin(); it != tessEvalTemplate_.end(); ++it)
1486 if (line.contains(
"SG_INPUT") || line.contains(
"SG_OUTPUT"))
1489 QStringList resolvedCode;
1491 resolvedCode.push_back(
"// ----------------------------------------");
1492 resolvedCode.push_back(
"// ShaderGen: resolve SG_OUTPUT = expression(SG_INPUT);");
1494 int numOccurrences = 0;
1502 QString resolvedLine = line;
1512 for (
int k = 0; k < 2; ++k)
1514 const QString stringToReplace = k ?
"SG_OUTPUT" :
"SG_INPUT";
1515 const int lenStringToReplace = stringToReplace.length();
1516 const QString replacementString = k ? outputName : inputName;
1518 int linePos = resolvedLine.indexOf(stringToReplace);
1520 while (linePos >= 0)
1522 bool replaceOcc =
true;
1524 int nextCharPos = linePos + lenStringToReplace;
1526 if (nextCharPos >= resolvedLine.size())
1529 if (nextCharPos > 0)
1531 QChar nextChar = resolvedLine.at(nextCharPos);
1533 if (nextChar ==
'_' || nextChar.isDigit() || nextChar.isLetter())
1537 linePos += lenStringToReplace;
1546 resolvedLine.replace(linePos, lenStringToReplace, replacementString);
1550 linePos = resolvedLine.indexOf(stringToReplace, linePos + 1);
1558 resolvedCode.push_back(resolvedLine);
1561 resolvedCode.push_back(
"// ----------------------------------------");
1564 mainCode.append(resolvedCode);
1566 mainCode.push_back(line);
1569 mainCode.push_back(line);
1575 void ShaderProgGenerator::buildGeometryShader()
1578 if ( desc_.geometryTemplateFile.isEmpty() )
1592 prevStage = vertex_;
1600 for (
size_t i = 0; i < activeMods_.size(); ++i)
1601 activeMods_[i]->modifyGeometryIO(geometry_);
1607 QStringList mainCode;
1613 mainCode.push_back(
"#define sg_MapIO(inIdx) do {\\");
1616 mainCode.push_back(
"gl_Position = gl_in[inIdx].gl_Position;\\");
1617 mainCode.push_back(
"gl_PrimitiveID = gl_PrimitiveIDIn;\\");
1621 static int maxClipDistances = -1;
1622 if (maxClipDistances < 0)
1624 #ifdef GL_MAX_CLIP_DISTANCES 1625 glGetIntegerv(GL_MAX_CLIP_DISTANCES, &maxClipDistances);
1626 maxClipDistances = std::min(maxClipDistances, 32);
1628 maxClipDistances = 32;
1631 for (
int i = 0; i < maxClipDistances; ++i)
1633 if (desc_.clipDistanceMask & (1 << i))
1634 mainCode.push_back(QString(
"gl_ClipDistance[%1] = gl_in[inIdx].gl_ClipDistance[%1];\\").arg(i));
1643 QString outputAssignCode = outputName + QString(
" = ") + inputName + QString(
"[inIdx];\\");
1645 mainCode.push_back(outputAssignCode);
1649 mainCode.push_back(
"} while(false)");
1656 foreach(it,geometryTemplate_)
1661 mainCode.push_back(it);
1669 void ShaderProgGenerator::buildFragmentShader()
1680 prevStage = tessEval_;
1682 prevStage = tessControl_;
1684 prevStage = vertex_;
1689 if (desc_.texGenDim && (desc_.texGenMode == GL_OBJECT_LINEAR || desc_.texGenMode == GL_EYE_LINEAR) && desc_.texGenPerFragment)
1692 QString uniformDecl =
"vec4 g_vTexGenPlane";
1693 if (desc_.texGenDim > 1)
1694 uniformDecl +=
"[" + QString::number(desc_.texGenDim) +
"]";
1695 fragment_->
addUniform(uniformDecl,
" // texture projection planes");
1703 if (desc_.textured())
1705 for (std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = desc_.textureTypes().begin();
1706 iter != desc_.textureTypes().end(); ++iter)
1708 QString name = QString(
"g_Texture%1").arg(iter->first);
1710 switch (iter->second.type)
1712 case GL_TEXTURE_1D: type =
"sampler1D";
break;
1713 case GL_TEXTURE_2D: type =
"sampler2D";
break;
1714 case GL_TEXTURE_3D: type =
"sampler3D";
break;
1715 case GL_TEXTURE_CUBE_MAP: type =
"samplerCube";
break;
1716 #ifdef GL_ARB_texture_rectangle //ARCH_DARWIN doesn't support all texture defines with all xcode version (xcode 5.0 seems to support all) 1717 case GL_TEXTURE_RECTANGLE_ARB: type =
"sampler2DRect";
break;
1719 case GL_TEXTURE_BUFFER: type =
"samplerBuffer";
break;
1720 #ifdef GL_EXT_texture_array 1721 case GL_TEXTURE_1D_ARRAY_EXT: type =
"sampler1DArray";
break;
1722 case GL_TEXTURE_2D_ARRAY_EXT: type =
"sampler2DArray";
break;
1724 #ifdef GL_ARB_texture_cube_map_array 1725 case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: type =
"samplerCubeArray";
break;
1727 #ifdef GL_ARB_texture_multisample 1728 case GL_TEXTURE_2D_MULTISAMPLE: type =
"sampler2DMS";
break;
1729 case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: type =
"sampler2DMSArray";
break;
1731 default: std::cerr <<
"Texture Type not supported "<< iter->second.type << std::endl;
break;
1734 if (iter->second.shadow)
1741 for (
size_t i = 0; i < activeMods_.size(); ++i)
1742 activeMods_[i]->modifyFragmentIO(fragment_);
1752 if (desc_.shadeMode == SG_SHADE_PHONG)
1754 for (
int i = 0; i < desc_.numLights; ++i)
1755 fragment_->
addLight(i, desc_.lightTypes[i]);
1759 QStringList mainCode;
1761 if (!fragmentTemplate_.size())
1763 mainCode.push_back(
"void main()");
1764 mainCode.push_back(
"{");
1766 addFragmentBeginCode(&mainCode);
1767 addFragmentEndCode(&mainCode);
1769 mainCode.push_back(
"}");
1776 foreach(it,fragmentTemplate_)
1783 if (it.contains(
"SG_FRAGMENT_BEGIN"))
1784 addFragmentBeginCode(&mainCode);
1785 else if (it.contains(
"SG_FRAGMENT_END"))
1786 addFragmentEndCode(&mainCode);
1787 else if (it.contains(
"SG_FRAGMENT_LIGHTING"))
1790 mainCode.push_back(it);
1805 void ShaderProgGenerator::addFragmentBeginCode(QStringList* _code)
1808 _code->push_back(QString(
"vec4 sg_vPosCS = ") + ShaderGenerator::keywords.macro_inputPosCS + QString(
";"));
1809 _code->push_back(
"vec2 sg_vScreenPos = sg_vPosCS.xy / sg_vPosCS.w * 0.5 + vec2(0.5, 0.5);");
1811 _code->push_back(QString(
"#ifdef ") + ShaderGenerator::keywords.macro_inputPosVS);
1812 _code->push_back(QString(
"vec4 sg_vPosVS = ") + ShaderGenerator::keywords.macro_inputPosVS + QString(
";"));
1813 _code->push_back(
"#endif");
1815 _code->push_back(QString(
"#ifdef ") + ShaderGenerator::keywords.macro_inputNormalVS);
1816 _code->push_back(QString(
"vec3 sg_vNormalVS = ") + ShaderGenerator::keywords.macro_inputNormalVS + QString(
";"));
1817 _code->push_back(
"sg_vNormalVS = normalize(sg_vNormalVS);");
1818 _code->push_back(
"#endif");
1821 if (desc_.vertexColors && (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE))
1822 _code->push_back(QString(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * ")
1823 + ShaderGenerator::keywords.macro_inputVertexColor
1824 + QString(
".rgb, SG_ALPHA * ")
1825 + ShaderGenerator::keywords.macro_inputVertexColor
1828 _code->push_back(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * g_cAmbient, SG_ALPHA);");
1830 if (desc_.shadeMode == SG_SHADE_GOURAUD ||
1831 desc_.shadeMode == SG_SHADE_FLAT ||
1832 (
ioDesc_.passColor_ && (desc_.shadeMode == SG_SHADE_UNLIT || desc_.colorMaterialMode == GL_EMISSION)))
1833 _code->push_back(QString(
"sg_cColor = ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(
";"));
1835 _code->push_back(QString(
"if (sg_cColor.a < SG_MINALPHA) discard;"));
1836 if (desc_.shadeMode == SG_SHADE_PHONG)
1842 if (desc_.textured())
1844 std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = desc_.textureTypes().begin();
1845 _code->push_back(
"vec4 sg_cTex = texture(g_Texture"+QString::number(iter->first)+
", sg_vTexCoord);");
1847 for (++iter; iter != desc_.textureTypes().end(); ++iter)
1848 _code->push_back(
"sg_cTex += texture(g_Texture"+QString::number(iter->first)+
", sg_vTexCoord);");
1851 _code->push_back(
"sg_cTex = sg_cTex * 1.0/" + QString::number(desc_.textureTypes().size()) +
".0 ;");
1853 if (desc_.shadeMode == SG_SHADE_UNLIT)
1854 _code->push_back(
"sg_cColor += sg_cTex;");
1856 _code->push_back(
"sg_cColor *= sg_cTex;");
1861 for (
size_t i = 0; i < activeMods_.size(); ++i)
1862 activeMods_[i]->modifyFragmentBeginCode(_code);
1865 void ShaderProgGenerator::addFragmentEndCode(QStringList* _code)
1867 _code->push_back(ShaderGenerator::keywords.fs_outputFragmentColor + QString(
" = sg_cColor;"));
1870 for (
size_t i = 0; i < activeMods_.size(); ++i)
1871 activeMods_[i]->modifyFragmentEndCode(_code);
1882 for (
size_t i = 0; i < activeMods_.size() && !lightingModifier; ++i)
1884 if (activeMods_[i]->replaceDefaultLightingCode())
1885 lightingModifier = activeMods_[i];
1888 if (!lightingModifier)
1894 QString vertexColorString = (
ioDesc_.inputColor_ &&
ioDesc_.passColor_) ? (ShaderGenerator::keywords.macro_inputVertexColor + QString(
".xyz * ")) :
"";
1895 QString diffuseVertexColor = (desc_.colorMaterialMode == GL_DIFFUSE || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE) ? vertexColorString :
"";
1896 QString ambientVertexColor = (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE) ? vertexColorString :
"";
1897 QString specularVertexColor = (desc_.colorMaterialMode == GL_SPECULAR) ? vertexColorString :
"";
1899 for (
int i = 0; i < desc_.numLights; ++i)
1901 ShaderGenLightType lgt = desc_.lightTypes[i];
1905 case SG_LIGHT_DIRECTIONAL:
1907 buf = QString(
"sg_cColor.xyz += LitDirLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightDir_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
1910 case SG_LIGHT_POINT:
1912 buf = QString(
"sg_cColor.xyz += LitPointLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightPos_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1, g_vLightAtten_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
1917 buf = QString(
"sg_cColor.xyz += LitSpotLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightPos_%1, g_vLightDir_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1, g_vLightAtten_%1, g_vLightAngleExp_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
1923 _code->push_back(buf);
1928 for (
size_t i = 0; i < activeMods_.size(); ++i)
1939 for (
size_t i = 0; i < activeMods_.size(); ++i)
1941 if (lightingModifier != activeMods_[i])
1950 if (!_modifier)
return;
1952 for (
int i = 0; i < desc_.numLights; ++i)
1954 ShaderGenLightType lgt = desc_.lightTypes[i];
1964 foreach(it,lightingCode_)
1965 _code->push_back(it);
1972 int texcoordVarDim = 2;
1974 !desc_.textureTypes().empty() &&
1975 desc_.textureTypes().begin()->second.type == GL_TEXTURE_3D)
1978 bool generateTexCoord = desc_.texGenDim && desc_.texGenMode && (_fragmentShader == desc_.texGenPerFragment);
1979 if (generateTexCoord)
1980 texcoordVarDim = desc_.texGenDim;
1982 QString texcoordVarInit;
1983 if (texcoordVarDim == 1)
1984 texcoordVarInit =
"float sg_vTexCoord";
1986 texcoordVarInit = QString(
"vec%1 sg_vTexCoord").arg(texcoordVarDim);
1990 texcoordVarInit += QString(
"= ") + ShaderGenerator::keywords.macro_inputTexcoord + QString(
";");
1991 else if (0 <= texcoordVarDim && texcoordVarDim <= 4)
1993 QString zeroVecDefs[] =
2001 texcoordVarInit += zeroVecDefs[texcoordVarDim];
2004 _code->push_back(texcoordVarInit);
2009 if (generateTexCoord)
2012 const char* texGenCoordString[] = {
"x",
"y",
"z",
"w" };
2014 switch (desc_.texGenMode)
2016 case GL_OBJECT_LINEAR:
2018 for (
int i = 0; i < desc_.texGenDim; ++i)
2020 QString assignmentInstrString;
2021 assignmentInstrString =
"sg_vTexCoord";
2022 if (desc_.texGenDim > 1)
2024 assignmentInstrString +=
".";
2025 assignmentInstrString += texGenCoordString[i];
2027 assignmentInstrString +=
" = dot(";
2028 assignmentInstrString += ShaderGenerator::keywords.macro_inputPosOS;
2029 assignmentInstrString +=
", g_vTexGenPlane";
2030 if (desc_.texGenDim > 1)
2032 assignmentInstrString +=
"[";
2033 assignmentInstrString += QString::number(i);
2034 assignmentInstrString +=
"]";
2036 assignmentInstrString +=
");";
2037 _code->push_back(assignmentInstrString);
2043 for (
int i = 0; i < desc_.texGenDim; ++i)
2045 QString assignmentInstrString;
2046 assignmentInstrString =
"sg_vTexCoord";
2047 if (desc_.texGenDim > 1)
2049 assignmentInstrString +=
".";
2050 assignmentInstrString += texGenCoordString[i];
2052 assignmentInstrString +=
" = dot(sg_vPosVS, g_vTexGenPlane";
2053 if (desc_.texGenDim > 1)
2055 assignmentInstrString +=
"[";
2056 assignmentInstrString += QString::number(i);
2057 assignmentInstrString +=
"]";
2059 assignmentInstrString +=
");";
2060 _code->push_back(assignmentInstrString);
2067 _code->push_back(
"vec3 sg_vPosVS_unit = normalize(sg_vPosVS.xyz);");
2068 _code->push_back(
"vec3 sg_TexGenRefl = reflect(sg_vPosVS_unit, sg_vNormalVS);");
2069 _code->push_back(
"vec3 sg_TexGenRefl2 = sg_TexGenRefl; sg_TexGenRefl2.z += 1.0;");
2070 _code->push_back(
"float sg_TexGenMRcp = 0.5 * inversesqrt(dot(sg_TexGenRefl2, sg_TexGenRefl2));");
2071 for (
int i = 0; i < desc_.texGenDim; ++i)
2073 _code->push_back(QString (
"sg_vTexCoord.%1 = sg_TexGenRefl.%2 * sg_TexGenMRcp + 0.5;").arg(texGenCoordString[i]).arg(texGenCoordString[i]));
2079 for (
int i = 0; i < desc_.texGenDim; ++i)
2081 _code->push_back( QString (
"sg_vTexCoord.%1 = sg_vNormalVS.%2;").arg(texGenCoordString[i]).arg(texGenCoordString[i]) );
2085 case GL_REFLECTION_MAP:
2087 _code->push_back(
"vec3 sg_vPosVS_unit = normalize(sg_vPosVS.xyz);");
2088 _code->push_back(
"vec3 sg_TexGenRefl = reflect(sg_vPosVS_unit, sg_vNormalVS);");
2089 for (
int i = 0; i < desc_.texGenDim; ++i)
2092 _code->push_back( QString (
"sg_vTexCoord.%1 = sg_TexGenRefl.%2;").arg(texGenCoordString[i]).arg(texGenCoordString[i]) );
2109 if (desc_.shadeMode != SG_SHADE_UNLIT)
2112 if (desc_.textured())
2119 int maxTexGenDim = 4;
2121 switch (desc_.texGenMode)
2124 case GL_OBJECT_LINEAR: maxTexGenDim = 4;
break;
2126 case GL_SPHERE_MAP: maxTexGenDim = 2;
break;
2129 case GL_REFLECTION_MAP: maxTexGenDim = 3;
break;
2131 default: maxTexGenDim = 0;
break;
2134 desc_.texGenDim = std::max(std::min(desc_.texGenDim, maxTexGenDim), 0);
2137 if (desc_.texGenDim && desc_.texGenMode)
2140 if (!desc_.texGenPerFragment)
2144 if (desc_.texGenMode == GL_REFLECTION_MAP || desc_.texGenMode == GL_SPHERE_MAP || desc_.texGenMode == GL_NORMAL_MAP)
2148 if (desc_.texGenPerFragment)
2150 switch (desc_.texGenMode)
2152 case GL_OBJECT_LINEAR:
ioDesc_.passPosOS_ =
true;
break;
2155 case GL_NORMAL_MAP:
ioDesc_.passNormalVS_ =
true;
break;
2163 if (desc_.vertexColors)
2166 if (desc_.shadeMode == SG_SHADE_PHONG)
2172 if (desc_.shadeMode == SG_SHADE_FLAT || desc_.shadeMode == SG_SHADE_GOURAUD || desc_.vertexColors)
2180 for (
size_t i = 0; i < activeMods_.size(); ++i)
2192 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestPosVS))
2194 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestTexcoord))
2199 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestVertexColor))
2204 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestNormalVS))
2209 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestNormalOS))
2214 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestPosOS))
2223 buildVertexShader();
2224 buildTessControlShader();
2225 buildTessEvalShader();
2226 buildGeometryShader();
2227 buildFragmentShader();
2257 void ShaderProgGenerator::saveVertexShToFile(
const char* _fileName)
2262 void ShaderProgGenerator::saveGeometryShToFile(
const char* _fileName)
2267 void ShaderProgGenerator::saveFragmentShToFile(
const char* _fileName)
2275 if (!desc_.vertexTemplateFile.isEmpty())
2280 if (!desc_.fragmentTemplateFile.isEmpty())
2285 if (!desc_.geometryTemplateFile.isEmpty())
2290 if (!desc_.tessControlTemplateFile.isEmpty())
2295 if (!desc_.tessEvaluationTemplateFile.isEmpty())
2298 scanShaderTemplate(tessEvalTemplate_, desc_.tessEvaluationTemplateFile, &tessEvalLayout_);
2303 tessControlShaderFile_ = desc_.tessControlTemplateFile;
2304 tessEvalShaderFile_ = desc_.tessEvaluationTemplateFile;
2305 geometryShaderFile_ = desc_.geometryTemplateFile;
2306 fragmentShaderFile_ = desc_.fragmentTemplateFile;
2314 QString filePath =
getPathName(_templateFilename);
2316 QStringList::iterator it;
2317 for (it = _templateSrc.begin(); it != _templateSrc.end(); ++it)
2326 it = _templateSrc.erase(it);
2328 int offset = it - _templateSrc.begin();
2333 foreach(importLine,
import)
2335 it = _templateSrc.insert(it, importLine);
2341 it = _templateSrc.begin() + offset;
2345 QString trimmedLine = it->trimmed();
2348 QByteArray lineBytes = trimmedLine.toUtf8();
2350 if (trimmedLine.startsWith(
"#version "))
2352 QStringList tokens = trimmedLine.split(
' ');
2354 if (tokens.size() > 1)
2357 bool convOk =
false;
2358 int templateVersion = tokens.at(1).toInt(&convOk);
2362 desc_.version = std::max(templateVersion, desc_.version);
2365 it = _templateSrc.erase(it);
2370 else if (trimmedLine.startsWith(
"layout(") || trimmedLine.startsWith(
"layout ("))
2372 if (_outLayoutDirectives)
2374 _outLayoutDirectives->push_back(trimmedLine);
2377 it = _templateSrc.erase(it);
2384 if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestPosVS))
2386 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestTexcoord))
2391 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestVertexColor))
2396 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestNormalVS))
2401 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestNormalOS))
2406 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestPosOS))
2408 else if (trimmedLine.startsWith(
"SG_FRAGMENT_LIGHTING"))
2412 desc_.shadeMode = SG_SHADE_PHONG;
2424 return fileInfo.absolutePath();
2429 QString absFilename;
2430 if ( QDir(_strFileName).isRelative() )
2431 absFilename =
getShaderDir() + QDir::separator() + _strFileName;
2433 absFilename = _strFileName;
2435 return QDir::cleanPath(absFilename);
2445 return shaderDir_ + QString(
"/");
2451 if (!_modifier)
return 0;
2456 if (registeredModifiers_[i] == _modifier)
2459 return registeredModifiers_[i]->getID();
2463 _modifier->modifierID_ = (
unsigned int)(numRegisteredModifiers_++);
2465 registeredModifiers_.push_back(_modifier);
2466 return _modifier->modifierID_;
2471 if (_i >= 0 && _i <=
int(activeMods_.size()))
2472 return activeMods_[_i];
2480 return int(activeMods_.size());
2486 return !desc_.geometryTemplateFile.isEmpty();
2491 return !desc_.tessControlTemplateFile.isEmpty();
2496 return !desc_.tessEvaluationTemplateFile.isEmpty();
2502 ShaderModifier::ShaderModifier(
void )
2506 ShaderModifier::~ShaderModifier(
void )
2533 const QString& filename()
const {
return filename_;}
2534 const QDateTime& filetime()
const {
return filetime_;}
2535 void filetime(
const QDateTime& _newtime) {filetime_ = _newtime;}
2541 for (
int i = 0; i < 5; ++i)
2544 vertexBeginCode_.clear();
2545 vertexEndCode_.clear();
2546 fragmentBeginCode_.clear();
2547 fragmentEndCode_.clear();
2556 QDateTime lastmod = QFileInfo(absFilename).lastModified();
2559 QHash<QString, ShaderModifierFile>::iterator cacheEntry = fileCache_.find(_filename);
2561 bool reload =
false;
2562 bool firstLoad =
false;
2564 if (cacheEntry != fileCache_.end())
2567 res = &cacheEntry.value();
2569 if (lastmod != res->filetime())
2589 res = &fileCache_[_filename];
2591 res->loadBlocks(lines);
2592 res->filetime(lastmod);
2606 void loadBlocks(
const QStringList& _lines)
2608 static const char* markers [] =
2617 "FragmentBeginCode:",
2620 const int numMarkers =
sizeof(markers) /
sizeof(markers[0]);
2622 QStringList* blockTargets [] =
2631 &fragmentBeginCode_,
2635 assert(
sizeof(blockTargets) /
sizeof(blockTargets[0]) == numMarkers);
2639 QStringList* curBlock_ = 0;
2644 for (QStringList::const_iterator it = _lines.begin(); it != _lines.end(); ++it, ++curLine)
2650 if (version_ <= 0 && it->startsWith(
"#version "))
2652 const int offset = strlen(
"#version ");
2653 version_ = atoi(it->toLatin1().data() + offset);
2659 bool blockMarker =
false;
2661 for (
int i = 0; i < numMarkers && !blockMarker; ++i)
2663 if ( it->startsWith(markers[i]) )
2666 curBlock_ = blockTargets[i];
2674 curBlock_->push_back(*it);
2676 std::cerr <<
"ShaderModifierFile::loadBlocks - line belongs to unknown block in file " << filename_.toLatin1().data() <<
" at line " << curLine << std::endl;
2694 QDateTime filetime_;
2703 QStringList vertexBeginCode_,
2710 static QHash<QString, ShaderModifierFile> fileCache_;
2713 QHash<QString, ShaderModifierFile> ShaderModifierFile::fileCache_;
2718 return ShaderModifierFile::loadFromFile(_filename);
2728 const char* shadeModeString[] =
2737 QTextStream resStrm(&res);
2739 resStrm <<
"version: " << version;
2741 resStrm <<
"\nshaderDesc.numLights: " << numLights;
2745 resStrm <<
"\nshaderDesc.lightTypes[]: {";
2747 for (
int i = 0; i < numLights; ++i)
2749 switch (lightTypes[i])
2751 case SG_LIGHT_DIRECTIONAL: resStrm <<
"DIRECTIONAL";
break;
2752 case SG_LIGHT_POINT: resStrm <<
"POINT";
break;
2753 case SG_LIGHT_SPOT: resStrm <<
"SPOT";
break;
2754 default: resStrm <<
"UNDEFINED";
break;
2757 if (i + 1 < numLights)
2763 resStrm <<
"\nshaderDesc.shadeMode: " << shadeModeString[shadeMode];
2764 resStrm <<
"\nshaderDesc.twoSidedLighting: " << (twoSidedLighting ?
"Yes" :
"No");
2765 resStrm <<
"\nshaderDesc.vertexColors: " << vertexColors;
2766 resStrm <<
"\nshaderDesc.textured(): " << textured();
2767 for (std::map<size_t,TextureType>::const_iterator iter = textureTypes_.begin(); iter != textureTypes_.end();++iter)
2769 resStrm <<
"\nTexture stage: " << iter->first;
2770 resStrm <<
"\nTexture Type: ";
2771 switch (iter->second.type)
2773 case GL_TEXTURE_1D: resStrm <<
"GL_TEXTURE_1D";
break;
2774 case GL_TEXTURE_2D: resStrm <<
"GL_TEXTURE_2D";
break;
2775 case GL_TEXTURE_3D: resStrm <<
"GL_TEXTURE_3D";
break;
2776 case GL_TEXTURE_CUBE_MAP: resStrm <<
"GL_TEXTURE_CUBE_MAP";
break;
2777 #ifdef GL_ARB_texture_rectangle //ARCH_DARWIN doesn't support all texture defines with all xcode version (xcode 5.0 seems to support all) 2778 case GL_TEXTURE_RECTANGLE_ARB: resStrm <<
"GL_TEXTURE_RECTANGLE";
break;
2780 case GL_TEXTURE_BUFFER: resStrm <<
"GL_TEXTURE_BUFFER";
break;
2781 #ifdef GL_EXT_texture_array 2782 case GL_TEXTURE_1D_ARRAY_EXT: resStrm <<
"GL_TEXTURE_1D_ARRAY";
break;
2783 case GL_TEXTURE_2D_ARRAY_EXT: resStrm <<
"GL_TEXTURE_2D_ARRAY";
break;
2785 #ifdef GL_ARB_texture_cube_map_array 2786 case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: resStrm <<
"GL_TEXTURE_CUBE_MAP_ARRAY";
break;
2788 #ifdef GL_ARB_texture_multisample 2789 case GL_TEXTURE_2D_MULTISAMPLE: resStrm <<
"GL_TEXTURE_2D_MULTISAMPLE";
break;
2790 case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: resStrm <<
"GL_TEXTURE_2D_MULTISAMPLE_ARRAY";
break;
2792 default: std::cerr <<
"Texture Type with number "<< iter->second.type <<
" on stage "<< iter->first <<
" is not supported " << std::endl;
break;
2795 resStrm <<
"\nShadowTexture: " << iter->second.shadow;
2798 resStrm <<
"\nshaderDesc.texGenDim: " << texGenDim;
2802 case GL_OBJECT_LINEAR: resStrm <<
"\nshaderDesc.texGenMode: GL_OBJECT_LINEAR";
break;
2803 case GL_EYE_LINEAR: resStrm <<
"\nshaderDesc.texGenMode: GL_EYE_LINEAR";
break;
2804 case GL_SPHERE_MAP: resStrm <<
"\nshaderDesc.texGenMode: GL_SPHERE_MAP";
break;
2805 case GL_NORMAL_MAP: resStrm <<
"\nshaderDesc.texGenMode: GL_NORMAL_MAP";
break;
2806 case GL_REFLECTION_MAP: resStrm <<
"\nshaderDesc.texGenMode: GL_REFLECTION_MAP";
break;
2807 default: resStrm <<
"\nshaderDesc.texGenMode: unknown";
break;
2810 resStrm <<
"\nshaderDesc.texGenPerFragment: " << texGenPerFragment;
2812 if (!vertexTemplateFile.isEmpty())
2813 resStrm <<
"\nshaderDesc.vertexTemplateFile: " << vertexTemplateFile;
2815 if (!tessControlTemplateFile.isEmpty())
2816 resStrm <<
"\nshaderDesc.tessControlTemplateFile: " << tessControlTemplateFile;
2818 if (!tessEvaluationTemplateFile.isEmpty())
2819 resStrm <<
"\nshaderDesc.tessEvaluationTemplateFile: " << tessEvaluationTemplateFile;
2821 if (!geometryTemplateFile.isEmpty())
2822 resStrm <<
"\nshaderDesc.geometryTemplateFile: " << geometryTemplateFile;
2824 if (!fragmentTemplateFile.isEmpty())
2825 resStrm <<
"\nshaderDesc.fragmentTemplateFile: " << fragmentTemplateFile;
virtual void modifyGeometryIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the geometry shader.
static QString getShaderDir()
void modifyFragmentIO(ShaderGenerator *_shader) override
Add your own inputs/outputs to the fragment shader.
static QString getAbsFilePath(QString _fileName)
Convert a filename to an absolute filename.
QString getOutputName(int _id) const
get variable name of output
void modifyLightingCode(QStringList *_code, ShaderModifier *_modifier)
Calls lighting modifier for each light.
int checkForIncludes(QString _str, ShaderGenerator *_gen, QString _includePath)
void addOutput(const QString &_output)
Add one GLSL output specifier.
void addInput(const QString &_input)
Add one GLSL input specifier.
const QStringList & getTessEvaluationShaderCode()
Returns generated tessellation control shader code.
ShaderGenerator::DefaultIODesc ioDesc_
default IO descriptor for the vertex shader
void modifyFragmentBeginCode(QStringList *_code) override
Append code the the fragment shader.
bool hasTessControlShader() const
check whether there is a tess-control shader present
void addMacros(const QStringList &_macros)
Add a list of preprocessor macros.
void initDefaultUniforms()
Adds frequently used uniform parameters.
void initTessEvalShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting tess-evaluation shader io for a given description.
QString getInputName(int _id) const
get variable name of input
void addLightingCode(QStringList *_code)
Adds lighting function calls to code.
int getNumInputs() const
get number of inputs
Namespace providing different geometric functions concerning angles.
void addIncludeFile(QString _fileName)
Imports another shader, same as #include.
bool inputTexCoord_
default attributes that should be imported in vertex shader
void modifyTessControlIO(ShaderGenerator *_shader) override
Add your own inputs/outputs to the tessellation control shader.
void addIOToCode(const QStringList &_cmds)
virtual void modifyFragmentIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the fragment shader.
void modifyVertexBeginCode(QStringList *_code) override
Append code the the vertex shader.
void setGLSLVersion(int _version)
Set glsl version.
void addRawIOBlock(QStringList _codeBlock)
Add a raw glsl IO code block.
const QStringList & getTessControlShaderCode()
Returns generated vertex shader code.
void addIODefine(const QString &_macroName, const QString &_resolvedName)
Assign an opaque name to the abstract macro.
const QStringList & getFragmentShaderCode()
Returns generated fragment shader code.
static ShaderModifier * loadFromFile(QString _filename)
Load a modifier from file.
QString vertexColorsInterpolator
interpolation qualifier for input vertex colors: "flat", "smooth", "noperspective" ...
void matchInputs(const ShaderGenerator *_previousShaderStage, bool _passToNextStage, QString _inputPrefix="outVertex", QString _outputPrefix="outGeometry")
Perform name matching of outputs and inputs between two shader stages.
void scanShaderTemplate(QStringList &_templateSrc, QString _templateFilename, QStringList *_outLayoutDirectives=0)
Scans loaded shader template for requested inputs, glsl version or includes.
QString getIOMapName(int _inId) const
get corresponding output name of an input id
void modifyTessEvalIO(ShaderGenerator *_shader) override
Add your own inputs/outputs to the tessellation evaluation shader.
bool hasTessEvaluationShader() const
check whether there is a tess-evaluation shader present
virtual void modifyVertexIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the vertex shader.
virtual void modifyTessEvalIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the tessellation evaluation shader.
QString vertexShaderFile_
path + filename to shader templates
virtual void modifyLightingCode(QStringList *_code, int _lightId, ShaderGenLightType _lightType)
Modify the default lighting code of the shader generator.
void addDefine(const QString &_define)
Add one define.
bool ACGDLLEXPORT openGLVersionTest(const int _major, const int _minor)
virtual void modifyTessControlIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the tessellation control shader.
void addStringToList(QString _str, QStringList *_list, QString _prefix="", QString _postfix="")
bool hasDefine(QString _define) const
Check for define.
static void setShaderDir(QString _dir)
void initGenDefines(ShaderGenerator *_gen)
provide generated defines to shader
bool passPosVS_
default attributes that should be passed down from vertex shader
void addLightingFunctions(QStringList *_code)
Adds lighting definition functions.
QString vertexNormalInterpolator
interpolation qualifier for vertex shader normal outputs: "flat", "smooth", "noperspective" ...
void initVertexShaderIO(const ShaderGenDesc *_desc, const DefaultIODesc *_iodesc)
Adds fitting vertex shader io for a given description.
void buildShaderCode(QStringList *_pMainCode, const QStringList &_defaultLightingFunctions)
Shader assembly function.
void addUniform(QString _uniform, QString _comment="")
Add one GLSL uniform specifier.
void generateShaders()
Generates the shader code.
void initGeometryShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting geometry shader io for a given description.
static int numRegisteredModifiers_
registered shader modifier
void addTexGenCode(QStringList *_code, bool _fragmentShader)
Add texture coordinate generation code.
QStringList tessControlLayout_
layout() directives scanned from loaded templates
void defineIOAbstraction(const DefaultIODesc *_iodesc, bool _vs, bool _fs)
Define abstract IO names via shader defines.
const QStringList & getGeometryShaderCode()
Returns generated tessellation evaluation shader code.
bool outputArrays_
outputs of shader are arrays (tess-control)
void modifyGeometryIO(ShaderGenerator *_shader) override
Add your own inputs/outputs to the geometry shader.
const QStringList & getShaderCode()
Get result of buildShaderCode.
void modifyFragmentEndCode(QStringList *_code) override
Append code the the fragment shader.
QString toString() const
convert ShaderGenDesc to string format for debugging
int getNumActiveModifiers() const
Get the number of active modifiers.
ShaderProgGenerator(const ShaderGenDesc *_desc)
void addLayout(QString _layout)
Add a layout directive.
void initFragmentShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting fragment shader io for a given description.
int getNumOutputs() const
get number of outputs
static unsigned int registerModifier(ShaderModifier *_modifier)
Shader modifiers have to be registered before they can be used. They also must remain allocated for t...
void modifyVertexIO(ShaderGenerator *_shader) override
Add your own inputs/outputs to the vertex shader.
void initTessControlShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting tess-control shader io for a given description.
const QStringList & getVertexShaderCode()
Returns generated vertex shader code.
void loadShaderTemplateFromFile()
Loads external shader templates.
bool hasGeometryShader() const
check whether there is a geometry shader present
static bool loadStringListFromFile(QString _fileName, QStringList *_out)
Load a text file as string list.
QString outputPrefix_
prefix of outputs of this shader
bool normalizeTexColors
Defines if the textureVariable is normalized or not, if multiple textures are used.
ShaderModifier * getActiveModifier(int _i)
Get active modfiers for this program.
void saveToFile(const char *_fileName)
Save generated shader code to text file.
static QString getPathName(QString _strFileName)
returns path to _strFileName without last slash
void init(const ShaderGenDesc *_desc, ShaderModifier *const *_modifiers, unsigned int _numActiveMods)
Called in constructor.
void modifyVertexEndCode(QStringList *_code) override
Append code the the vertex shader.
void addLight(int lightIndex_, ShaderGenLightType _light)
Add a light description to shader: