Shader.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. /**
  2. * Copyright (c) 2006-2015 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. // LOVE
  21. #include "common/config.h"
  22. #include "Shader.h"
  23. #include "Canvas.h"
  24. // C++
  25. #include <algorithm>
  26. namespace love
  27. {
  28. namespace graphics
  29. {
  30. namespace opengl
  31. {
  32. namespace
  33. {
  34. // temporarily attaches a shader program (for setting uniforms, etc)
  35. // reattaches the originally active program when destroyed
  36. struct TemporaryAttacher
  37. {
  38. TemporaryAttacher(Shader *shader)
  39. : curShader(shader)
  40. , prevShader(Shader::current)
  41. {
  42. curShader->attach(true);
  43. }
  44. ~TemporaryAttacher()
  45. {
  46. if (prevShader != nullptr)
  47. prevShader->attach();
  48. else
  49. curShader->detach();
  50. }
  51. Shader *curShader;
  52. Shader *prevShader;
  53. };
  54. } // anonymous namespace
  55. Shader *Shader::current = nullptr;
  56. Shader *Shader::defaultShader = nullptr;
  57. Shader::ShaderSource Shader::defaultCode[Graphics::RENDERER_MAX_ENUM];
  58. GLint Shader::maxTexUnits = 0;
  59. std::vector<int> Shader::textureCounters;
  60. Shader::Shader(const ShaderSource &source)
  61. : shaderSource(source)
  62. , program(0)
  63. , builtinUniforms()
  64. , builtinAttributes()
  65. , lastCanvas((Canvas *) -1)
  66. , lastViewport()
  67. {
  68. if (source.vertex.empty() && source.pixel.empty())
  69. throw love::Exception("Cannot create shader: no source code!");
  70. if (maxTexUnits <= 0)
  71. {
  72. GLint maxtexunits;
  73. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxtexunits);
  74. maxTexUnits = std::max(maxtexunits - 1, 0);
  75. }
  76. // initialize global texture id counters if needed
  77. if (textureCounters.size() < (size_t) maxTexUnits)
  78. textureCounters.resize(maxTexUnits, 0);
  79. // load shader source and create program object
  80. loadVolatile();
  81. }
  82. Shader::~Shader()
  83. {
  84. if (current == this)
  85. detach();
  86. for (const auto &retainable : boundRetainables)
  87. retainable.second->release();
  88. boundRetainables.clear();
  89. unloadVolatile();
  90. }
  91. GLuint Shader::compileCode(ShaderStage stage, const std::string &code)
  92. {
  93. GLenum glstage;
  94. const char *typestr;
  95. if (!stageNames.find(stage, typestr))
  96. typestr = "";
  97. switch (stage)
  98. {
  99. case STAGE_VERTEX:
  100. glstage = GL_VERTEX_SHADER;
  101. break;
  102. case STAGE_PIXEL:
  103. glstage = GL_FRAGMENT_SHADER;
  104. break;
  105. default:
  106. throw love::Exception("Cannot create shader object: unknown shader type.");
  107. break;
  108. }
  109. GLuint shaderid = glCreateShader(glstage);
  110. if (shaderid == 0)
  111. {
  112. if (glGetError() == GL_INVALID_ENUM)
  113. throw love::Exception("Cannot create %s shader object: %s shaders not supported.", typestr, typestr);
  114. else
  115. throw love::Exception("Cannot create %s shader object.", typestr);
  116. }
  117. const char *src = code.c_str();
  118. GLint srclen = (GLint) code.length();
  119. glShaderSource(shaderid, 1, (const GLchar **)&src, &srclen);
  120. glCompileShader(shaderid);
  121. GLint infologlen;
  122. glGetShaderiv(shaderid, GL_INFO_LOG_LENGTH, &infologlen);
  123. // Get any warnings the shader compiler may have produced.
  124. if (infologlen > 0)
  125. {
  126. GLchar *infolog = new GLchar[infologlen];
  127. glGetShaderInfoLog(shaderid, infologlen, nullptr, infolog);
  128. // Save any warnings for later querying.
  129. shaderWarnings[stage] = infolog;
  130. delete[] infolog;
  131. }
  132. GLint status;
  133. glGetShaderiv(shaderid, GL_COMPILE_STATUS, &status);
  134. if (status == GL_FALSE)
  135. {
  136. glDeleteShader(shaderid);
  137. throw love::Exception("Cannot compile %s shader code:\n%s",
  138. typestr, shaderWarnings[stage].c_str());
  139. }
  140. return shaderid;
  141. }
  142. void Shader::mapActiveUniforms()
  143. {
  144. // Built-in uniform locations default to -1 (nonexistant.)
  145. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  146. builtinUniforms[i] = -1;
  147. uniforms.clear();
  148. GLint numuniforms;
  149. glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &numuniforms);
  150. GLchar cname[256];
  151. const GLint bufsize = (GLint) (sizeof(cname) / sizeof(GLchar));
  152. for (int i = 0; i < numuniforms; i++)
  153. {
  154. GLsizei namelen = 0;
  155. Uniform u = {};
  156. glGetActiveUniform(program, (GLuint) i, bufsize, &namelen, &u.count, &u.type, cname);
  157. u.name = std::string(cname, (size_t) namelen);
  158. u.location = glGetUniformLocation(program, u.name.c_str());
  159. u.baseType = getUniformBaseType(u.type);
  160. // glGetActiveUniform appends "[0]" to the end of array uniform names...
  161. if (u.name.length() > 3)
  162. {
  163. size_t findpos = u.name.find("[0]");
  164. if (findpos != std::string::npos && findpos == u.name.length() - 3)
  165. u.name.erase(u.name.length() - 3);
  166. }
  167. // If this is a built-in (LOVE-created) uniform, store the location.
  168. BuiltinUniform builtin;
  169. if (builtinNames.find(u.name.c_str(), builtin))
  170. builtinUniforms[int(builtin)] = u.location;
  171. if (u.location != -1)
  172. uniforms[u.name] = u;
  173. }
  174. }
  175. bool Shader::loadVolatile()
  176. {
  177. // Recreating the shader program will invalidate uniforms that rely on these.
  178. lastCanvas = (Canvas *) -1;
  179. lastViewport = OpenGL::Viewport();
  180. // zero out active texture list
  181. activeTexUnits.clear();
  182. activeTexUnits.insert(activeTexUnits.begin(), maxTexUnits, 0);
  183. std::vector<GLuint> shaderids;
  184. const ShaderSource *defaults = &defaultCode[Graphics::RENDERER_OPENGL];
  185. if (GLAD_ES_VERSION_2_0)
  186. defaults = &defaultCode[Graphics::RENDERER_OPENGLES];
  187. // The shader program must have both vertex and pixel shader stages.
  188. const std::string &vertexcode = shaderSource.vertex.empty() ? defaults->vertex : shaderSource.vertex;
  189. const std::string &pixelcode = shaderSource.pixel.empty() ? defaults->pixel : shaderSource.pixel;
  190. try
  191. {
  192. shaderids.push_back(compileCode(STAGE_VERTEX, vertexcode));
  193. shaderids.push_back(compileCode(STAGE_PIXEL, pixelcode));
  194. }
  195. catch (love::Exception &)
  196. {
  197. for (GLuint id : shaderids)
  198. glDeleteShader(id);
  199. throw;
  200. }
  201. program = glCreateProgram();
  202. if (program == 0)
  203. {
  204. for (GLuint id : shaderids)
  205. glDeleteShader(id);
  206. throw love::Exception("Cannot create shader program object.");
  207. }
  208. for (GLuint id : shaderids)
  209. glAttachShader(program, id);
  210. // Bind generic vertex attribute indices to names in the shader.
  211. for (int i = 0; i < int(ATTRIB_MAX_ENUM); i++)
  212. {
  213. VertexAttribID attrib = (VertexAttribID) i;
  214. // FIXME: We skip this both because pseudo-instancing is temporarily
  215. // disabled (see graphics.lua), and because binding a non-existant
  216. // attribute name to a location causes a shader linker warning.
  217. if (attrib == ATTRIB_PSEUDO_INSTANCE_ID)
  218. continue;
  219. const char *name = nullptr;
  220. if (attribNames.find(attrib, name))
  221. glBindAttribLocation(program, i, (const GLchar *) name);
  222. }
  223. glLinkProgram(program);
  224. // Flag shaders for auto-deletion when the program object is deleted.
  225. for (GLuint id : shaderids)
  226. glDeleteShader(id);
  227. GLint status;
  228. glGetProgramiv(program, GL_LINK_STATUS, &status);
  229. if (status == GL_FALSE)
  230. {
  231. std::string warnings = getProgramWarnings();
  232. glDeleteProgram(program);
  233. program = 0;
  234. throw love::Exception("Cannot link shader program object:\n%s", warnings.c_str());
  235. }
  236. // Retreive all active uniform variables in this shader from OpenGL.
  237. mapActiveUniforms();
  238. for (int i = 0; i < int(ATTRIB_MAX_ENUM); i++)
  239. {
  240. const char *name = nullptr;
  241. if (attribNames.find(VertexAttribID(i), name))
  242. builtinAttributes[i] = glGetAttribLocation(program, name);
  243. else
  244. builtinAttributes[i] = -1;
  245. }
  246. if (current == this)
  247. {
  248. // make sure glUseProgram gets called.
  249. current = nullptr;
  250. attach();
  251. checkSetScreenParams();
  252. }
  253. return true;
  254. }
  255. void Shader::unloadVolatile()
  256. {
  257. if (current == this)
  258. glUseProgram(0);
  259. if (program != 0)
  260. {
  261. glDeleteProgram(program);
  262. program = 0;
  263. }
  264. // decrement global texture id counters for texture units which had textures bound from this shader
  265. for (size_t i = 0; i < activeTexUnits.size(); ++i)
  266. {
  267. if (activeTexUnits[i] > 0)
  268. textureCounters[i] = std::max(textureCounters[i] - 1, 0);
  269. }
  270. // active texture list is probably invalid, clear it
  271. activeTexUnits.clear();
  272. activeTexUnits.resize(maxTexUnits, 0);
  273. // same with uniform location list
  274. uniforms.clear();
  275. // And the locations of any built-in uniform variables.
  276. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  277. builtinUniforms[i] = -1;
  278. shaderWarnings.clear();
  279. }
  280. std::string Shader::getProgramWarnings() const
  281. {
  282. GLint strsize, nullpos;
  283. glGetProgramiv(program, GL_INFO_LOG_LENGTH, &strsize);
  284. if (strsize == 0)
  285. return "";
  286. char *tempstr = new char[strsize];
  287. // be extra sure that the error string will be 0-terminated
  288. memset(tempstr, '\0', strsize);
  289. glGetProgramInfoLog(program, strsize, &nullpos, tempstr);
  290. tempstr[nullpos] = '\0';
  291. std::string warnings(tempstr);
  292. delete[] tempstr;
  293. return warnings;
  294. }
  295. std::string Shader::getWarnings() const
  296. {
  297. std::string warnings;
  298. const char *stagestr;
  299. // Get the individual shader stage warnings
  300. for (const auto &warning : shaderWarnings)
  301. {
  302. if (stageNames.find(warning.first, stagestr))
  303. warnings += std::string(stagestr) + std::string(" shader:\n") + warning.second;
  304. }
  305. warnings += getProgramWarnings();
  306. return warnings;
  307. }
  308. void Shader::attach(bool temporary)
  309. {
  310. if (current != this)
  311. {
  312. glUseProgram(program);
  313. current = this;
  314. // retain/release happens in Graphics::setShader.
  315. }
  316. if (!temporary)
  317. {
  318. // make sure all sent textures are properly bound to their respective texture units
  319. // note: list potentially contains texture ids of deleted/invalid textures!
  320. for (size_t i = 0; i < activeTexUnits.size(); ++i)
  321. {
  322. if (activeTexUnits[i] > 0)
  323. gl.bindTextureToUnit(activeTexUnits[i], (int) i + 1, false);
  324. }
  325. // We always want to use texture unit 0 for everyhing else.
  326. gl.setTextureUnit(0);
  327. }
  328. }
  329. void Shader::detach()
  330. {
  331. if (defaultShader)
  332. {
  333. if (current != defaultShader)
  334. defaultShader->attach();
  335. return;
  336. }
  337. if (current != nullptr)
  338. glUseProgram(0);
  339. current = nullptr;
  340. }
  341. const Shader::Uniform &Shader::getUniform(const std::string &name) const
  342. {
  343. std::map<std::string, Uniform>::const_iterator it = uniforms.find(name);
  344. if (it == uniforms.end())
  345. throw love::Exception("Variable '%s' does not exist.\n"
  346. "A common error is to define but not use the variable.", name.c_str());
  347. return it->second;
  348. }
  349. void Shader::checkSetUniformError(const Uniform &u, int size, int count, UniformType sendtype) const
  350. {
  351. if (!program)
  352. throw love::Exception("No active shader program.");
  353. int realsize = getUniformTypeSize(u.type);
  354. if (size != realsize)
  355. throw love::Exception("Value size of %d does not match variable size of %d.", size, realsize);
  356. if ((u.count == 1 && count > 1) || count < 0)
  357. throw love::Exception("Invalid number of values (expected %d, got %d).", u.count, count);
  358. if (u.baseType == UNIFORM_SAMPLER && sendtype != u.baseType)
  359. throw love::Exception("Cannot send a value of this type to an Image variable.");
  360. if ((sendtype == UNIFORM_FLOAT && u.baseType == UNIFORM_INT) || (sendtype == UNIFORM_INT && u.baseType == UNIFORM_FLOAT))
  361. throw love::Exception("Cannot convert between float and int.");
  362. }
  363. void Shader::sendInt(const std::string &name, int size, const GLint *vec, int count)
  364. {
  365. TemporaryAttacher attacher(this);
  366. const Uniform &u = getUniform(name);
  367. checkSetUniformError(u, size, count, UNIFORM_INT);
  368. switch (size)
  369. {
  370. case 4:
  371. glUniform4iv(u.location, count, vec);
  372. break;
  373. case 3:
  374. glUniform3iv(u.location, count, vec);
  375. break;
  376. case 2:
  377. glUniform2iv(u.location, count, vec);
  378. break;
  379. case 1:
  380. default:
  381. glUniform1iv(u.location, count, vec);
  382. break;
  383. }
  384. }
  385. void Shader::sendFloat(const std::string &name, int size, const GLfloat *vec, int count)
  386. {
  387. TemporaryAttacher attacher(this);
  388. const Uniform &u = getUniform(name);
  389. checkSetUniformError(u, size, count, UNIFORM_FLOAT);
  390. switch (size)
  391. {
  392. case 4:
  393. glUniform4fv(u.location, count, vec);
  394. break;
  395. case 3:
  396. glUniform3fv(u.location, count, vec);
  397. break;
  398. case 2:
  399. glUniform2fv(u.location, count, vec);
  400. break;
  401. case 1:
  402. default:
  403. glUniform1fv(u.location, count, vec);
  404. break;
  405. }
  406. }
  407. void Shader::sendMatrix(const std::string &name, int size, const GLfloat *m, int count)
  408. {
  409. TemporaryAttacher attacher(this);
  410. if (size < 2 || size > 4)
  411. {
  412. throw love::Exception("Invalid matrix size: %dx%d "
  413. "(can only set 2x2, 3x3 or 4x4 matrices.)", size,size);
  414. }
  415. const Uniform &u = getUniform(name);
  416. checkSetUniformError(u, size, count, UNIFORM_FLOAT);
  417. switch (size)
  418. {
  419. case 4:
  420. glUniformMatrix4fv(u.location, count, GL_FALSE, m);
  421. break;
  422. case 3:
  423. glUniformMatrix3fv(u.location, count, GL_FALSE, m);
  424. break;
  425. case 2:
  426. default:
  427. glUniformMatrix2fv(u.location, count, GL_FALSE, m);
  428. break;
  429. }
  430. }
  431. void Shader::sendTexture(const std::string &name, Texture *texture)
  432. {
  433. GLuint gltex = texture->getGLTexture();
  434. TemporaryAttacher attacher(this);
  435. int texunit = getTextureUnit(name);
  436. const Uniform &u = getUniform(name);
  437. checkSetUniformError(u, 1, 1, UNIFORM_SAMPLER);
  438. // bind texture to assigned texture unit and send uniform to shader program
  439. gl.bindTextureToUnit(gltex, texunit, false);
  440. glUniform1i(u.location, texunit);
  441. // reset texture unit
  442. gl.setTextureUnit(0);
  443. // increment global shader texture id counter for this texture unit, if we haven't already
  444. if (activeTexUnits[texunit-1] == 0)
  445. ++textureCounters[texunit-1];
  446. // store texture id so it can be re-bound to the proper texture unit later
  447. activeTexUnits[texunit-1] = gltex;
  448. retainObject(name, texture);
  449. }
  450. void Shader::retainObject(const std::string &name, Object *object)
  451. {
  452. object->retain();
  453. auto it = boundRetainables.find(name);
  454. if (it != boundRetainables.end())
  455. it->second->release();
  456. boundRetainables[name] = object;
  457. }
  458. int Shader::getTextureUnit(const std::string &name)
  459. {
  460. auto it = texUnitPool.find(name);
  461. if (it != texUnitPool.end())
  462. return it->second;
  463. int texunit = 1;
  464. // prefer texture units which are unused by all other shaders
  465. auto freeunit_it = std::find(textureCounters.begin(), textureCounters.end(), 0);
  466. if (freeunit_it != textureCounters.end())
  467. {
  468. // we don't want to use unit 0
  469. texunit = (int) std::distance(textureCounters.begin(), freeunit_it) + 1;
  470. }
  471. else
  472. {
  473. // no completely unused texture units exist, try to use next free slot in our own list
  474. auto nextunit_it = std::find(activeTexUnits.begin(), activeTexUnits.end(), 0);
  475. if (nextunit_it == activeTexUnits.end())
  476. throw love::Exception("No more texture units available for shader.");
  477. // we don't want to use unit 0
  478. texunit = (int) std::distance(activeTexUnits.begin(), nextunit_it) + 1;
  479. }
  480. texUnitPool[name] = texunit;
  481. return texunit;
  482. }
  483. Shader::UniformType Shader::getExternVariable(const std::string &name, int &components, int &count)
  484. {
  485. auto it = uniforms.find(name);
  486. if (it == uniforms.end())
  487. {
  488. components = 0;
  489. count = 0;
  490. return UNIFORM_UNKNOWN;
  491. }
  492. components = getUniformTypeSize(it->second.type);
  493. count = (int) it->second.count;
  494. return it->second.baseType;
  495. }
  496. bool Shader::hasVertexAttrib(VertexAttribID attrib) const
  497. {
  498. return builtinAttributes[int(attrib)] != -1;
  499. }
  500. bool Shader::hasBuiltinUniform(BuiltinUniform builtin) const
  501. {
  502. return builtinUniforms[int(builtin)] != -1;
  503. }
  504. bool Shader::sendBuiltinMatrix(BuiltinUniform builtin, int size, const GLfloat *m, int count)
  505. {
  506. if (!hasBuiltinUniform(builtin))
  507. return false;
  508. GLint location = builtinUniforms[GLint(builtin)];
  509. TemporaryAttacher attacher(this);
  510. switch (size)
  511. {
  512. case 2:
  513. glUniformMatrix2fv(location, count, GL_FALSE, m);
  514. break;
  515. case 3:
  516. glUniformMatrix3fv(location, count, GL_FALSE, m);
  517. break;
  518. case 4:
  519. glUniformMatrix4fv(location, count, GL_FALSE, m);
  520. break;
  521. default:
  522. return false;
  523. }
  524. return true;
  525. }
  526. bool Shader::sendBuiltinFloat(BuiltinUniform builtin, int size, const GLfloat *vec, int count)
  527. {
  528. if (!hasBuiltinUniform(builtin))
  529. return false;
  530. GLint location = builtinUniforms[int(builtin)];
  531. TemporaryAttacher attacher(this);
  532. switch (size)
  533. {
  534. case 1:
  535. glUniform1fv(location, count, vec);
  536. break;
  537. case 2:
  538. glUniform2fv(location, count, vec);
  539. break;
  540. case 3:
  541. glUniform3fv(location, count, vec);
  542. break;
  543. case 4:
  544. glUniform4fv(location, count, vec);
  545. break;
  546. default:
  547. return false;
  548. }
  549. return true;
  550. }
  551. void Shader::checkSetScreenParams()
  552. {
  553. OpenGL::Viewport view = gl.getViewport();
  554. if (view == lastViewport && lastCanvas == Canvas::current)
  555. return;
  556. // In the shader, we do pixcoord.y = gl_FragCoord.y * params.z + params.w.
  557. // This lets us flip pixcoord.y when needed, to be consistent (drawing with
  558. // no Canvas active makes the y-values for pixel coordinates flipped.)
  559. GLfloat params[] = {
  560. (GLfloat) view.w, (GLfloat) view.h,
  561. 0.0f, 0.0f,
  562. };
  563. if (Canvas::current != nullptr)
  564. {
  565. // No flipping: pixcoord.y = gl_FragCoord.y * 1.0 + 0.0.
  566. params[2] = 1.0f;
  567. params[3] = 0.0f;
  568. }
  569. else
  570. {
  571. // gl_FragCoord.y is flipped when drawing to the screen, so we un-flip:
  572. // pixcoord.y = gl_FragCoord.y * -1.0 + height.
  573. params[2] = -1.0f;
  574. params[3] = (GLfloat) view.h;
  575. }
  576. sendBuiltinFloat(BUILTIN_SCREEN_SIZE, 4, params, 1);
  577. lastCanvas = Canvas::current;
  578. lastViewport = view;
  579. }
  580. const std::map<std::string, Object *> &Shader::getBoundRetainables() const
  581. {
  582. return boundRetainables;
  583. }
  584. std::string Shader::getGLSLVersion()
  585. {
  586. const char *tmp = (const char *) glGetString(GL_SHADING_LANGUAGE_VERSION);
  587. if (tmp == nullptr)
  588. return "0.0";
  589. // the version string always begins with a version number of the format
  590. // major_number.minor_number
  591. // or
  592. // major_number.minor_number.release_number
  593. // we can keep release_number, since it does not affect the check below.
  594. std::string versionstring(tmp);
  595. size_t minorendpos = versionstring.find(' ');
  596. return versionstring.substr(0, minorendpos);
  597. }
  598. bool Shader::isSupported()
  599. {
  600. return GLAD_ES_VERSION_2_0 || (getGLSLVersion() >= "1.2");
  601. }
  602. int Shader::getUniformTypeSize(GLenum type) const
  603. {
  604. switch (type)
  605. {
  606. case GL_INT:
  607. case GL_FLOAT:
  608. case GL_BOOL:
  609. case GL_SAMPLER_1D:
  610. case GL_SAMPLER_2D:
  611. case GL_SAMPLER_3D:
  612. return 1;
  613. case GL_INT_VEC2:
  614. case GL_FLOAT_VEC2:
  615. case GL_FLOAT_MAT2:
  616. case GL_BOOL_VEC2:
  617. return 2;
  618. case GL_INT_VEC3:
  619. case GL_FLOAT_VEC3:
  620. case GL_FLOAT_MAT3:
  621. case GL_BOOL_VEC3:
  622. return 3;
  623. case GL_INT_VEC4:
  624. case GL_FLOAT_VEC4:
  625. case GL_FLOAT_MAT4:
  626. case GL_BOOL_VEC4:
  627. return 4;
  628. default:
  629. return 1;
  630. }
  631. }
  632. Shader::UniformType Shader::getUniformBaseType(GLenum type) const
  633. {
  634. switch (type)
  635. {
  636. case GL_INT:
  637. case GL_INT_VEC2:
  638. case GL_INT_VEC3:
  639. case GL_INT_VEC4:
  640. return UNIFORM_INT;
  641. case GL_FLOAT:
  642. case GL_FLOAT_VEC2:
  643. case GL_FLOAT_VEC3:
  644. case GL_FLOAT_VEC4:
  645. case GL_FLOAT_MAT2:
  646. case GL_FLOAT_MAT3:
  647. case GL_FLOAT_MAT4:
  648. return UNIFORM_FLOAT;
  649. case GL_BOOL:
  650. case GL_BOOL_VEC2:
  651. case GL_BOOL_VEC3:
  652. case GL_BOOL_VEC4:
  653. return UNIFORM_BOOL;
  654. case GL_SAMPLER_1D:
  655. case GL_SAMPLER_2D:
  656. case GL_SAMPLER_3D:
  657. return UNIFORM_SAMPLER;
  658. default:
  659. return UNIFORM_UNKNOWN;
  660. }
  661. }
  662. bool Shader::getConstant(const char *in, UniformType &out)
  663. {
  664. return uniformTypes.find(in, out);
  665. }
  666. bool Shader::getConstant(UniformType in, const char *&out)
  667. {
  668. return uniformTypes.find(in, out);
  669. }
  670. StringMap<Shader::ShaderStage, Shader::STAGE_MAX_ENUM>::Entry Shader::stageNameEntries[] =
  671. {
  672. {"vertex", Shader::STAGE_VERTEX},
  673. {"pixel", Shader::STAGE_PIXEL},
  674. };
  675. StringMap<Shader::ShaderStage, Shader::STAGE_MAX_ENUM> Shader::stageNames(Shader::stageNameEntries, sizeof(Shader::stageNameEntries));
  676. StringMap<Shader::UniformType, Shader::UNIFORM_MAX_ENUM>::Entry Shader::uniformTypeEntries[] =
  677. {
  678. {"float", Shader::UNIFORM_FLOAT},
  679. {"int", Shader::UNIFORM_INT},
  680. {"bool", Shader::UNIFORM_BOOL},
  681. {"image", Shader::UNIFORM_SAMPLER},
  682. {"unknown", Shader::UNIFORM_UNKNOWN},
  683. };
  684. StringMap<Shader::UniformType, Shader::UNIFORM_MAX_ENUM> Shader::uniformTypes(Shader::uniformTypeEntries, sizeof(Shader::uniformTypeEntries));
  685. StringMap<VertexAttribID, ATTRIB_MAX_ENUM>::Entry Shader::attribNameEntries[] =
  686. {
  687. {"VertexPosition", ATTRIB_POS},
  688. {"VertexTexCoord", ATTRIB_TEXCOORD},
  689. {"VertexColor", ATTRIB_COLOR},
  690. {"love_PseudoInstanceID", ATTRIB_PSEUDO_INSTANCE_ID},
  691. };
  692. StringMap<VertexAttribID, ATTRIB_MAX_ENUM> Shader::attribNames(Shader::attribNameEntries, sizeof(Shader::attribNameEntries));
  693. StringMap<Shader::BuiltinUniform, Shader::BUILTIN_MAX_ENUM>::Entry Shader::builtinNameEntries[] =
  694. {
  695. {"TransformMatrix", Shader::BUILTIN_TRANSFORM_MATRIX},
  696. {"ProjectionMatrix", Shader::BUILTIN_PROJECTION_MATRIX},
  697. {"TransformProjectionMatrix", Shader::BUILTIN_TRANSFORM_PROJECTION_MATRIX},
  698. {"love_PointSize", Shader::BUILTIN_POINT_SIZE},
  699. {"love_ScreenSize", Shader::BUILTIN_SCREEN_SIZE},
  700. };
  701. StringMap<Shader::BuiltinUniform, Shader::BUILTIN_MAX_ENUM> Shader::builtinNames(Shader::builtinNameEntries, sizeof(Shader::builtinNameEntries));
  702. } // opengl
  703. } // graphics
  704. } // love