ShaderProgram.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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::getCurrentProgram() ==
  15. &getFatherShaderProgram());
  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 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(!isInitialized());
  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(glId,
  168. count,
  169. transformFeedbackVaryings,
  170. GL_SEPARATE_ATTRIBS);
  171. }
  172. // 4) link
  173. link();
  174. // init the rest
  175. getUniAndAttribVars();
  176. }
  177. //==============================================================================
  178. void ShaderProgram::destroy()
  179. {
  180. if(vertShaderGlId != 0)
  181. {
  182. glDeleteShader(vertShaderGlId);
  183. }
  184. if(tcShaderGlId != 0)
  185. {
  186. glDeleteShader(tcShaderGlId);
  187. }
  188. if(teShaderGlId != 0)
  189. {
  190. glDeleteShader(teShaderGlId);
  191. }
  192. if(geomShaderGlId != 0)
  193. {
  194. glDeleteShader(geomShaderGlId);
  195. }
  196. if(fragShaderGlId != 0)
  197. {
  198. glDeleteShader(fragShaderGlId);
  199. }
  200. glDeleteProgram(glId);
  201. }
  202. //==============================================================================
  203. GLuint ShaderProgram::createAndCompileShader(const char* sourceCode,
  204. const char* preproc, GLenum type)
  205. {
  206. uint glId = 0;
  207. const char* sourceStrs[2] = {NULL, NULL};
  208. // create the shader
  209. glId = glCreateShader(type);
  210. // attach the source
  211. sourceStrs[1] = sourceCode;
  212. sourceStrs[0] = preproc;
  213. // compile
  214. glShaderSource(glId, 2, sourceStrs, NULL);
  215. glCompileShader(glId);
  216. int success;
  217. glGetShaderiv(glId, GL_COMPILE_STATUS, &success);
  218. if(!success)
  219. {
  220. // print info log
  221. int infoLen = 0;
  222. int charsWritten = 0;
  223. std::vector<char> infoLog;
  224. glGetShaderiv(glId, GL_INFO_LOG_LENGTH, &infoLen);
  225. infoLog.resize(infoLen + 1);
  226. glGetShaderInfoLog(glId, infoLen, &charsWritten, &infoLog[0]);
  227. infoLog[charsWritten] = '\0';
  228. throw ANKI_EXCEPTION("Shader failed. Log:\n" + &infoLog[0]
  229. + "\nSource:\n" + sourceCode);
  230. }
  231. return glId;
  232. }
  233. //==============================================================================
  234. void ShaderProgram::link() const
  235. {
  236. // link
  237. glLinkProgram(glId);
  238. // check if linked correctly
  239. int success;
  240. glGetProgramiv(glId, GL_LINK_STATUS, &success);
  241. if(!success)
  242. {
  243. int info_len = 0;
  244. int charsWritten = 0;
  245. std::string infoLogTxt;
  246. glGetProgramiv(glId, GL_INFO_LOG_LENGTH, &info_len);
  247. infoLogTxt.resize(info_len + 1);
  248. glGetProgramInfoLog(glId, info_len, &charsWritten, &infoLogTxt[0]);
  249. throw ANKI_EXCEPTION("Link error log follows:\n"
  250. + infoLogTxt);
  251. }
  252. }
  253. //==============================================================================
  254. void ShaderProgram::getUniAndAttribVars()
  255. {
  256. int num;
  257. std::array<char, 256> name_;
  258. GLsizei length;
  259. GLint size;
  260. GLenum type;
  261. // attrib locations
  262. glGetProgramiv(glId, GL_ACTIVE_ATTRIBUTES, &num);
  263. for(int i = 0; i < num; i++) // loop all attributes
  264. {
  265. glGetActiveAttrib(glId, i, sizeof(name_) / sizeof(char), &length,
  266. &size, &type, &name_[0]);
  267. name_[length] = '\0';
  268. // check if its FFP location
  269. int loc = glGetAttribLocation(glId, &name_[0]);
  270. if(loc == -1) // if -1 it means that its an FFP var
  271. {
  272. throw ANKI_EXCEPTION("You are using FFP vertex attributes (\""
  273. + std::string(&name_[0]) + "\")");
  274. }
  275. ShaderProgramAttributeVariable* var =
  276. new ShaderProgramAttributeVariable(loc, &name_[0], type,
  277. size, this);
  278. vars.push_back(var);
  279. attribs.push_back(var);
  280. nameToVar[var->getName().c_str()] = var;
  281. nameToAttribVar[var->getName().c_str()] = var;
  282. }
  283. // uni locations
  284. glGetProgramiv(glId, GL_ACTIVE_UNIFORMS, &num);
  285. for(int i = 0; i < num; i++) // loop all uniforms
  286. {
  287. glGetActiveUniform(glId, i, sizeof(name_) / sizeof(char), &length,
  288. &size, &type, &name_[0]);
  289. name_[length] = '\0';
  290. // check if its FFP location
  291. int loc = glGetUniformLocation(glId, &name_[0]);
  292. if(loc == -1) // if -1 it means that its an FFP var
  293. {
  294. throw ANKI_EXCEPTION("You are using FFP vertex uniforms (\""
  295. + std::string(&name_[0]) + "\")");
  296. }
  297. ShaderProgramUniformVariable* var =
  298. new ShaderProgramUniformVariable(loc, &name_[0], type,
  299. size, this);
  300. vars.push_back(var);
  301. unis.push_back(var);
  302. nameToVar[var->getName().c_str()] = var;
  303. nameToUniVar[var->getName().c_str()] = var;
  304. }
  305. }
  306. //==============================================================================
  307. const ShaderProgramVariable* ShaderProgram::findVariableByName(
  308. const char* name) const
  309. {
  310. NameToVarHashMap::const_iterator it = nameToVar.find(name);
  311. if(it == nameToVar.end())
  312. {
  313. return nullptr;
  314. }
  315. return it->second;
  316. }
  317. //==============================================================================
  318. const ShaderProgramAttributeVariable*
  319. ShaderProgram::findAttributeVariableByName(const char* name) const
  320. {
  321. NameToAttribVarHashMap::const_iterator it = nameToAttribVar.find(name);
  322. if(it == nameToAttribVar.end())
  323. {
  324. return nullptr;
  325. }
  326. return it->second;
  327. }
  328. //==============================================================================
  329. const ShaderProgramUniformVariable* ShaderProgram::findUniformVariableByName(
  330. const char* name) const
  331. {
  332. NameToUniVarHashMap::const_iterator it = nameToUniVar.find(name);
  333. if(it == nameToUniVar.end())
  334. {
  335. return nullptr;
  336. }
  337. return it->second;
  338. }
  339. //==============================================================================
  340. std::ostream& operator<<(std::ostream& s, const ShaderProgram& x)
  341. {
  342. s << "ShaderProgram\n";
  343. s << "Variables:\n";
  344. for(const ShaderProgramVariable& var : x.vars)
  345. {
  346. s << var.getName() << " " << var.getLocation() << " "
  347. << (var.getType() == ShaderProgramVariable::SPVT_ATTRIBUTE
  348. ? "[A]" : "[U]") << '\n';
  349. }
  350. return s;
  351. }
  352. } // end namespace