ShaderProgram.cpp 11 KB

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