CCGLProgram.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. /****************************************************************************
  2. Copyright 2011 Jeff Lamarche
  3. Copyright 2012 Goffredo Marocchi
  4. Copyright 2012 Ricardo Quesada
  5. Copyright 2012 cocos2d-x.org
  6. Copyright (c) 2013-2017 Chukong Technologies Inc.
  7. http://www.cocos2d-x.org
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in
  15. all copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN false EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. THE SOFTWARE.
  23. ****************************************************************************/
  24. #include "renderer/CCGLProgram.h"
  25. #ifndef WIN32
  26. #include <alloca.h>
  27. #endif
  28. #include "base/CCDirector.h"
  29. #include "base/ccUTF8.h"
  30. #include "renderer/ccGLStateCache.h"
  31. #include "platform/CCFileUtils.h"
  32. // helper functions
  33. static void replaceDefines(const std::string& compileTimeDefines, std::string& out)
  34. {
  35. // Replace semicolons with '#define ... \n'
  36. if (!compileTimeDefines.empty())
  37. {
  38. // append ';' if the last char doesn't have one
  39. auto copyDefines = compileTimeDefines;
  40. if (copyDefines[copyDefines.length()-1] != ';')
  41. copyDefines.append(1, ';');
  42. std::string currentDefine;
  43. for (auto itChar: copyDefines)
  44. {
  45. if (itChar == ';')
  46. {
  47. if (!currentDefine.empty())
  48. {
  49. out.append("\n#define " + currentDefine);
  50. currentDefine.clear();
  51. }
  52. }
  53. else
  54. {
  55. currentDefine.append(1, itChar);
  56. }
  57. }
  58. out += "\n";
  59. }
  60. }
  61. NS_CC_BEGIN
  62. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_COLOR = "#ShaderETC1ASPositionTextureColor";
  63. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_COLOR_NO_MVP = "#ShaderETC1ASPositionTextureColor_noMVP";
  64. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_GRAY = "#ShaderETC1ASPositionTextureGray";
  65. const char* GLProgram::SHADER_NAME_ETC1AS_POSITION_TEXTURE_GRAY_NO_MVP = "#ShaderETC1ASPositionTextureGray_noMVP";
  66. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR = "ShaderPositionTextureColor";
  67. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP = "ShaderPositionTextureColor_noMVP";
  68. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST = "ShaderPositionTextureColorAlphaTest";
  69. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV = "ShaderPositionTextureColorAlphaTest_NoMV";
  70. const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor";
  71. const char* GLProgram::SHADER_NAME_POSITION_COLOR_TEXASPOINTSIZE = "ShaderPositionColorTexAsPointsize";
  72. const char* GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP = "ShaderPositionColor_noMVP";
  73. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture";
  74. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR = "ShaderPositionTexture_uColor";
  75. const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR = "ShaderPositionTextureA8Color";
  76. const char* GLProgram::SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor";
  77. const char* GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR = "ShaderPositionLengthTextureColor";
  78. const char* GLProgram::SHADER_NAME_POSITION_GRAYSCALE = "ShaderUIGrayScale";
  79. const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL = "ShaderLabelDFNormal";
  80. const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW = "ShaderLabelDFGlow";
  81. const char* GLProgram::SHADER_NAME_LABEL_NORMAL = "ShaderLabelNormal";
  82. const char* GLProgram::SHADER_NAME_LABEL_OUTLINE = "ShaderLabelOutline";
  83. const char* GLProgram::SHADER_3D_POSITION = "Shader3DPosition";
  84. const char* GLProgram::SHADER_3D_POSITION_TEXTURE = "Shader3DPositionTexture";
  85. const char* GLProgram::SHADER_3D_SKINPOSITION_TEXTURE = "Shader3DSkinPositionTexture";
  86. const char* GLProgram::SHADER_3D_POSITION_NORMAL = "Shader3DPositionNormal";
  87. const char* GLProgram::SHADER_3D_POSITION_NORMAL_TEXTURE = "Shader3DPositionNormalTexture";
  88. const char* GLProgram::SHADER_3D_SKINPOSITION_NORMAL_TEXTURE = "Shader3DSkinPositionNormalTexture";
  89. const char* GLProgram::SHADER_3D_POSITION_BUMPEDNORMAL_TEXTURE = "Shader3DPositionBumpedNormalTexture";
  90. const char* GLProgram::SHADER_3D_SKINPOSITION_BUMPEDNORMAL_TEXTURE = "Shader3DSkinPositionBumpedNormalTexture";
  91. const char* GLProgram::SHADER_3D_PARTICLE_COLOR = "Shader3DParticleColor";
  92. const char* GLProgram::SHADER_3D_PARTICLE_TEXTURE = "Shader3DParticleTexture";
  93. const char* GLProgram::SHADER_3D_SKYBOX = "Shader3DSkybox";
  94. const char* GLProgram::SHADER_3D_TERRAIN = "Shader3DTerrain";
  95. const char* GLProgram::SHADER_CAMERA_CLEAR = "ShaderCameraClear";
  96. const char* GLProgram::SHADER_LAYER_RADIAL_GRADIENT = "ShaderLayerRadialGradient";
  97. // uniform names
  98. const char* GLProgram::UNIFORM_NAME_AMBIENT_COLOR = "CC_AmbientColor";
  99. const char* GLProgram::UNIFORM_NAME_P_MATRIX = "CC_PMatrix";
  100. const char* GLProgram::UNIFORM_NAME_MULTIVIEW_P_MATRIX = "CC_MultiViewPMatrix";
  101. const char* GLProgram::UNIFORM_NAME_MV_MATRIX = "CC_MVMatrix";
  102. const char* GLProgram::UNIFORM_NAME_MVP_MATRIX = "CC_MVPMatrix";
  103. const char* GLProgram::UNIFORM_NAME_MULTIVIEW_MVP_MATRIX = "CC_MultiViewMVPMatrix";
  104. const char* GLProgram::UNIFORM_NAME_NORMAL_MATRIX = "CC_NormalMatrix";
  105. const char* GLProgram::UNIFORM_NAME_TIME = "CC_Time";
  106. const char* GLProgram::UNIFORM_NAME_SIN_TIME = "CC_SinTime";
  107. const char* GLProgram::UNIFORM_NAME_COS_TIME = "CC_CosTime";
  108. const char* GLProgram::UNIFORM_NAME_RANDOM01 = "CC_Random01";
  109. const char* GLProgram::UNIFORM_NAME_SAMPLER0 = "CC_Texture0";
  110. const char* GLProgram::UNIFORM_NAME_SAMPLER1 = "CC_Texture1";
  111. const char* GLProgram::UNIFORM_NAME_SAMPLER2 = "CC_Texture2";
  112. const char* GLProgram::UNIFORM_NAME_SAMPLER3 = "CC_Texture3";
  113. const char* GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE = "CC_alpha_value";
  114. // Attribute names
  115. const char* GLProgram::ATTRIBUTE_NAME_COLOR = "a_color";
  116. const char* GLProgram::ATTRIBUTE_NAME_POSITION = "a_position";
  117. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD = "a_texCoord";
  118. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD1 = "a_texCoord1";
  119. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD2 = "a_texCoord2";
  120. const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD3 = "a_texCoord3";
  121. const char* GLProgram::ATTRIBUTE_NAME_NORMAL = "a_normal";
  122. const char* GLProgram::ATTRIBUTE_NAME_BLEND_WEIGHT = "a_blendWeight";
  123. const char* GLProgram::ATTRIBUTE_NAME_BLEND_INDEX = "a_blendIndex";
  124. const char* GLProgram::ATTRIBUTE_NAME_TANGENT = "a_tangent";
  125. const char* GLProgram::ATTRIBUTE_NAME_BINORMAL = "a_binormal";
  126. static const char * COCOS2D_SHADER_UNIFORMS =
  127. "uniform mat4 CC_PMatrix;\n"
  128. "uniform mat4 CC_MultiViewPMatrix[4];\n"
  129. "uniform mat4 CC_MVMatrix;\n"
  130. "uniform mat4 CC_MVPMatrix;\n"
  131. "uniform mat4 CC_MultiViewMVPMatrix[4];\n"
  132. "uniform mat3 CC_NormalMatrix;\n"
  133. "uniform vec4 CC_Time;\n"
  134. "uniform vec4 CC_SinTime;\n"
  135. "uniform vec4 CC_CosTime;\n"
  136. "uniform vec4 CC_Random01;\n"
  137. "uniform sampler2D CC_Texture0;\n"
  138. "uniform sampler2D CC_Texture1;\n"
  139. "uniform sampler2D CC_Texture2;\n"
  140. "uniform sampler2D CC_Texture3;\n"
  141. "//CC INCLUDES END\n\n";
  142. static const std::string EMPTY_DEFINE;
  143. GLProgram* GLProgram::createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray)
  144. {
  145. return createWithByteArrays(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE);
  146. }
  147. GLProgram* GLProgram::createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeDefines)
  148. {
  149. return createWithByteArrays(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE, compileTimeDefines);
  150. }
  151. GLProgram* GLProgram::createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeHeaders, const std::string& compileTimeDefines)
  152. {
  153. auto ret = new (std::nothrow) GLProgram();
  154. if(ret && ret->initWithByteArrays(vShaderByteArray, fShaderByteArray, compileTimeHeaders, compileTimeDefines)) {
  155. ret->link();
  156. ret->updateUniforms();
  157. ret->autorelease();
  158. return ret;
  159. }
  160. CC_SAFE_DELETE(ret);
  161. return nullptr;
  162. }
  163. GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename)
  164. {
  165. return createWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE);
  166. }
  167. GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeDefines)
  168. {
  169. return createWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE, compileTimeDefines);
  170. }
  171. GLProgram* GLProgram::createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& /*compileTimeHeaders*/, const std::string& compileTimeDefines)
  172. {
  173. auto ret = new (std::nothrow) GLProgram();
  174. if(ret && ret->initWithFilenames(vShaderFilename, fShaderFilename, compileTimeDefines)) {
  175. ret->link();
  176. ret->updateUniforms();
  177. ret->autorelease();
  178. return ret;
  179. }
  180. CC_SAFE_DELETE(ret);
  181. return nullptr;
  182. }
  183. GLProgram::GLProgram()
  184. : _program(0)
  185. , _vertShader(0)
  186. , _fragShader(0)
  187. , _flags()
  188. {
  189. _director = Director::getInstance();
  190. CCASSERT(nullptr != _director, "Director is null when init a GLProgram");
  191. memset(_builtInUniforms, 0, sizeof(_builtInUniforms));
  192. }
  193. GLProgram::~GLProgram()
  194. {
  195. CCLOGINFO("%s %d deallocing GLProgram: %p", __FUNCTION__, __LINE__, this);
  196. clearShader();
  197. if (_program)
  198. {
  199. GL::deleteProgram(_program);
  200. }
  201. clearHashUniforms();
  202. }
  203. bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray)
  204. {
  205. return initWithByteArrays(vShaderByteArray, fShaderByteArray, EMPTY_DEFINE);
  206. }
  207. bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeDefines)
  208. {
  209. return initWithByteArrays(vShaderByteArray, fShaderByteArray, "", compileTimeDefines);
  210. }
  211. bool GLProgram::initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray, const std::string& compileTimeHeaders, const std::string& compileTimeDefines)
  212. {
  213. _program = glCreateProgram();
  214. CHECK_GL_ERROR_DEBUG();
  215. // convert defines here. If we do it in "compileShader" we will do it twice.
  216. // a cache for the defines could be useful, but seems like overkill at this point
  217. std::string replacedDefines = "";
  218. replaceDefines(compileTimeDefines, replacedDefines);
  219. _vertShader = _fragShader = 0;
  220. if (vShaderByteArray)
  221. {
  222. if (!compileShader(&_vertShader, GL_VERTEX_SHADER, vShaderByteArray, compileTimeHeaders, replacedDefines))
  223. {
  224. CCLOG("cocos2d: ERROR: Failed to compile vertex shader");
  225. return false;
  226. }
  227. }
  228. // Create and compile fragment shader
  229. if (fShaderByteArray)
  230. {
  231. if (!compileShader(&_fragShader, GL_FRAGMENT_SHADER, fShaderByteArray, compileTimeHeaders, replacedDefines))
  232. {
  233. CCLOG("cocos2d: ERROR: Failed to compile fragment shader");
  234. return false;
  235. }
  236. }
  237. if (_vertShader)
  238. {
  239. glAttachShader(_program, _vertShader);
  240. }
  241. CHECK_GL_ERROR_DEBUG();
  242. if (_fragShader)
  243. {
  244. glAttachShader(_program, _fragShader);
  245. }
  246. clearHashUniforms();
  247. CHECK_GL_ERROR_DEBUG();
  248. return true;
  249. }
  250. bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename)
  251. {
  252. return initWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE);
  253. }
  254. bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeDefines)
  255. {
  256. return initWithFilenames(vShaderFilename, fShaderFilename, EMPTY_DEFINE, compileTimeDefines);
  257. }
  258. bool GLProgram::initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename, const std::string& compileTimeHeaders, const std::string& compileTimeDefines)
  259. {
  260. auto fileUtils = FileUtils::getInstance();
  261. std::string vertexSource = fileUtils->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(vShaderFilename));
  262. std::string fragmentSource = fileUtils->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(fShaderFilename));
  263. return initWithByteArrays(vertexSource.c_str(), fragmentSource.c_str(), compileTimeHeaders, compileTimeDefines);
  264. }
  265. void GLProgram::bindPredefinedVertexAttribs()
  266. {
  267. static const struct {
  268. const char *attributeName;
  269. int location;
  270. } attribute_locations[] =
  271. {
  272. {GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION},
  273. {GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR},
  274. {GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD},
  275. {GLProgram::ATTRIBUTE_NAME_TEX_COORD1, GLProgram::VERTEX_ATTRIB_TEX_COORD1},
  276. {GLProgram::ATTRIBUTE_NAME_TEX_COORD2, GLProgram::VERTEX_ATTRIB_TEX_COORD2},
  277. {GLProgram::ATTRIBUTE_NAME_TEX_COORD3, GLProgram::VERTEX_ATTRIB_TEX_COORD3},
  278. {GLProgram::ATTRIBUTE_NAME_NORMAL, GLProgram::VERTEX_ATTRIB_NORMAL},
  279. };
  280. const int size = sizeof(attribute_locations) / sizeof(attribute_locations[0]);
  281. for(int i=0; i<size;i++) {
  282. glBindAttribLocation(_program, attribute_locations[i].location, attribute_locations[i].attributeName);
  283. }
  284. }
  285. void GLProgram::parseVertexAttribs()
  286. {
  287. //_vertexAttribs.clear();
  288. // Query and store vertex attribute meta-data from the program.
  289. GLint activeAttributes;
  290. GLint length;
  291. glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTES, &activeAttributes);
  292. if(activeAttributes > 0)
  293. {
  294. VertexAttrib attribute;
  295. glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length);
  296. if(length > 0)
  297. {
  298. GLchar* attribName = (GLchar*) alloca(length + 1);
  299. for(int i = 0; i < activeAttributes; ++i)
  300. {
  301. // Query attribute info.
  302. glGetActiveAttrib(_program, i, length, nullptr, &attribute.size, &attribute.type, attribName);
  303. attribName[length] = '\0';
  304. attribute.name = std::string(attribName);
  305. // Query the pre-assigned attribute location
  306. attribute.index = glGetAttribLocation(_program, attribName);
  307. _vertexAttribs[attribute.name] = attribute;
  308. }
  309. }
  310. }
  311. else
  312. {
  313. GLchar ErrorLog[1024];
  314. glGetProgramInfoLog(_program, sizeof(ErrorLog), nullptr, ErrorLog);
  315. CCLOG("Error linking shader program: '%s'\n", ErrorLog);
  316. }
  317. }
  318. void GLProgram::parseUniforms()
  319. {
  320. //_userUniforms.clear();
  321. // Query and store uniforms from the program.
  322. GLint activeUniforms;
  323. glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &activeUniforms);
  324. if(activeUniforms > 0)
  325. {
  326. GLint length;
  327. glGetProgramiv(_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length);
  328. if(length > 0)
  329. {
  330. Uniform uniform;
  331. GLchar* uniformName = (GLchar*)alloca(length + 1);
  332. for(int i = 0; i < activeUniforms; ++i)
  333. {
  334. // Query uniform info.
  335. glGetActiveUniform(_program, i, length, nullptr, &uniform.size, &uniform.type, uniformName);
  336. uniformName[length] = '\0';
  337. // Only add uniforms that are not built-in.
  338. // The ones that start with 'CC_' are built-ins
  339. if(strncmp("CC_", uniformName, 3) != 0) {
  340. // remove possible array '[]' from uniform name
  341. if(length > 3)
  342. {
  343. char* c = strrchr(uniformName, '[');
  344. if(c)
  345. {
  346. *c = '\0';
  347. }
  348. }
  349. uniform.name = std::string(uniformName);
  350. uniform.location = glGetUniformLocation(_program, uniformName);
  351. GLenum __gl_error_code = glGetError();
  352. if (__gl_error_code != GL_NO_ERROR)
  353. {
  354. CCLOG("error: 0x%x uniformName: %s", (int)__gl_error_code, uniformName);
  355. }
  356. assert(__gl_error_code == GL_NO_ERROR);
  357. _userUniforms[uniform.name] = uniform;
  358. }
  359. }
  360. }
  361. }
  362. else
  363. {
  364. GLchar ErrorLog[1024];
  365. glGetProgramInfoLog(_program, sizeof(ErrorLog), nullptr, ErrorLog);
  366. CCLOG("Error linking shader program: '%s'\n", ErrorLog);
  367. }
  368. }
  369. Uniform* GLProgram::getUniform(const std::string &name)
  370. {
  371. const auto itr = _userUniforms.find(name);
  372. if( itr != _userUniforms.end())
  373. return &itr->second;
  374. return nullptr;
  375. }
  376. VertexAttrib* GLProgram::getVertexAttrib(const std::string &name)
  377. {
  378. const auto itr = _vertexAttribs.find(name);
  379. if( itr != _vertexAttribs.end())
  380. return &itr->second;
  381. return nullptr;
  382. }
  383. std::string GLProgram::getDescription() const
  384. {
  385. return StringUtils::format("<GLProgram = "
  386. CC_FORMAT_PRINTF_SIZE_T
  387. " | Program = %i, VertexShader = %i, FragmentShader = %i>",
  388. (size_t)this, _program, _vertShader, _fragShader);
  389. }
  390. bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source)
  391. {
  392. return compileShader(shader, type, source, "");
  393. }
  394. bool GLProgram::compileShader(GLuint* shader, GLenum type, const GLchar* source, const std::string& convertedDefines)
  395. {
  396. return compileShader(shader, type, source, "", convertedDefines);
  397. }
  398. bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source, const std::string& compileTimeHeaders, const std::string& convertedDefines)
  399. {
  400. GLint status;
  401. if (!source)
  402. {
  403. return false;
  404. }
  405. std::string headersDef;
  406. if (compileTimeHeaders.empty()) {
  407. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
  408. headersDef = (type == GL_VERTEX_SHADER ? "precision mediump float;\n precision mediump int;\n" : "precision mediump float;\n precision mediump int;\n");
  409. #elif (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32 && CC_TARGET_PLATFORM != CC_PLATFORM_LINUX && CC_TARGET_PLATFORM != CC_PLATFORM_MAC)
  410. headersDef = (type == GL_VERTEX_SHADER ? "precision highp float;\n precision highp int;\n" : "precision highp float;\n precision mediump int;\n");
  411. #endif
  412. }else{
  413. headersDef = compileTimeHeaders;
  414. }
  415. const GLchar *sources[] = {
  416. headersDef.c_str(),
  417. COCOS2D_SHADER_UNIFORMS,
  418. convertedDefines.c_str(),
  419. source};
  420. *shader = glCreateShader(type);
  421. glShaderSource(*shader, sizeof(sources)/sizeof(*sources), sources, nullptr);
  422. glCompileShader(*shader);
  423. glGetShaderiv(*shader, GL_COMPILE_STATUS, &status);
  424. if (! status)
  425. {
  426. GLsizei length;
  427. glGetShaderiv(*shader, GL_SHADER_SOURCE_LENGTH, &length);
  428. GLchar* src = (GLchar *)malloc(sizeof(GLchar) * length);
  429. glGetShaderSource(*shader, length, nullptr, src);
  430. CCLOG("cocos2d: ERROR: Failed to compile shader:\n%s", src);
  431. if (type == GL_VERTEX_SHADER)
  432. {
  433. CCLOG("cocos2d: %s", getVertexShaderLog().c_str());
  434. }
  435. else
  436. {
  437. CCLOG("cocos2d: %s", getFragmentShaderLog().c_str());
  438. }
  439. free(src);
  440. return false;
  441. }
  442. return (status == GL_TRUE);
  443. }
  444. GLint GLProgram::getAttribLocation(const std::string &attributeName) const
  445. {
  446. return glGetAttribLocation(_program, attributeName.c_str());
  447. }
  448. GLint GLProgram::getUniformLocation(const std::string &attributeName) const
  449. {
  450. return glGetUniformLocation(_program, attributeName.c_str());
  451. }
  452. void GLProgram::bindAttribLocation(const std::string &attributeName, GLuint index) const
  453. {
  454. glBindAttribLocation(_program, index, attributeName.c_str());
  455. }
  456. void GLProgram::updateUniforms()
  457. {
  458. _builtInUniforms[UNIFORM_AMBIENT_COLOR] = glGetUniformLocation(_program, UNIFORM_NAME_AMBIENT_COLOR);
  459. _builtInUniforms[UNIFORM_P_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_P_MATRIX);
  460. _builtInUniforms[UNIFORM_MULTIVIEW_P_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MULTIVIEW_P_MATRIX);
  461. _builtInUniforms[UNIFORM_MV_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MV_MATRIX);
  462. _builtInUniforms[UNIFORM_MVP_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MVP_MATRIX);
  463. _builtInUniforms[UNIFORM_MULTIVIEW_MVP_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_MULTIVIEW_MVP_MATRIX);
  464. _builtInUniforms[UNIFORM_NORMAL_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_NORMAL_MATRIX);
  465. _builtInUniforms[UNIFORM_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_TIME);
  466. _builtInUniforms[UNIFORM_SIN_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_SIN_TIME);
  467. _builtInUniforms[UNIFORM_COS_TIME] = glGetUniformLocation(_program, UNIFORM_NAME_COS_TIME);
  468. _builtInUniforms[UNIFORM_RANDOM01] = glGetUniformLocation(_program, UNIFORM_NAME_RANDOM01);
  469. _builtInUniforms[UNIFORM_SAMPLER0] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER0);
  470. _builtInUniforms[UNIFORM_SAMPLER1] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER1);
  471. _builtInUniforms[UNIFORM_SAMPLER2] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER2);
  472. _builtInUniforms[UNIFORM_SAMPLER3] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER3);
  473. _flags.usesP = _builtInUniforms[UNIFORM_P_MATRIX] != -1;
  474. _flags.usesMultiViewP = _builtInUniforms[UNIFORM_MULTIVIEW_P_MATRIX] != -1;
  475. _flags.usesMV = _builtInUniforms[UNIFORM_MV_MATRIX] != -1;
  476. _flags.usesMVP = _builtInUniforms[UNIFORM_MVP_MATRIX] != -1;
  477. _flags.usesMultiViewMVP = _builtInUniforms[UNIFORM_MULTIVIEW_MVP_MATRIX] != -1;
  478. _flags.usesNormal = _builtInUniforms[UNIFORM_NORMAL_MATRIX] != -1;
  479. _flags.usesTime = (
  480. _builtInUniforms[UNIFORM_TIME] != -1 ||
  481. _builtInUniforms[UNIFORM_SIN_TIME] != -1 ||
  482. _builtInUniforms[UNIFORM_COS_TIME] != -1
  483. );
  484. _flags.usesRandom = _builtInUniforms[UNIFORM_RANDOM01] != -1;
  485. this->use();
  486. // Since sample most probably won't change, set it to 0,1,2,3 now.
  487. if(_builtInUniforms[UNIFORM_SAMPLER0] != -1)
  488. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER0], 0);
  489. if(_builtInUniforms[UNIFORM_SAMPLER1] != -1)
  490. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER1], 1);
  491. if(_builtInUniforms[UNIFORM_SAMPLER2] != -1)
  492. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER2], 2);
  493. if(_builtInUniforms[UNIFORM_SAMPLER3] != -1)
  494. setUniformLocationWith1i(_builtInUniforms[UNIFORM_SAMPLER3], 3);
  495. // clear any glErrors created by any not found uniforms
  496. glGetError();
  497. }
  498. bool GLProgram::link()
  499. {
  500. CCASSERT(_program != 0, "Cannot link invalid program");
  501. GLint status = GL_TRUE;
  502. bindPredefinedVertexAttribs();
  503. glLinkProgram(_program);
  504. // Calling glGetProgramiv(...GL_LINK_STATUS...) will force linking of the program at this moment.
  505. // Otherwise, they might be linked when they are used for the first time. (I guess this depends on the driver implementation)
  506. // So it might slow down the "booting" process on certain devices. But, on the other hand it is important to know if the shader
  507. // linked successfully. Some shaders might be downloaded in runtime so, release version should have this check.
  508. // For more info, see Github issue #16231
  509. glGetProgramiv(_program, GL_LINK_STATUS, &status);
  510. if (status == GL_FALSE)
  511. {
  512. CCLOG("cocos2d: ERROR: Failed to link program: %i", _program);
  513. GL::deleteProgram(_program);
  514. _program = 0;
  515. }
  516. else
  517. {
  518. parseVertexAttribs();
  519. parseUniforms();
  520. clearShader();
  521. }
  522. return (status == GL_TRUE);
  523. }
  524. void GLProgram::use()
  525. {
  526. GL::useProgram(_program);
  527. }
  528. static std::string logForOpenGLShader(GLuint shader)
  529. {
  530. GLint logLength = 0;
  531. glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
  532. if (logLength < 1)
  533. return "";
  534. char *logBytes = (char*)malloc(sizeof(char) * logLength);
  535. glGetShaderInfoLog(shader, logLength, nullptr, logBytes);
  536. std::string ret(logBytes);
  537. free(logBytes);
  538. return ret;
  539. }
  540. static std::string logForOpenGLProgram(GLuint program)
  541. {
  542. GLint logLength = 0;
  543. glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
  544. if (logLength < 1)
  545. return "";
  546. char *logBytes = (char*)malloc(sizeof(char) * logLength);
  547. glGetProgramInfoLog(program, logLength, nullptr, logBytes);
  548. std::string ret(logBytes);
  549. free(logBytes);
  550. return ret;
  551. }
  552. std::string GLProgram::getVertexShaderLog() const
  553. {
  554. return cocos2d::logForOpenGLShader(_vertShader);
  555. }
  556. std::string GLProgram::getFragmentShaderLog() const
  557. {
  558. return cocos2d::logForOpenGLShader(_fragShader);
  559. }
  560. std::string GLProgram::getProgramLog() const
  561. {
  562. return logForOpenGLProgram(_program);
  563. }
  564. // Uniform cache
  565. bool GLProgram::updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes)
  566. {
  567. if (location < 0)
  568. {
  569. return false;
  570. }
  571. bool updated = true;
  572. auto element = _hashForUniforms.find(location);
  573. if (element == _hashForUniforms.end())
  574. {
  575. GLvoid* value = malloc(bytes);
  576. memcpy(value, data, bytes );
  577. _hashForUniforms.emplace(location, std::make_pair(value, bytes));
  578. }
  579. else
  580. {
  581. if (element->second.second < bytes)
  582. {
  583. GLvoid* value = realloc(element->second.first, bytes);
  584. memcpy(value, data, bytes);
  585. _hashForUniforms[location] = std::make_pair(value, bytes);
  586. }
  587. else
  588. {
  589. if (memcmp(element->second.first, data, bytes) == 0)
  590. {
  591. updated = false;
  592. }
  593. else
  594. memcpy(element->second.first, data, bytes);
  595. }
  596. }
  597. return updated;
  598. }
  599. GLint GLProgram::getUniformLocationForName(const char* name) const
  600. {
  601. CCASSERT(name != nullptr, "Invalid uniform name" );
  602. CCASSERT(_program != 0, "Invalid operation. Cannot get uniform location when program is not initialized");
  603. return glGetUniformLocation(_program, name);
  604. }
  605. void GLProgram::setUniformLocationWith1i(GLint location, GLint i1)
  606. {
  607. bool updated = updateUniformLocation(location, &i1, sizeof(i1)*1);
  608. if (updated)
  609. {
  610. glUniform1i( (GLint)location, i1);
  611. }
  612. }
  613. void GLProgram::setUniformLocationWith2i(GLint location, GLint i1, GLint i2)
  614. {
  615. GLint ints[2] = {i1,i2};
  616. bool updated = updateUniformLocation(location, ints, sizeof(ints));
  617. if (updated)
  618. {
  619. glUniform2i( (GLint)location, i1, i2);
  620. }
  621. }
  622. void GLProgram::setUniformLocationWith3i(GLint location, GLint i1, GLint i2, GLint i3)
  623. {
  624. GLint ints[3] = {i1,i2,i3};
  625. bool updated = updateUniformLocation(location, ints, sizeof(ints));
  626. if (updated)
  627. {
  628. glUniform3i( (GLint)location, i1, i2, i3);
  629. }
  630. }
  631. void GLProgram::setUniformLocationWith4i(GLint location, GLint i1, GLint i2, GLint i3, GLint i4)
  632. {
  633. GLint ints[4] = {i1,i2,i3,i4};
  634. bool updated = updateUniformLocation(location, ints, sizeof(ints));
  635. if (updated)
  636. {
  637. glUniform4i( (GLint)location, i1, i2, i3, i4);
  638. }
  639. }
  640. void GLProgram::setUniformLocationWith2iv(GLint location, GLint* ints, unsigned int numberOfArrays)
  641. {
  642. bool updated = updateUniformLocation(location, ints, sizeof(int)*2*numberOfArrays);
  643. if (updated)
  644. {
  645. glUniform2iv( (GLint)location, (GLsizei)numberOfArrays, ints );
  646. }
  647. }
  648. void GLProgram::setUniformLocationWith3iv(GLint location, GLint* ints, unsigned int numberOfArrays)
  649. {
  650. bool updated = updateUniformLocation(location, ints, sizeof(int)*3*numberOfArrays);
  651. if (updated)
  652. {
  653. glUniform3iv( (GLint)location, (GLsizei)numberOfArrays, ints );
  654. }
  655. }
  656. void GLProgram::setUniformLocationWith4iv(GLint location, GLint* ints, unsigned int numberOfArrays)
  657. {
  658. bool updated = updateUniformLocation(location, ints, sizeof(int)*4*numberOfArrays);
  659. if (updated)
  660. {
  661. glUniform4iv( (GLint)location, (GLsizei)numberOfArrays, ints );
  662. }
  663. }
  664. void GLProgram::setUniformLocationWith1f(GLint location, GLfloat f1)
  665. {
  666. bool updated = updateUniformLocation(location, &f1, sizeof(f1)*1);
  667. if (updated)
  668. {
  669. glUniform1f( (GLint)location, f1);
  670. }
  671. }
  672. void GLProgram::setUniformLocationWith2f(GLint location, GLfloat f1, GLfloat f2)
  673. {
  674. GLfloat floats[2] = {f1,f2};
  675. bool updated = updateUniformLocation(location, floats, sizeof(floats));
  676. if (updated)
  677. {
  678. glUniform2f( (GLint)location, f1, f2);
  679. }
  680. }
  681. void GLProgram::setUniformLocationWith3f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3)
  682. {
  683. GLfloat floats[3] = {f1,f2,f3};
  684. bool updated = updateUniformLocation(location, floats, sizeof(floats));
  685. if (updated)
  686. {
  687. glUniform3f( (GLint)location, f1, f2, f3);
  688. }
  689. }
  690. void GLProgram::setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4)
  691. {
  692. GLfloat floats[4] = {f1,f2,f3,f4};
  693. bool updated = updateUniformLocation(location, floats, sizeof(floats));
  694. if (updated)
  695. {
  696. glUniform4f( (GLint)location, f1, f2, f3,f4);
  697. }
  698. }
  699. void GLProgram::setUniformLocationWith1fv( GLint location, const GLfloat* floats, unsigned int numberOfArrays )
  700. {
  701. bool updated = updateUniformLocation(location, floats, sizeof(float)*numberOfArrays);
  702. if (updated)
  703. {
  704. glUniform1fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  705. }
  706. }
  707. void GLProgram::setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
  708. {
  709. bool updated = updateUniformLocation(location, floats, sizeof(float)*2*numberOfArrays);
  710. if (updated)
  711. {
  712. glUniform2fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  713. }
  714. }
  715. void GLProgram::setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
  716. {
  717. bool updated = updateUniformLocation(location, floats, sizeof(float)*3*numberOfArrays);
  718. if (updated)
  719. {
  720. glUniform3fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  721. }
  722. }
  723. void GLProgram::setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
  724. {
  725. bool updated = updateUniformLocation(location, floats, sizeof(float)*4*numberOfArrays);
  726. if (updated)
  727. {
  728. glUniform4fv( (GLint)location, (GLsizei)numberOfArrays, floats );
  729. }
  730. }
  731. void GLProgram::setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) {
  732. bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*4*numberOfMatrices);
  733. if (updated)
  734. {
  735. glUniformMatrix2fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
  736. }
  737. }
  738. void GLProgram::setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) {
  739. bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*9*numberOfMatrices);
  740. if (updated)
  741. {
  742. glUniformMatrix3fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
  743. }
  744. }
  745. void GLProgram::setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices)
  746. {
  747. bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*16*numberOfMatrices);
  748. if (updated)
  749. {
  750. glUniformMatrix4fv( (GLint)location, (GLsizei)numberOfMatrices, GL_FALSE, matrixArray);
  751. }
  752. }
  753. void GLProgram::setUniformsForBuiltins()
  754. {
  755. setUniformsForBuiltins(_director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW));
  756. }
  757. void GLProgram::setUniformsForBuiltins(const Mat4 &matrixMV)
  758. {
  759. const auto& matrixP = _director->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
  760. if (_flags.usesP)
  761. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_P_MATRIX], matrixP.m, 1);
  762. if (_flags.usesMultiViewP)
  763. {
  764. Mat4 mats[4];
  765. const auto stackSize = std::min<size_t>(_director->getProjectionMatrixStackSize(), 4);
  766. for (size_t i = 0; i < stackSize; ++i) {
  767. mats[i] = _director->getProjectionMatrix(i);
  768. }
  769. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MULTIVIEW_P_MATRIX], mats[0].m, 4);
  770. }
  771. if (_flags.usesMV)
  772. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MV_MATRIX], matrixMV.m, 1);
  773. if (_flags.usesMVP)
  774. {
  775. Mat4 matrixMVP = matrixP * matrixMV;
  776. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MVP_MATRIX], matrixMVP.m, 1);
  777. }
  778. if (_flags.usesMultiViewMVP)
  779. {
  780. Mat4 mats[4];
  781. const auto stackSize = std::min<size_t>(_director->getProjectionMatrixStackSize(), 4);
  782. for (size_t i = 0; i < stackSize; ++i) {
  783. mats[i] = _director->getProjectionMatrix(i) * matrixMV;
  784. }
  785. setUniformLocationWithMatrix4fv(_builtInUniforms[UNIFORM_MULTIVIEW_MVP_MATRIX], mats[0].m, 4);
  786. }
  787. if (_flags.usesNormal)
  788. {
  789. Mat4 mvInverse = matrixMV;
  790. mvInverse.m[12] = mvInverse.m[13] = mvInverse.m[14] = 0.0f;
  791. mvInverse.inverse();
  792. mvInverse.transpose();
  793. GLfloat normalMat[9];
  794. normalMat[0] = mvInverse.m[0];normalMat[1] = mvInverse.m[1];normalMat[2] = mvInverse.m[2];
  795. normalMat[3] = mvInverse.m[4];normalMat[4] = mvInverse.m[5];normalMat[5] = mvInverse.m[6];
  796. normalMat[6] = mvInverse.m[8];normalMat[7] = mvInverse.m[9];normalMat[8] = mvInverse.m[10];
  797. setUniformLocationWithMatrix3fv(_builtInUniforms[UNIFORM_NORMAL_MATRIX], normalMat, 1);
  798. }
  799. if (_flags.usesTime) {
  800. // This doesn't give the most accurate global time value.
  801. // Cocos2D doesn't store a high precision time value, so this will have to do.
  802. // Getting Mach time per frame per shader using time could be extremely expensive.
  803. float time = _director->getTotalFrames() * _director->getAnimationInterval();
  804. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_TIME], time/10.0f, time, time*2, time*4);
  805. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_SIN_TIME], time/8.0f, time/4.0f, time/2.0f, sinf(time));
  806. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_COS_TIME], time/8.0f, time/4.0f, time/2.0f, cosf(time));
  807. }
  808. if (_flags.usesRandom)
  809. setUniformLocationWith4f(_builtInUniforms[GLProgram::UNIFORM_RANDOM01], CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1());
  810. }
  811. void GLProgram::reset()
  812. {
  813. _vertShader = _fragShader = 0;
  814. memset(_builtInUniforms, 0, sizeof(_builtInUniforms));
  815. // it is already deallocated by android
  816. //GL::deleteProgram(_program);
  817. _program = 0;
  818. clearHashUniforms();
  819. }
  820. inline void GLProgram::clearShader()
  821. {
  822. if (_vertShader)
  823. {
  824. glDeleteShader(_vertShader);
  825. }
  826. if (_fragShader)
  827. {
  828. glDeleteShader(_fragShader);
  829. }
  830. _vertShader = _fragShader = 0;
  831. }
  832. inline void GLProgram::clearHashUniforms()
  833. {
  834. for (auto e: _hashForUniforms)
  835. {
  836. free(e.second.first);
  837. }
  838. _hashForUniforms.clear();
  839. }
  840. NS_CC_END