ShaderProgram.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #include "anki/resource/ShaderProgram.h"
  2. #include "anki/resource/ShaderProgramPrePreprocessor.h"
  3. #include "anki/core/App.h" // To get cache dir
  4. #include "anki/gl/GlException.h"
  5. #include "anki/core/Logger.h"
  6. #include "anki/util/Util.h"
  7. #include "anki/core/Globals.h"
  8. #include "anki/util/Exception.h"
  9. #include <boost/filesystem.hpp>
  10. #include <boost/lexical_cast.hpp>
  11. #include <boost/foreach.hpp>
  12. #include <boost/functional/hash.hpp>
  13. #include <fstream>
  14. #include <sstream>
  15. namespace anki {
  16. //==============================================================================
  17. #define SHADER_PROGRAM_EXCEPTION(x) ANKI_EXCEPTION( \
  18. "Shader program \"" + rsrcFilename + \
  19. "\": " + x)
  20. const char* ShaderProgram::stdSourceCode =
  21. "#version 330 core\n"
  22. //"precision lowp float;\n"
  23. #if defined(NDEBUG)
  24. "#pragma optimize(on)\n"
  25. "#pragma debug(off)\n";
  26. #else
  27. "#pragma optimize(of)\n"
  28. "#pragma debug(on)\n";
  29. #endif
  30. //==============================================================================
  31. ShaderProgram::~ShaderProgram()
  32. {
  33. /// @todo add code
  34. }
  35. //==============================================================================
  36. uint ShaderProgram::createAndCompileShader(const char* sourceCode,
  37. const char* preproc, int type) const
  38. {
  39. uint glId = 0;
  40. const char* sourceStrs[2] = {NULL, NULL};
  41. // create the shader
  42. glId = glCreateShader(type);
  43. // attach the source
  44. sourceStrs[1] = sourceCode;
  45. sourceStrs[0] = preproc;
  46. // compile
  47. glShaderSource(glId, 2, sourceStrs, NULL);
  48. glCompileShader(glId);
  49. int success;
  50. glGetShaderiv(glId, GL_COMPILE_STATUS, &success);
  51. if(!success)
  52. {
  53. // print info log
  54. int infoLen = 0;
  55. int charsWritten = 0;
  56. std::vector<char> infoLog;
  57. glGetShaderiv(glId, GL_INFO_LOG_LENGTH, &infoLen);
  58. infoLog.resize(infoLen + 1);
  59. glGetShaderInfoLog(glId, infoLen, &charsWritten, &infoLog[0]);
  60. infoLog[charsWritten] = '\0';
  61. const char* shaderType = "*dummy*";
  62. switch(type)
  63. {
  64. case GL_VERTEX_SHADER:
  65. shaderType = "Vertex shader";
  66. break;
  67. case GL_FRAGMENT_SHADER:
  68. shaderType = "Fragment shader";
  69. break;
  70. default:
  71. ANKI_ASSERT(0); // Not supported
  72. }
  73. throw SHADER_PROGRAM_EXCEPTION(shaderType +
  74. " compiler error log follows:\n"
  75. "===================================\n" +
  76. &infoLog[0] +
  77. "\n===================================\n" + sourceCode);
  78. }
  79. return glId;
  80. }
  81. //==============================================================================
  82. void ShaderProgram::link() const
  83. {
  84. // link
  85. glLinkProgram(glId);
  86. // check if linked correctly
  87. int success;
  88. glGetProgramiv(glId, GL_LINK_STATUS, &success);
  89. if(!success)
  90. {
  91. int info_len = 0;
  92. int charsWritten = 0;
  93. std::string infoLogTxt;
  94. glGetProgramiv(glId, GL_INFO_LOG_LENGTH, &info_len);
  95. infoLogTxt.resize(info_len + 1);
  96. glGetProgramInfoLog(glId, info_len, &charsWritten, &infoLogTxt[0]);
  97. throw SHADER_PROGRAM_EXCEPTION("Link error log follows:\n" +
  98. infoLogTxt);
  99. }
  100. }
  101. //==============================================================================
  102. void ShaderProgram::getUniAndAttribVars()
  103. {
  104. int num;
  105. boost::array<char, 256> name_;
  106. GLsizei length;
  107. GLint size;
  108. GLenum type;
  109. // attrib locations
  110. glGetProgramiv(glId, GL_ACTIVE_ATTRIBUTES, &num);
  111. for(int i = 0; i < num; i++) // loop all attributes
  112. {
  113. glGetActiveAttrib(glId, i, sizeof(name_) / sizeof(char), &length,
  114. &size, &type, &name_[0]);
  115. name_[length] = '\0';
  116. // check if its FFP location
  117. int loc = glGetAttribLocation(glId, &name_[0]);
  118. if(loc == -1) // if -1 it means that its an FFP var
  119. {
  120. ANKI_WARNING("Shader prog: \"" << rsrcFilename <<
  121. "\": You are using FFP vertex attributes (\"" <<
  122. &name_[0] << "\")");
  123. continue;
  124. }
  125. ShaderProgramAttributeVariable* var =
  126. new ShaderProgramAttributeVariable(loc, &name_[0], type, *this);
  127. vars.push_back(var);
  128. attribs.push_back(var);
  129. nameToVar[var->getName().c_str()] = var;
  130. nameToAttribVar[var->getName().c_str()] = var;
  131. }
  132. // uni locations
  133. glGetProgramiv(glId, GL_ACTIVE_UNIFORMS, &num);
  134. for(int i = 0; i < num; i++) // loop all uniforms
  135. {
  136. glGetActiveUniform(glId, i, sizeof(name_) / sizeof(char), &length,
  137. &size, &type, &name_[0]);
  138. name_[length] = '\0';
  139. // check if its FFP location
  140. int loc = glGetUniformLocation(glId, &name_[0]);
  141. if(loc == -1) // if -1 it means that its an FFP var
  142. {
  143. ANKI_WARNING("Shader prog: \"" << rsrcFilename <<
  144. "\": You are using FFP vertex uniforms (\"" <<
  145. &name_[0] << "\")");
  146. continue;
  147. }
  148. ShaderProgramUniformVariable* var =
  149. new ShaderProgramUniformVariable(loc, &name_[0], type, *this);
  150. vars.push_back(var);
  151. unis.push_back(var);
  152. nameToVar[var->getName().c_str()] = var;
  153. nameToUniVar[var->getName().c_str()] = var;
  154. }
  155. }
  156. //==============================================================================
  157. void ShaderProgram::load(const char* filename)
  158. {
  159. rsrcFilename = filename;
  160. ANKI_ASSERT(!isInitialized());
  161. ShaderProgramPrePreprocessor pars(filename);
  162. // 1) create and compile the shaders
  163. std::string preprocSource = stdSourceCode;
  164. vertShaderGlId = createAndCompileShader(
  165. pars.getShaderSource(ST_VERTEX).c_str(),
  166. preprocSource.c_str(),
  167. GL_VERTEX_SHADER);
  168. fragShaderGlId = createAndCompileShader(
  169. pars.getShaderSource(ST_FRAGMENT).c_str(),
  170. preprocSource.c_str(),
  171. GL_FRAGMENT_SHADER);
  172. // 2) create program and attach shaders
  173. glId = glCreateProgram();
  174. if(glId == 0)
  175. {
  176. throw SHADER_PROGRAM_EXCEPTION("glCreateProgram failed");
  177. }
  178. glAttachShader(glId, vertShaderGlId);
  179. glAttachShader(glId, fragShaderGlId);
  180. // 3) set the TRFFB varyings
  181. if(pars.getTranformFeedbackVaryings().size() > 0)
  182. {
  183. boost::array<const char*, 128> varsArr;
  184. for(uint i = 0; i < pars.getTranformFeedbackVaryings().size(); i++)
  185. {
  186. varsArr[i] = pars.getTranformFeedbackVaryings()[i].c_str();
  187. }
  188. glTransformFeedbackVaryings(glId,
  189. pars.getTranformFeedbackVaryings().size(), &varsArr[0],
  190. GL_SEPARATE_ATTRIBS);
  191. }
  192. // 4) link
  193. link();
  194. // init the rest
  195. getUniAndAttribVars();
  196. }
  197. //==============================================================================
  198. const ShaderProgramVariable& ShaderProgram::findVariableByName(
  199. const char* name) const
  200. {
  201. NameToVarHashMap::const_iterator it = nameToVar.find(name);
  202. if(it == nameToVar.end())
  203. {
  204. throw SHADER_PROGRAM_EXCEPTION("Cannot find variable: " + name);
  205. }
  206. return *(it->second);
  207. }
  208. //==============================================================================
  209. const ShaderProgramAttributeVariable&
  210. ShaderProgram::findAttributeVariableByName(const char* name) const
  211. {
  212. NameToAttribVarHashMap::const_iterator it = nameToAttribVar.find(name);
  213. if(it == nameToAttribVar.end())
  214. {
  215. throw SHADER_PROGRAM_EXCEPTION("Cannot find attribute loc: " + name);
  216. }
  217. return *(it->second);
  218. }
  219. //==============================================================================
  220. const ShaderProgramUniformVariable& ShaderProgram::findUniformVariableByName(
  221. const char* name) const
  222. {
  223. NameToUniVarHashMap::const_iterator it = nameToUniVar.find(name);
  224. if(it == nameToUniVar.end())
  225. {
  226. throw SHADER_PROGRAM_EXCEPTION("Cannot find uniform loc: " + name);
  227. }
  228. return *(it->second);
  229. }
  230. //==============================================================================
  231. bool ShaderProgram::variableExists(const char* name) const
  232. {
  233. NameToVarHashMap::const_iterator it = nameToVar.find(name);
  234. return it != nameToVar.end();
  235. }
  236. //==============================================================================
  237. bool ShaderProgram::uniformVariableExists(const char* name) const
  238. {
  239. NameToUniVarHashMap::const_iterator it = nameToUniVar.find(name);
  240. return it != nameToUniVar.end();
  241. }
  242. //==============================================================================
  243. bool ShaderProgram::attributeVariableExists(const char* name) const
  244. {
  245. NameToAttribVarHashMap::const_iterator it = nameToAttribVar.find(name);
  246. return it != nameToAttribVar.end();
  247. }
  248. //==============================================================================
  249. std::string ShaderProgram::createSrcCodeToCache(const char* sProgFPathName,
  250. const char* preAppendedSrcCode)
  251. {
  252. using namespace boost::filesystem;
  253. if(strlen(preAppendedSrcCode) < 1)
  254. {
  255. return sProgFPathName;
  256. }
  257. // Create suffix
  258. boost::hash<std::string> stringHash;
  259. std::size_t h = stringHash(preAppendedSrcCode);
  260. std::string suffix = boost::lexical_cast<std::string>(h);
  261. //
  262. path newfPathName = AppSingleton::get().getCachePath() /
  263. (path(sProgFPathName).filename().string() + "." + suffix);
  264. if(exists(newfPathName))
  265. {
  266. return newfPathName.string();
  267. }
  268. std::string src_ = Util::readFile(sProgFPathName);
  269. std::string src = preAppendedSrcCode + src_;
  270. std::ofstream f(newfPathName.string().c_str());
  271. if(!f.is_open())
  272. {
  273. throw ANKI_EXCEPTION("Cannot open file for writing \"" +
  274. newfPathName.string() + "\"");
  275. }
  276. f.write(src.c_str(), src.length());
  277. return newfPathName.string();
  278. }
  279. //==============================================================================
  280. std::ostream& operator<<(std::ostream& s, const ShaderProgram& x)
  281. {
  282. s << "Variables:\n";
  283. BOOST_FOREACH(const ShaderProgramVariable& var, x.getVariables())
  284. {
  285. s << var.getName() << " " << var.getLocation() << " ";
  286. if(var.getType() == ShaderProgramVariable::T_ATTRIBUTE)
  287. {
  288. s << "attribute";
  289. }
  290. else
  291. {
  292. s << "uniform";
  293. }
  294. }
  295. return s;
  296. }
  297. } // end namespace