ShaderProgram.cpp 13 KB

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