ShaderProgram.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. #include "anki/gl/ShaderProgram.h"
  2. #include "anki/gl/GlException.h"
  3. #include "anki/math/Math.h"
  4. #include "anki/util/Exception.h"
  5. #include "anki/gl/Texture.h"
  6. namespace anki {
  7. //==============================================================================
  8. // ShaderProgramVariable =
  9. //==============================================================================
  10. //==============================================================================
  11. void ShaderProgramUniformVariable::doSanityChecks() const
  12. {
  13. ANKI_ASSERT(getLocation() != -1);
  14. ANKI_ASSERT(ShaderProgram::getCurrentProgramGlId() ==
  15. getFatherShaderProgram().getGlId());
  16. ANKI_ASSERT(glGetUniformLocation(getFatherShaderProgram().getGlId(),
  17. getName().c_str()) == getLocation());
  18. }
  19. //==============================================================================
  20. void ShaderProgramUniformVariable::set(const float x) const
  21. {
  22. doSanityChecks();
  23. ANKI_ASSERT(getGlDataType() == GL_FLOAT);
  24. ANKI_ASSERT(getSize() == 1);
  25. glUniform1f(getLocation(), x);
  26. }
  27. //==============================================================================
  28. void ShaderProgramUniformVariable::set(const Vec2& x) const
  29. {
  30. doSanityChecks();
  31. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC2);
  32. ANKI_ASSERT(getSize() == 2);
  33. glUniform2f(getLocation(), x.x(), x.y());
  34. }
  35. //==============================================================================
  36. void ShaderProgramUniformVariable::set(const float x[], uint size) const
  37. {
  38. doSanityChecks();
  39. ANKI_ASSERT(getGlDataType() == GL_FLOAT);
  40. ANKI_ASSERT(getSize() == size);
  41. glUniform1fv(getLocation(), size, x);
  42. }
  43. //==============================================================================
  44. void ShaderProgramUniformVariable::set(const Vec2 x[], uint size) const
  45. {
  46. doSanityChecks();
  47. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC2);
  48. ANKI_ASSERT(getSize() == size * 2);
  49. glUniform2fv(getLocation(), size, &(const_cast<Vec2&>(x[0]))[0]);
  50. }
  51. //==============================================================================
  52. void ShaderProgramUniformVariable::set(const Vec3 x[], uint size) const
  53. {
  54. doSanityChecks();
  55. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC3);
  56. ANKI_ASSERT(getSize() == size * 3);
  57. glUniform3fv(getLocation(), size, &(const_cast<Vec3&>(x[0]))[0]);
  58. }
  59. //==============================================================================
  60. void ShaderProgramUniformVariable::set(const Vec4 x[], uint size) const
  61. {
  62. doSanityChecks();
  63. ANKI_ASSERT(getGlDataType() == GL_FLOAT_VEC4);
  64. ANKI_ASSERT(getSize() == size * 4);
  65. glUniform4fv(getLocation(), size, &(const_cast<Vec4&>(x[0]))[0]);
  66. }
  67. //==============================================================================
  68. void ShaderProgramUniformVariable::set(const Mat3 x[], uint size) const
  69. {
  70. doSanityChecks();
  71. ANKI_ASSERT(getGlDataType() == GL_FLOAT_MAT3);
  72. ANKI_ASSERT(getSize() == size);
  73. glUniformMatrix3fv(getLocation(), size, true, &(x[0])[0]);
  74. }
  75. //==============================================================================
  76. void ShaderProgramUniformVariable::set(const Mat4 x[], uint size) const
  77. {
  78. doSanityChecks();
  79. ANKI_ASSERT(getGlDataType() == GL_FLOAT_MAT4);
  80. ANKI_ASSERT(getSize() == size);
  81. glUniformMatrix4fv(getLocation(), size, true, &(x[0])[0]);
  82. }
  83. //==============================================================================
  84. void ShaderProgramUniformVariable::set(const Texture& tex) const
  85. {
  86. doSanityChecks();
  87. ANKI_ASSERT(getGlDataType() == GL_SAMPLER_2D
  88. || getGlDataType() == GL_SAMPLER_2D_SHADOW);
  89. tex.bind();
  90. glUniform1i(getLocation(), tex.getUnit());
  91. }
  92. //==============================================================================
  93. // ShaderProgram =
  94. //==============================================================================
  95. //==============================================================================
  96. const char* ShaderProgram::stdSourceCode =
  97. "#version 330 core\n"
  98. //"precision lowp float;\n"
  99. #if defined(NDEBUG)
  100. "#pragma optimize(on)\n"
  101. "#pragma debug(off)\n";
  102. #else
  103. "#pragma optimize(of)\n"
  104. "#pragma debug(on)\n";
  105. #endif
  106. const thread_local ShaderProgram* ShaderProgram::currentProgram = nullptr;
  107. //==============================================================================
  108. void ShaderProgram::create(const char* vertSource, const char* tcSource,
  109. const char* teSource, const char* geomSource, const char* fragSource,
  110. const char* transformFeedbackVaryings[])
  111. {
  112. ANKI_ASSERT(!isCreated());
  113. // 1) create and compile the shaders
  114. //
  115. std::string preprocSource = stdSourceCode;
  116. ANKI_ASSERT(vertSource != nullptr);
  117. vertShaderGlId = createAndCompileShader(vertSource, preprocSource.c_str(),
  118. GL_VERTEX_SHADER);
  119. if(tcSource != nullptr)
  120. {
  121. tcShaderGlId = createAndCompileShader(tcSource, preprocSource.c_str(),
  122. GL_TESS_CONTROL_SHADER);
  123. }
  124. if(teSource != nullptr)
  125. {
  126. teShaderGlId = createAndCompileShader(teSource, preprocSource.c_str(),
  127. GL_TESS_EVALUATION_SHADER);
  128. }
  129. if(geomSource != nullptr)
  130. {
  131. geomShaderGlId = createAndCompileShader(geomSource,
  132. preprocSource.c_str(), GL_GEOMETRY_SHADER);
  133. }
  134. ANKI_ASSERT(fragSource != nullptr);
  135. fragShaderGlId = createAndCompileShader(fragSource, preprocSource.c_str(),
  136. GL_FRAGMENT_SHADER);
  137. // 2) create program and attach shaders
  138. glId = glCreateProgram();
  139. if(glId == 0)
  140. {
  141. throw ANKI_EXCEPTION("glCreateProgram failed");
  142. }
  143. glAttachShader(glId, vertShaderGlId);
  144. glAttachShader(glId, fragShaderGlId);
  145. if(tcSource != nullptr)
  146. {
  147. glAttachShader(glId, tcShaderGlId);
  148. }
  149. if(teSource != nullptr)
  150. {
  151. glAttachShader(glId, teShaderGlId);
  152. }
  153. if(geomSource != nullptr)
  154. {
  155. glAttachShader(glId, geomShaderGlId);
  156. }
  157. // 3) set the TRFFB varyings
  158. ANKI_ASSERT(transformFeedbackVaryings != nullptr);
  159. int count = 0;
  160. while(*transformFeedbackVaryings != nullptr)
  161. {
  162. ++count;
  163. ++transformFeedbackVaryings;
  164. }
  165. if(count)
  166. {
  167. glTransformFeedbackVaryings(
  168. glId,
  169. count,
  170. transformFeedbackVaryings,
  171. GL_SEPARATE_ATTRIBS);
  172. }
  173. // 4) link
  174. link();
  175. // init the rest
  176. getUniAndAttribVars();
  177. }
  178. //==============================================================================
  179. void ShaderProgram::destroy()
  180. {
  181. unbind();
  182. if(vertShaderGlId != 0)
  183. {
  184. glDeleteShader(vertShaderGlId);
  185. }
  186. if(tcShaderGlId != 0)
  187. {
  188. glDeleteShader(tcShaderGlId);
  189. }
  190. if(teShaderGlId != 0)
  191. {
  192. glDeleteShader(teShaderGlId);
  193. }
  194. if(geomShaderGlId != 0)
  195. {
  196. glDeleteShader(geomShaderGlId);
  197. }
  198. if(fragShaderGlId != 0)
  199. {
  200. glDeleteShader(fragShaderGlId);
  201. }
  202. if(glId != 0)
  203. {
  204. glDeleteProgram(glId);
  205. }
  206. init();
  207. }
  208. //==============================================================================
  209. GLuint ShaderProgram::createAndCompileShader(const char* sourceCode,
  210. const char* preproc, GLenum type)
  211. {
  212. uint glId = 0;
  213. const char* sourceStrs[2] = {NULL, NULL};
  214. // create the shader
  215. glId = glCreateShader(type);
  216. // attach the source
  217. sourceStrs[1] = sourceCode;
  218. sourceStrs[0] = preproc;
  219. // compile
  220. glShaderSource(glId, 2, sourceStrs, NULL);
  221. glCompileShader(glId);
  222. int success;
  223. glGetShaderiv(glId, GL_COMPILE_STATUS, &success);
  224. if(!success)
  225. {
  226. // print info log
  227. int infoLen = 0;
  228. int charsWritten = 0;
  229. std::vector<char> infoLog;
  230. glGetShaderiv(glId, GL_INFO_LOG_LENGTH, &infoLen);
  231. infoLog.resize(infoLen + 1);
  232. glGetShaderInfoLog(glId, infoLen, &charsWritten, &infoLog[0]);
  233. infoLog[charsWritten] = '\0';
  234. throw ANKI_EXCEPTION("Shader failed. Log:\n" + &infoLog[0]
  235. + "\nSource:\n" + sourceCode);
  236. }
  237. return glId;
  238. }
  239. //==============================================================================
  240. void ShaderProgram::link() const
  241. {
  242. // link
  243. glLinkProgram(glId);
  244. // check if linked correctly
  245. int success;
  246. glGetProgramiv(glId, GL_LINK_STATUS, &success);
  247. if(!success)
  248. {
  249. int info_len = 0;
  250. int charsWritten = 0;
  251. std::string infoLogTxt;
  252. glGetProgramiv(glId, GL_INFO_LOG_LENGTH, &info_len);
  253. infoLogTxt.resize(info_len + 1);
  254. glGetProgramInfoLog(glId, info_len, &charsWritten, &infoLogTxt[0]);
  255. throw ANKI_EXCEPTION("Link error log follows:\n"
  256. + infoLogTxt);
  257. }
  258. }
  259. //==============================================================================
  260. void ShaderProgram::getUniAndAttribVars()
  261. {
  262. int num;
  263. std::array<char, 256> name_;
  264. GLsizei length;
  265. GLint size;
  266. GLenum type;
  267. // attrib locations
  268. glGetProgramiv(glId, GL_ACTIVE_ATTRIBUTES, &num);
  269. for(int i = 0; i < num; i++) // loop all attributes
  270. {
  271. glGetActiveAttrib(glId, i, sizeof(name_) / sizeof(char), &length,
  272. &size, &type, &name_[0]);
  273. name_[length] = '\0';
  274. // check if its FFP location
  275. int loc = glGetAttribLocation(glId, &name_[0]);
  276. if(loc == -1) // if -1 it means that its an FFP var
  277. {
  278. throw ANKI_EXCEPTION("You are using FFP vertex attributes");
  279. }
  280. ShaderProgramAttributeVariable* var =
  281. new ShaderProgramAttributeVariable(loc, &name_[0], type,
  282. size, this);
  283. vars.push_back(var);
  284. attribs.push_back(var);
  285. nameToVar[var->getName().c_str()] = var;
  286. nameToAttribVar[var->getName().c_str()] = var;
  287. }
  288. // uni locations
  289. glGetProgramiv(glId, GL_ACTIVE_UNIFORMS, &num);
  290. for(int i = 0; i < num; i++) // loop all uniforms
  291. {
  292. glGetActiveUniform(glId, i, sizeof(name_) / sizeof(char), &length,
  293. &size, &type, &name_[0]);
  294. name_[length] = '\0';
  295. // check if its FFP location
  296. int loc = glGetUniformLocation(glId, &name_[0]);
  297. if(loc == -1) // if -1 it means that its an FFP var
  298. {
  299. throw ANKI_EXCEPTION("You are using FFP vertex uniforms");
  300. }
  301. ShaderProgramUniformVariable* var =
  302. new ShaderProgramUniformVariable(loc, &name_[0], type,
  303. size, this);
  304. vars.push_back(var);
  305. unis.push_back(var);
  306. nameToVar[var->getName().c_str()] = var;
  307. nameToUniVar[var->getName().c_str()] = var;
  308. }
  309. }
  310. //==============================================================================
  311. const ShaderProgramVariable* ShaderProgram::findVariableByName(
  312. const char* name) const
  313. {
  314. NameToVarHashMap::const_iterator it = nameToVar.find(name);
  315. if(it == nameToVar.end())
  316. {
  317. return nullptr;
  318. }
  319. return it->second;
  320. }
  321. //==============================================================================
  322. const ShaderProgramAttributeVariable*
  323. ShaderProgram::findAttributeVariableByName(const char* name) const
  324. {
  325. NameToAttribVarHashMap::const_iterator it = nameToAttribVar.find(name);
  326. if(it == nameToAttribVar.end())
  327. {
  328. return nullptr;
  329. }
  330. return it->second;
  331. }
  332. //==============================================================================
  333. const ShaderProgramUniformVariable* ShaderProgram::findUniformVariableByName(
  334. const char* name) const
  335. {
  336. NameToUniVarHashMap::const_iterator it = nameToUniVar.find(name);
  337. if(it == nameToUniVar.end())
  338. {
  339. return nullptr;
  340. }
  341. return it->second;
  342. }
  343. //==============================================================================
  344. std::ostream& operator<<(std::ostream& s, const ShaderProgram& x)
  345. {
  346. s << "ShaderProgram\n";
  347. s << "Variables:\n";
  348. for(const ShaderProgramVariable& var : x.vars)
  349. {
  350. s << var.getName() << " " << var.getLocation() << " "
  351. << (var.getType() == ShaderProgramVariable::SPVT_ATTRIBUTE
  352. ? "[A]" : "[U]") << '\n';
  353. }
  354. return s;
  355. }
  356. } // end namespace