Effect.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. #include "Base.h"
  2. #include "Effect.h"
  3. #include "FileSystem.h"
  4. #define OPENGL_ES_DEFINE "#define OPENGL_ES\n"
  5. namespace gameplay
  6. {
  7. // Cache of unique effects.
  8. static std::map<std::string, Effect*> __effectCache;
  9. static Effect* __currentEffect = NULL;
  10. Effect::Effect() : _program(0)
  11. {
  12. }
  13. Effect::~Effect()
  14. {
  15. // Remove this effect from the cache.
  16. __effectCache.erase(_id);
  17. // Free uniforms.
  18. for (std::map<std::string, Uniform*>::iterator itr = _uniforms.begin(); itr != _uniforms.end(); itr++)
  19. {
  20. SAFE_DELETE(itr->second);
  21. }
  22. if (_program)
  23. {
  24. // If our program object is currently bound, unbind it before we're destroyed.
  25. if (__currentEffect == this)
  26. {
  27. GL_ASSERT( glUseProgram(0) );
  28. __currentEffect = NULL;
  29. }
  30. GL_ASSERT( glDeleteProgram(_program) );
  31. _program = 0;
  32. }
  33. }
  34. Effect* Effect::createFromFile(const char* vshPath, const char* fshPath, const char* defines)
  35. {
  36. GP_ASSERT(vshPath);
  37. GP_ASSERT(fshPath);
  38. // Search the effect cache for an identical effect that is already loaded.
  39. std::string uniqueId = vshPath;
  40. uniqueId += ';';
  41. uniqueId += fshPath;
  42. uniqueId += ';';
  43. if (defines)
  44. {
  45. uniqueId += defines;
  46. }
  47. std::map<std::string, Effect*>::const_iterator itr = __effectCache.find(uniqueId);
  48. if (itr != __effectCache.end())
  49. {
  50. // Found an exiting effect with this id, so increase its ref count and return it.
  51. GP_ASSERT(itr->second);
  52. itr->second->addRef();
  53. return itr->second;
  54. }
  55. // Read source from file.
  56. char* vshSource = FileSystem::readAll(vshPath);
  57. if (vshSource == NULL)
  58. {
  59. GP_ERROR("Failed to read vertex shader from file '%s'.", vshPath);
  60. return NULL;
  61. }
  62. char* fshSource = FileSystem::readAll(fshPath);
  63. if (fshSource == NULL)
  64. {
  65. GP_ERROR("Failed to read fragment shader from file '%s'.", fshPath);
  66. SAFE_DELETE_ARRAY(vshSource);
  67. return NULL;
  68. }
  69. Effect* effect = createFromSource(vshPath, vshSource, fshPath, fshSource, defines);
  70. SAFE_DELETE_ARRAY(vshSource);
  71. SAFE_DELETE_ARRAY(fshSource);
  72. if (effect == NULL)
  73. {
  74. GP_ERROR("Failed to create effect from shaders '%s', '%s'.", vshPath, fshPath);
  75. }
  76. else
  77. {
  78. // Store this effect in the cache.
  79. effect->_id = uniqueId;
  80. __effectCache[uniqueId] = effect;
  81. }
  82. return effect;
  83. }
  84. Effect* Effect::createFromSource(const char* vshSource, const char* fshSource, const char* defines)
  85. {
  86. return createFromSource(NULL, vshSource, NULL, fshSource, defines);
  87. }
  88. static void replaceDefines(const char* defines, std::string& out)
  89. {
  90. if (defines && strlen(defines) != 0)
  91. {
  92. out = defines;
  93. unsigned int pos;
  94. out.insert(0, "#define ");
  95. while ((pos = out.find(';')) != std::string::npos)
  96. {
  97. out.replace(pos, 1, "\n#define ");
  98. }
  99. out += "\n";
  100. }
  101. #ifdef OPENGL_ES
  102. out.insert(0, OPENGL_ES_DEFINE);
  103. #endif
  104. }
  105. static void replaceIncludes(const char* filepath, const char* source, std::string& out)
  106. {
  107. // Replace the #include "xxxx.xxx" with the sourced file contents of "filepath/xxxx.xxx"
  108. std::string str = source;
  109. size_t lastPos = 0;
  110. size_t headPos = 0;
  111. size_t tailPos = 0;
  112. size_t fileLen = str.length();
  113. tailPos = fileLen;
  114. while (headPos < fileLen)
  115. {
  116. lastPos = headPos;
  117. if (headPos == 0)
  118. {
  119. // find the first "#include"
  120. headPos = str.find("#include");
  121. }
  122. else
  123. {
  124. // find the next "#include"
  125. headPos = str.find("#include", headPos + 1);
  126. }
  127. // If "#include" is found
  128. if (headPos != std::string::npos)
  129. {
  130. // append from our last position for the legth (head - last position)
  131. out.append(str.substr(lastPos, headPos - lastPos));
  132. // find the start quote "
  133. size_t startQuote = str.find("\"", headPos) + 1;
  134. if (startQuote == std::string::npos)
  135. {
  136. // We have started an "#include" but missing the leading quote "
  137. GP_ERROR("Compile failed for shader '%s' missing leading \".", filepath);
  138. return;
  139. }
  140. // find the end quote "
  141. size_t endQuote = str.find("\"", startQuote);
  142. if (endQuote == std::string::npos)
  143. {
  144. // We have a start quote but missing the trailing quote "
  145. GP_ERROR("Compile failed for shader '%s' missing trailing \".", filepath);
  146. return;
  147. }
  148. // jump the head position past the end quote
  149. headPos = endQuote + 1;
  150. // File path to include and 'stitch' in the value in the quotes to the file path and source it.
  151. std::string filepathStr = filepath;
  152. std::string directoryPath = filepathStr.substr(0, filepathStr.rfind('/') + 1);
  153. size_t len = endQuote - (startQuote);
  154. std::string includeStr = str.substr(startQuote, len);
  155. directoryPath.append(includeStr);
  156. const char* includedSource = FileSystem::readAll(directoryPath.c_str());
  157. if (includedSource == NULL)
  158. {
  159. GP_ERROR("Compile failed for shader '%s' invalid filepath.", filepathStr.c_str());
  160. return;
  161. }
  162. else
  163. {
  164. // Valid file so lets attempt to see if we need to append anything to it too (recurse...)
  165. replaceIncludes(directoryPath.c_str(), includedSource, out);
  166. SAFE_DELETE_ARRAY(includedSource);
  167. }
  168. }
  169. else
  170. {
  171. // Append the remaining
  172. out.append(str.c_str(), lastPos, tailPos);
  173. }
  174. }
  175. }
  176. static void writeShaderToErrorFile(const char* filePath, const char* source)
  177. {
  178. std::string path = filePath;
  179. path += ".err";
  180. FILE* file = FileSystem::openFile(path.c_str(), "wb");
  181. int err = ferror(file);
  182. fwrite(source, 1, strlen(source), file);
  183. fclose(file);
  184. }
  185. Effect* Effect::createFromSource(const char* vshPath, const char* vshSource, const char* fshPath, const char* fshSource, const char* defines)
  186. {
  187. GP_ASSERT(vshSource);
  188. GP_ASSERT(fshSource);
  189. const unsigned int SHADER_SOURCE_LENGTH = 3;
  190. const GLchar* shaderSource[SHADER_SOURCE_LENGTH];
  191. char* infoLog = NULL;
  192. GLuint vertexShader;
  193. GLuint fragmentShader;
  194. GLuint program;
  195. GLint length;
  196. GLint success;
  197. // Replace all comma seperated definitions with #define prefix and \n suffix
  198. std::string definesStr = "";
  199. replaceDefines(defines, definesStr);
  200. shaderSource[0] = definesStr.c_str();
  201. shaderSource[1] = "\n";
  202. std::string vshSourceStr = "";
  203. if (vshPath)
  204. {
  205. // Replace the #include "xxxxx.xxx" with the sources that come from file paths
  206. replaceIncludes(vshPath, vshSource, vshSourceStr);
  207. if (vshSource && strlen(vshSource) != 0)
  208. vshSourceStr += "\n";
  209. //writeShaderToErrorFile(vshPath, vshSourceStr.c_str()); // Debugging
  210. }
  211. shaderSource[2] = vshPath ? vshSourceStr.c_str() : vshSource;
  212. GL_ASSERT( vertexShader = glCreateShader(GL_VERTEX_SHADER) );
  213. GL_ASSERT( glShaderSource(vertexShader, SHADER_SOURCE_LENGTH, shaderSource, NULL) );
  214. GL_ASSERT( glCompileShader(vertexShader) );
  215. GL_ASSERT( glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success) );
  216. if (success != GL_TRUE)
  217. {
  218. GL_ASSERT( glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &length) );
  219. if (length > 0)
  220. {
  221. infoLog = new char[length];
  222. GL_ASSERT( glGetShaderInfoLog(vertexShader, length, NULL, infoLog) );
  223. infoLog[length-1] = '\0';
  224. }
  225. // Write out the expanded shader file.
  226. if (vshPath)
  227. writeShaderToErrorFile(vshPath, shaderSource[2]);
  228. GP_ERROR("Compile failed for vertex shader '%s' with error '%s'.", vshPath == NULL ? "NULL" : vshPath, infoLog == NULL ? "" : infoLog);
  229. SAFE_DELETE_ARRAY(infoLog);
  230. // Clean up.
  231. GL_ASSERT( glDeleteShader(vertexShader) );
  232. return NULL;
  233. }
  234. // Compile the fragment shader.
  235. std::string fshSourceStr;
  236. if (fshPath)
  237. {
  238. // Replace the #include "xxxxx.xxx" with the sources that come from file paths
  239. replaceIncludes(fshPath, fshSource, fshSourceStr);
  240. if (fshSource && strlen(fshSource) != 0)
  241. fshSourceStr += "\n";
  242. //writeShaderToErrorFile(fshPath, fshSourceStr.c_str()); // Debugging
  243. }
  244. shaderSource[2] = fshPath ? fshSourceStr.c_str() : fshSource;
  245. GL_ASSERT( fragmentShader = glCreateShader(GL_FRAGMENT_SHADER) );
  246. GL_ASSERT( glShaderSource(fragmentShader, SHADER_SOURCE_LENGTH, shaderSource, NULL) );
  247. GL_ASSERT( glCompileShader(fragmentShader) );
  248. GL_ASSERT( glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success) );
  249. if (success != GL_TRUE)
  250. {
  251. GL_ASSERT( glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &length) );
  252. if (length > 0)
  253. {
  254. infoLog = new char[length];
  255. GL_ASSERT( glGetShaderInfoLog(fragmentShader, length, NULL, infoLog) );
  256. infoLog[length-1] = '\0';
  257. }
  258. // Write out the expanded shader file.
  259. if (fshPath)
  260. writeShaderToErrorFile(fshPath, shaderSource[2]);
  261. GP_ERROR("Compile failed for fragment shader (%s): %s", fshPath == NULL ? "NULL" : fshPath, infoLog == NULL ? "" : infoLog);
  262. SAFE_DELETE_ARRAY(infoLog);
  263. // Clean up.
  264. GL_ASSERT( glDeleteShader(vertexShader) );
  265. GL_ASSERT( glDeleteShader(fragmentShader) );
  266. return NULL;
  267. }
  268. // Link program.
  269. GL_ASSERT( program = glCreateProgram() );
  270. GL_ASSERT( glAttachShader(program, vertexShader) );
  271. GL_ASSERT( glAttachShader(program, fragmentShader) );
  272. GL_ASSERT( glLinkProgram(program) );
  273. GL_ASSERT( glGetProgramiv(program, GL_LINK_STATUS, &success) );
  274. // Delete shaders after linking.
  275. GL_ASSERT( glDeleteShader(vertexShader) );
  276. GL_ASSERT( glDeleteShader(fragmentShader) );
  277. // Check link status.
  278. if (success != GL_TRUE)
  279. {
  280. GL_ASSERT( glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length) );
  281. if (length > 0)
  282. {
  283. infoLog = new char[length];
  284. GL_ASSERT( glGetProgramInfoLog(program, length, NULL, infoLog) );
  285. infoLog[length-1] = '\0';
  286. }
  287. GP_ERROR("Linking program failed (%s,%s): %s", vshPath == NULL ? "NULL" : vshPath, fshPath == NULL ? "NULL" : fshPath, infoLog == NULL ? "" : infoLog);
  288. SAFE_DELETE_ARRAY(infoLog);
  289. // Clean up.
  290. GL_ASSERT( glDeleteProgram(program) );
  291. return NULL;
  292. }
  293. // Create and return the new Effect.
  294. Effect* effect = new Effect();
  295. effect->_program = program;
  296. // Query and store vertex attribute meta-data from the program.
  297. // NOTE: Rather than using glBindAttribLocation to explicitly specify our own
  298. // preferred attribute locations, we're going to query the locations that were
  299. // automatically bound by the GPU. While it can sometimes be convenient to use
  300. // glBindAttribLocation, some vendors actually reserve certain attribute indices
  301. // and thereore using this function can create compatibility issues between
  302. // different hardware vendors.
  303. GLint activeAttributes;
  304. GL_ASSERT( glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES, &activeAttributes) );
  305. if (activeAttributes > 0)
  306. {
  307. GL_ASSERT( glGetProgramiv(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length) );
  308. if (length > 0)
  309. {
  310. GLchar* attribName = new GLchar[length + 1];
  311. GLint attribSize;
  312. GLenum attribType;
  313. GLint attribLocation;
  314. for (int i = 0; i < activeAttributes; ++i)
  315. {
  316. // Query attribute info.
  317. GL_ASSERT( glGetActiveAttrib(program, i, length, NULL, &attribSize, &attribType, attribName) );
  318. attribName[length] = '\0';
  319. // Query the pre-assigned attribute location.
  320. GL_ASSERT( attribLocation = glGetAttribLocation(program, attribName) );
  321. // Assign the vertex attribute mapping for the effect.
  322. effect->_vertexAttributes[attribName] = attribLocation;
  323. }
  324. SAFE_DELETE_ARRAY(attribName);
  325. }
  326. }
  327. // Query and store uniforms from the program.
  328. GLint activeUniforms;
  329. GL_ASSERT( glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  330. if (activeUniforms > 0)
  331. {
  332. GL_ASSERT( glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length) );
  333. if (length > 0)
  334. {
  335. GLchar* uniformName = new GLchar[length + 1];
  336. GLint uniformSize;
  337. GLenum uniformType;
  338. GLint uniformLocation;
  339. unsigned int samplerIndex = 0;
  340. for (int i = 0; i < activeUniforms; ++i)
  341. {
  342. // Query uniform info.
  343. GL_ASSERT( glGetActiveUniform(program, i, length, NULL, &uniformSize, &uniformType, uniformName) );
  344. uniformName[length] = '\0'; // null terminate
  345. if (uniformSize > 1 && length > 3)
  346. {
  347. // This is an array uniform. I'm stripping array indexers off it since GL does not
  348. // seem to be consistent across different drivers/implementations in how it returns
  349. // array uniforms. On some systems it will return "u_matrixArray", while on others
  350. // it will return "u_matrixArray[0]".
  351. char* c = strrchr(uniformName, '[');
  352. if (c)
  353. {
  354. *c = '\0';
  355. }
  356. }
  357. // Query the pre-assigned uniform location.
  358. GL_ASSERT( uniformLocation = glGetUniformLocation(program, uniformName) );
  359. Uniform* uniform = new Uniform();
  360. uniform->_effect = effect;
  361. uniform->_name = uniformName;
  362. uniform->_location = uniformLocation;
  363. uniform->_type = uniformType;
  364. uniform->_index = uniformType == GL_SAMPLER_2D ? (samplerIndex++) : 0;
  365. effect->_uniforms[uniformName] = uniform;
  366. }
  367. SAFE_DELETE_ARRAY(uniformName);
  368. }
  369. }
  370. return effect;
  371. }
  372. const char* Effect::getId() const
  373. {
  374. return _id.c_str();
  375. }
  376. VertexAttribute Effect::getVertexAttribute(const char* name) const
  377. {
  378. std::map<std::string, VertexAttribute>::const_iterator itr = _vertexAttributes.find(name);
  379. return (itr == _vertexAttributes.end() ? -1 : itr->second);
  380. }
  381. Uniform* Effect::getUniform(const char* name) const
  382. {
  383. std::map<std::string, Uniform*>::const_iterator itr = _uniforms.find(name);
  384. return (itr == _uniforms.end() ? NULL : itr->second);
  385. }
  386. Uniform* Effect::getUniform(unsigned int index) const
  387. {
  388. unsigned int i = 0;
  389. for (std::map<std::string, Uniform*>::const_iterator itr = _uniforms.begin(); itr != _uniforms.end(); itr++, i++)
  390. {
  391. if (i == index)
  392. {
  393. return itr->second;
  394. }
  395. }
  396. return NULL;
  397. }
  398. unsigned int Effect::getUniformCount() const
  399. {
  400. return _uniforms.size();
  401. }
  402. void Effect::setValue(Uniform* uniform, float value)
  403. {
  404. GP_ASSERT(uniform);
  405. GL_ASSERT( glUniform1f(uniform->_location, value) );
  406. }
  407. void Effect::setValue(Uniform* uniform, const float* values, unsigned int count)
  408. {
  409. GP_ASSERT(uniform);
  410. GP_ASSERT(values);
  411. GL_ASSERT( glUniform1fv(uniform->_location, count, values) );
  412. }
  413. void Effect::setValue(Uniform* uniform, int value)
  414. {
  415. GP_ASSERT(uniform);
  416. GL_ASSERT( glUniform1i(uniform->_location, value) );
  417. }
  418. void Effect::setValue(Uniform* uniform, const int* values, unsigned int count)
  419. {
  420. GP_ASSERT(uniform);
  421. GP_ASSERT(values);
  422. GL_ASSERT( glUniform1iv(uniform->_location, count, values) );
  423. }
  424. void Effect::setValue(Uniform* uniform, const Matrix& value)
  425. {
  426. GP_ASSERT(uniform);
  427. GL_ASSERT( glUniformMatrix4fv(uniform->_location, 1, GL_FALSE, value.m) );
  428. }
  429. void Effect::setValue(Uniform* uniform, const Matrix* values, unsigned int count)
  430. {
  431. GP_ASSERT(uniform);
  432. GP_ASSERT(values);
  433. GL_ASSERT( glUniformMatrix4fv(uniform->_location, count, GL_FALSE, (GLfloat*)values) );
  434. }
  435. void Effect::setValue(Uniform* uniform, const Vector2& value)
  436. {
  437. GP_ASSERT(uniform);
  438. GL_ASSERT( glUniform2f(uniform->_location, value.x, value.y) );
  439. }
  440. void Effect::setValue(Uniform* uniform, const Vector2* values, unsigned int count)
  441. {
  442. GP_ASSERT(uniform);
  443. GP_ASSERT(values);
  444. GL_ASSERT( glUniform2fv(uniform->_location, count, (GLfloat*)values) );
  445. }
  446. void Effect::setValue(Uniform* uniform, const Vector3& value)
  447. {
  448. GP_ASSERT(uniform);
  449. GL_ASSERT( glUniform3f(uniform->_location, value.x, value.y, value.z) );
  450. }
  451. void Effect::setValue(Uniform* uniform, const Vector3* values, unsigned int count)
  452. {
  453. GP_ASSERT(uniform);
  454. GP_ASSERT(values);
  455. GL_ASSERT( glUniform3fv(uniform->_location, count, (GLfloat*)values) );
  456. }
  457. void Effect::setValue(Uniform* uniform, const Vector4& value)
  458. {
  459. GP_ASSERT(uniform);
  460. GL_ASSERT( glUniform4f(uniform->_location, value.x, value.y, value.z, value.w) );
  461. }
  462. void Effect::setValue(Uniform* uniform, const Vector4* values, unsigned int count)
  463. {
  464. GP_ASSERT(uniform);
  465. GP_ASSERT(values);
  466. GL_ASSERT( glUniform4fv(uniform->_location, count, (GLfloat*)values) );
  467. }
  468. void Effect::setValue(Uniform* uniform, const Texture::Sampler* sampler)
  469. {
  470. GP_ASSERT(uniform);
  471. GP_ASSERT(uniform->_type == GL_SAMPLER_2D);
  472. GP_ASSERT(sampler);
  473. GL_ASSERT( glActiveTexture(GL_TEXTURE0 + uniform->_index) );
  474. // Bind the sampler - this binds the texture and applies sampler state
  475. const_cast<Texture::Sampler*>(sampler)->bind();
  476. GL_ASSERT( glUniform1i(uniform->_location, uniform->_index) );
  477. }
  478. void Effect::bind()
  479. {
  480. glUseProgram(_program) ;
  481. GLenum test = glGetError();
  482. __currentEffect = this;
  483. }
  484. Effect* Effect::getCurrentEffect()
  485. {
  486. return __currentEffect;
  487. }
  488. Uniform::Uniform() :
  489. _location(-1), _type(0), _index(0)
  490. {
  491. }
  492. Uniform::~Uniform()
  493. {
  494. // hidden
  495. }
  496. Effect* Uniform::getEffect() const
  497. {
  498. return _effect;
  499. }
  500. const char* Uniform::getName() const
  501. {
  502. return _name.c_str();
  503. }
  504. const GLenum Uniform::getType() const
  505. {
  506. return _type;
  507. }
  508. }