Shader.cpp 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. /**
  2. * Copyright (c) 2006-2016 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. #include <limits>
  27. namespace love
  28. {
  29. namespace graphics
  30. {
  31. namespace opengl
  32. {
  33. namespace
  34. {
  35. // temporarily attaches a shader program (for setting uniforms, etc)
  36. // reattaches the originally active program when destroyed
  37. struct TemporaryAttacher
  38. {
  39. TemporaryAttacher(Shader *shader)
  40. : curShader(shader)
  41. , prevShader(Shader::current)
  42. {
  43. curShader->attach(true);
  44. }
  45. ~TemporaryAttacher()
  46. {
  47. if (prevShader != nullptr)
  48. prevShader->attach();
  49. else
  50. curShader->detach();
  51. }
  52. Shader *curShader;
  53. Shader *prevShader;
  54. };
  55. } // anonymous namespace
  56. Shader *Shader::current = nullptr;
  57. Shader *Shader::defaultShader = nullptr;
  58. Shader *Shader::defaultVideoShader = nullptr;
  59. Shader::ShaderSource Shader::defaultCode[Graphics::RENDERER_MAX_ENUM][2];
  60. Shader::ShaderSource Shader::defaultVideoCode[Graphics::RENDERER_MAX_ENUM][2];
  61. std::vector<int> Shader::textureCounters;
  62. Shader::Shader(const ShaderSource &source)
  63. : shaderSource(source)
  64. , program(0)
  65. , builtinUniforms()
  66. , builtinAttributes()
  67. , lastCanvas((Canvas *) -1)
  68. , lastViewport()
  69. , lastPointSize(0.0f)
  70. , videoTextureUnits()
  71. {
  72. if (source.vertex.empty() && source.pixel.empty())
  73. throw love::Exception("Cannot create shader: no source code!");
  74. // initialize global texture id counters if needed
  75. if ((int) textureCounters.size() < gl.getMaxTextureUnits() - 1)
  76. textureCounters.resize(gl.getMaxTextureUnits() - 1, 0);
  77. // load shader source and create program object
  78. loadVolatile();
  79. }
  80. Shader::~Shader()
  81. {
  82. if (current == this)
  83. detach();
  84. for (const auto &retainable : boundRetainables)
  85. retainable.second->release();
  86. boundRetainables.clear();
  87. unloadVolatile();
  88. }
  89. GLuint Shader::compileCode(ShaderStage stage, const std::string &code)
  90. {
  91. GLenum glstage;
  92. const char *typestr;
  93. if (!stageNames.find(stage, typestr))
  94. typestr = "";
  95. switch (stage)
  96. {
  97. case STAGE_VERTEX:
  98. glstage = GL_VERTEX_SHADER;
  99. break;
  100. case STAGE_PIXEL:
  101. glstage = GL_FRAGMENT_SHADER;
  102. break;
  103. default:
  104. throw love::Exception("Cannot create shader object: unknown shader type.");
  105. break;
  106. }
  107. GLuint shaderid = glCreateShader(glstage);
  108. if (shaderid == 0)
  109. {
  110. if (glGetError() == GL_INVALID_ENUM)
  111. throw love::Exception("Cannot create %s shader object: %s shaders not supported.", typestr, typestr);
  112. else
  113. throw love::Exception("Cannot create %s shader object.", typestr);
  114. }
  115. const char *src = code.c_str();
  116. GLint srclen = (GLint) code.length();
  117. glShaderSource(shaderid, 1, (const GLchar **)&src, &srclen);
  118. glCompileShader(shaderid);
  119. GLint infologlen;
  120. glGetShaderiv(shaderid, GL_INFO_LOG_LENGTH, &infologlen);
  121. // Get any warnings the shader compiler may have produced.
  122. if (infologlen > 0)
  123. {
  124. GLchar *infolog = new GLchar[infologlen];
  125. glGetShaderInfoLog(shaderid, infologlen, nullptr, infolog);
  126. // Save any warnings for later querying.
  127. shaderWarnings[stage] = infolog;
  128. delete[] infolog;
  129. }
  130. GLint status;
  131. glGetShaderiv(shaderid, GL_COMPILE_STATUS, &status);
  132. if (status == GL_FALSE)
  133. {
  134. glDeleteShader(shaderid);
  135. throw love::Exception("Cannot compile %s shader code:\n%s",
  136. typestr, shaderWarnings[stage].c_str());
  137. }
  138. return shaderid;
  139. }
  140. void Shader::mapActiveUniforms()
  141. {
  142. // Built-in uniform locations default to -1 (nonexistant.)
  143. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  144. builtinUniforms[i] = -1;
  145. uniforms.clear();
  146. GLint activeprogram = 0;
  147. glGetIntegerv(GL_CURRENT_PROGRAM, &activeprogram);
  148. glUseProgram(program);
  149. GLint numuniforms;
  150. glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &numuniforms);
  151. GLchar cname[256];
  152. const GLint bufsize = (GLint) (sizeof(cname) / sizeof(GLchar));
  153. for (int i = 0; i < numuniforms; i++)
  154. {
  155. GLsizei namelen = 0;
  156. Uniform u = {};
  157. glGetActiveUniform(program, (GLuint) i, bufsize, &namelen, &u.count, &u.type, cname);
  158. u.name = std::string(cname, (size_t) namelen);
  159. u.location = glGetUniformLocation(program, u.name.c_str());
  160. u.baseType = getUniformBaseType(u.type);
  161. // Initialize all samplers to 0. Both GLSL and GLSL ES are supposed to
  162. // do this themselves, but some Android devices (galaxy tab 3 and 4)
  163. // don't seem to do it...
  164. if (u.baseType == UNIFORM_SAMPLER)
  165. glUniform1i(u.location, 0);
  166. // glGetActiveUniform appends "[0]" to the end of array uniform names...
  167. if (u.name.length() > 3)
  168. {
  169. size_t findpos = u.name.find("[0]");
  170. if (findpos != std::string::npos && findpos == u.name.length() - 3)
  171. u.name.erase(u.name.length() - 3);
  172. }
  173. // If this is a built-in (LOVE-created) uniform, store the location.
  174. BuiltinUniform builtin;
  175. if (builtinNames.find(u.name.c_str(), builtin))
  176. builtinUniforms[int(builtin)] = u.location;
  177. if (u.location != -1)
  178. uniforms[u.name] = u;
  179. }
  180. glUseProgram(activeprogram);
  181. }
  182. bool Shader::loadVolatile()
  183. {
  184. OpenGL::TempDebugGroup debuggroup("Shader load");
  185. // Recreating the shader program will invalidate uniforms that rely on these.
  186. lastCanvas = (Canvas *) -1;
  187. lastViewport = OpenGL::Viewport();
  188. lastPointSize = -1.0f;
  189. // Invalidate the cached matrices by setting some elements to NaN.
  190. float nan = std::numeric_limits<float>::quiet_NaN();
  191. lastProjectionMatrix.setTranslation(nan, nan);
  192. lastTransformMatrix.setTranslation(nan, nan);
  193. for (int i = 0; i < 3; i++)
  194. videoTextureUnits[i] = 0;
  195. // zero out active texture list
  196. activeTexUnits.clear();
  197. activeTexUnits.insert(activeTexUnits.begin(), gl.getMaxTextureUnits() - 1, 0);
  198. std::vector<GLuint> shaderids;
  199. bool gammacorrect = graphics::isGammaCorrect();
  200. const ShaderSource *defaults = &defaultCode[Graphics::RENDERER_OPENGL][gammacorrect ? 1 : 0];
  201. if (GLAD_ES_VERSION_2_0)
  202. defaults = &defaultCode[Graphics::RENDERER_OPENGLES][gammacorrect ? 1 : 0];
  203. // The shader program must have both vertex and pixel shader stages.
  204. const std::string &vertexcode = shaderSource.vertex.empty() ? defaults->vertex : shaderSource.vertex;
  205. const std::string &pixelcode = shaderSource.pixel.empty() ? defaults->pixel : shaderSource.pixel;
  206. try
  207. {
  208. shaderids.push_back(compileCode(STAGE_VERTEX, vertexcode));
  209. shaderids.push_back(compileCode(STAGE_PIXEL, pixelcode));
  210. }
  211. catch (love::Exception &)
  212. {
  213. for (GLuint id : shaderids)
  214. glDeleteShader(id);
  215. throw;
  216. }
  217. program = glCreateProgram();
  218. if (program == 0)
  219. {
  220. for (GLuint id : shaderids)
  221. glDeleteShader(id);
  222. throw love::Exception("Cannot create shader program object.");
  223. }
  224. for (GLuint id : shaderids)
  225. glAttachShader(program, id);
  226. // Bind generic vertex attribute indices to names in the shader.
  227. for (int i = 0; i < int(ATTRIB_MAX_ENUM); i++)
  228. {
  229. const char *name = nullptr;
  230. if (attribNames.find((VertexAttribID) i, name))
  231. glBindAttribLocation(program, i, (const GLchar *) name);
  232. }
  233. glLinkProgram(program);
  234. // Flag shaders for auto-deletion when the program object is deleted.
  235. for (GLuint id : shaderids)
  236. glDeleteShader(id);
  237. GLint status;
  238. glGetProgramiv(program, GL_LINK_STATUS, &status);
  239. if (status == GL_FALSE)
  240. {
  241. std::string warnings = getProgramWarnings();
  242. glDeleteProgram(program);
  243. program = 0;
  244. throw love::Exception("Cannot link shader program object:\n%s", warnings.c_str());
  245. }
  246. // Get all active uniform variables in this shader from OpenGL.
  247. mapActiveUniforms();
  248. for (int i = 0; i < int(ATTRIB_MAX_ENUM); i++)
  249. {
  250. const char *name = nullptr;
  251. if (attribNames.find(VertexAttribID(i), name))
  252. builtinAttributes[i] = glGetAttribLocation(program, name);
  253. else
  254. builtinAttributes[i] = -1;
  255. }
  256. if (current == this)
  257. {
  258. // make sure glUseProgram gets called.
  259. current = nullptr;
  260. attach();
  261. checkSetBuiltinUniforms();
  262. }
  263. return true;
  264. }
  265. void Shader::unloadVolatile()
  266. {
  267. if (current == this)
  268. glUseProgram(0);
  269. if (program != 0)
  270. {
  271. glDeleteProgram(program);
  272. program = 0;
  273. }
  274. // decrement global texture id counters for texture units which had textures bound from this shader
  275. for (size_t i = 0; i < activeTexUnits.size(); ++i)
  276. {
  277. if (activeTexUnits[i] > 0)
  278. textureCounters[i] = std::max(textureCounters[i] - 1, 0);
  279. }
  280. // active texture list is probably invalid, clear it
  281. activeTexUnits.clear();
  282. activeTexUnits.resize(gl.getMaxTextureUnits() - 1, 0);
  283. attributes.clear();
  284. // same with uniform location list
  285. uniforms.clear();
  286. // And the locations of any built-in uniform variables.
  287. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  288. builtinUniforms[i] = -1;
  289. shaderWarnings.clear();
  290. }
  291. std::string Shader::getProgramWarnings() const
  292. {
  293. GLint strsize, nullpos;
  294. glGetProgramiv(program, GL_INFO_LOG_LENGTH, &strsize);
  295. if (strsize == 0)
  296. return "";
  297. char *tempstr = new char[strsize];
  298. // be extra sure that the error string will be 0-terminated
  299. memset(tempstr, '\0', strsize);
  300. glGetProgramInfoLog(program, strsize, &nullpos, tempstr);
  301. tempstr[nullpos] = '\0';
  302. std::string warnings(tempstr);
  303. delete[] tempstr;
  304. return warnings;
  305. }
  306. std::string Shader::getWarnings() const
  307. {
  308. std::string warnings;
  309. const char *stagestr;
  310. // Get the individual shader stage warnings
  311. for (const auto &warning : shaderWarnings)
  312. {
  313. if (stageNames.find(warning.first, stagestr))
  314. warnings += std::string(stagestr) + std::string(" shader:\n") + warning.second;
  315. }
  316. warnings += getProgramWarnings();
  317. return warnings;
  318. }
  319. void Shader::attach(bool temporary)
  320. {
  321. if (current != this)
  322. {
  323. glUseProgram(program);
  324. current = this;
  325. // retain/release happens in Graphics::setShader.
  326. }
  327. if (!temporary)
  328. {
  329. // make sure all sent textures are properly bound to their respective texture units
  330. // note: list potentially contains texture ids of deleted/invalid textures!
  331. for (size_t i = 0; i < activeTexUnits.size(); ++i)
  332. {
  333. if (activeTexUnits[i] > 0)
  334. gl.bindTextureToUnit(activeTexUnits[i], i + 1, false);
  335. }
  336. // We always want to use texture unit 0 for everyhing else.
  337. gl.setTextureUnit(0);
  338. }
  339. }
  340. void Shader::detach()
  341. {
  342. if (defaultShader)
  343. {
  344. if (current != defaultShader)
  345. defaultShader->attach();
  346. return;
  347. }
  348. if (current != nullptr)
  349. glUseProgram(0);
  350. current = nullptr;
  351. }
  352. const Shader::Uniform &Shader::getUniform(const std::string &name) const
  353. {
  354. std::map<std::string, Uniform>::const_iterator it = uniforms.find(name);
  355. if (it == uniforms.end())
  356. throw love::Exception("Variable '%s' does not exist.\n"
  357. "A common error is to define but not use the variable.", name.c_str());
  358. return it->second;
  359. }
  360. void Shader::checkSetUniformError(const Uniform &u, int size, int count, UniformType sendtype) const
  361. {
  362. if (!program)
  363. throw love::Exception("No active shader program.");
  364. int realsize = getUniformTypeSize(u.type);
  365. if (size != realsize)
  366. throw love::Exception("Value size of %d does not match variable size of %d.", size, realsize);
  367. if ((u.count == 1 && count > 1) || count < 0)
  368. throw love::Exception("Invalid number of values (expected %d, got %d).", u.count, count);
  369. if (u.baseType == UNIFORM_SAMPLER && sendtype != u.baseType)
  370. throw love::Exception("Cannot send a value of this type to an Image variable.");
  371. if ((sendtype == UNIFORM_FLOAT && u.baseType == UNIFORM_INT) || (sendtype == UNIFORM_INT && u.baseType == UNIFORM_FLOAT))
  372. throw love::Exception("Cannot convert between float and int.");
  373. }
  374. void Shader::sendInt(const std::string &name, int size, const GLint *vec, int count)
  375. {
  376. TemporaryAttacher attacher(this);
  377. const Uniform &u = getUniform(name);
  378. checkSetUniformError(u, size, count, UNIFORM_INT);
  379. switch (size)
  380. {
  381. case 4:
  382. glUniform4iv(u.location, count, vec);
  383. break;
  384. case 3:
  385. glUniform3iv(u.location, count, vec);
  386. break;
  387. case 2:
  388. glUniform2iv(u.location, count, vec);
  389. break;
  390. case 1:
  391. default:
  392. glUniform1iv(u.location, count, vec);
  393. break;
  394. }
  395. }
  396. void Shader::sendFloat(const std::string &name, int size, const GLfloat *vec, int count)
  397. {
  398. TemporaryAttacher attacher(this);
  399. const Uniform &u = getUniform(name);
  400. checkSetUniformError(u, size, count, UNIFORM_FLOAT);
  401. switch (size)
  402. {
  403. case 4:
  404. glUniform4fv(u.location, count, vec);
  405. break;
  406. case 3:
  407. glUniform3fv(u.location, count, vec);
  408. break;
  409. case 2:
  410. glUniform2fv(u.location, count, vec);
  411. break;
  412. case 1:
  413. default:
  414. glUniform1fv(u.location, count, vec);
  415. break;
  416. }
  417. }
  418. void Shader::sendMatrix(const std::string &name, int size, const GLfloat *m, int count)
  419. {
  420. TemporaryAttacher attacher(this);
  421. if (size < 2 || size > 4)
  422. {
  423. throw love::Exception("Invalid matrix size: %dx%d "
  424. "(can only set 2x2, 3x3 or 4x4 matrices.)", size,size);
  425. }
  426. const Uniform &u = getUniform(name);
  427. checkSetUniformError(u, size, count, UNIFORM_FLOAT);
  428. switch (size)
  429. {
  430. case 4:
  431. glUniformMatrix4fv(u.location, count, GL_FALSE, m);
  432. break;
  433. case 3:
  434. glUniformMatrix3fv(u.location, count, GL_FALSE, m);
  435. break;
  436. case 2:
  437. default:
  438. glUniformMatrix2fv(u.location, count, GL_FALSE, m);
  439. break;
  440. }
  441. }
  442. void Shader::sendTexture(const std::string &name, Texture *texture)
  443. {
  444. GLuint gltex = *(GLuint *) texture->getHandle();
  445. TemporaryAttacher attacher(this);
  446. int texunit = getTextureUnit(name);
  447. const Uniform &u = getUniform(name);
  448. checkSetUniformError(u, 1, 1, UNIFORM_SAMPLER);
  449. // bind texture to assigned texture unit and send uniform to shader program
  450. gl.bindTextureToUnit(gltex, texunit, true);
  451. glUniform1i(u.location, texunit);
  452. // increment global shader texture id counter for this texture unit, if we haven't already
  453. if (activeTexUnits[texunit-1] == 0)
  454. ++textureCounters[texunit-1];
  455. // store texture id so it can be re-bound to the proper texture unit later
  456. activeTexUnits[texunit-1] = gltex;
  457. retainObject(name, texture);
  458. }
  459. void Shader::retainObject(const std::string &name, Object *object)
  460. {
  461. object->retain();
  462. auto it = boundRetainables.find(name);
  463. if (it != boundRetainables.end())
  464. it->second->release();
  465. boundRetainables[name] = object;
  466. }
  467. int Shader::getTextureUnit(const std::string &name)
  468. {
  469. auto it = texUnitPool.find(name);
  470. if (it != texUnitPool.end())
  471. return it->second;
  472. int texunit = 1;
  473. // prefer texture units which are unused by all other shaders
  474. auto freeunit_it = std::find(textureCounters.begin(), textureCounters.end(), 0);
  475. if (freeunit_it != textureCounters.end())
  476. {
  477. // we don't want to use unit 0
  478. texunit = (int) std::distance(textureCounters.begin(), freeunit_it) + 1;
  479. }
  480. else
  481. {
  482. // no completely unused texture units exist, try to use next free slot in our own list
  483. auto nextunit_it = std::find(activeTexUnits.begin(), activeTexUnits.end(), 0);
  484. if (nextunit_it == activeTexUnits.end())
  485. throw love::Exception("No more texture units available for shader.");
  486. // we don't want to use unit 0
  487. texunit = (int) std::distance(activeTexUnits.begin(), nextunit_it) + 1;
  488. }
  489. texUnitPool[name] = texunit;
  490. return texunit;
  491. }
  492. Shader::UniformType Shader::getExternVariable(const std::string &name, int &components, int &count)
  493. {
  494. auto it = uniforms.find(name);
  495. if (it == uniforms.end())
  496. {
  497. components = 0;
  498. count = 0;
  499. return UNIFORM_UNKNOWN;
  500. }
  501. components = getUniformTypeSize(it->second.type);
  502. count = (int) it->second.count;
  503. return it->second.baseType;
  504. }
  505. GLint Shader::getAttribLocation(const std::string &name)
  506. {
  507. auto it = attributes.find(name);
  508. if (it != attributes.end())
  509. return it->second;
  510. GLint location = glGetAttribLocation(program, name.c_str());
  511. attributes[name] = location;
  512. return location;
  513. }
  514. bool Shader::hasVertexAttrib(VertexAttribID attrib) const
  515. {
  516. return builtinAttributes[int(attrib)] != -1;
  517. }
  518. void Shader::setVideoTextures(GLuint ytexture, GLuint cbtexture, GLuint crtexture)
  519. {
  520. TemporaryAttacher attacher(this);
  521. // Set up the texture units that will be used by the shader to sample from
  522. // the textures, if they haven't been set up yet.
  523. if (videoTextureUnits[0] == 0)
  524. {
  525. const GLint locs[3] = {
  526. builtinUniforms[BUILTIN_VIDEO_Y_CHANNEL],
  527. builtinUniforms[BUILTIN_VIDEO_CB_CHANNEL],
  528. builtinUniforms[BUILTIN_VIDEO_CR_CHANNEL]
  529. };
  530. const char *names[3] = {nullptr, nullptr, nullptr};
  531. builtinNames.find(BUILTIN_VIDEO_Y_CHANNEL, names[0]);
  532. builtinNames.find(BUILTIN_VIDEO_CB_CHANNEL, names[1]);
  533. builtinNames.find(BUILTIN_VIDEO_CR_CHANNEL, names[2]);
  534. for (int i = 0; i < 3; i++)
  535. {
  536. if (locs[i] >= 0 && names[i] != nullptr)
  537. {
  538. videoTextureUnits[i] = getTextureUnit(names[i]);
  539. // Increment global shader texture id counter for this texture
  540. // unit, if we haven't already.
  541. if (activeTexUnits[videoTextureUnits[i] - 1] == 0)
  542. ++textureCounters[videoTextureUnits[i] - 1];
  543. glUniform1i(locs[i], videoTextureUnits[i]);
  544. }
  545. }
  546. }
  547. const GLuint textures[3] = {ytexture, cbtexture, crtexture};
  548. // Bind the textures to their respective texture units.
  549. for (int i = 0; i < 3; i++)
  550. {
  551. if (videoTextureUnits[i] != 0)
  552. {
  553. // Store texture id so it can be re-bound later.
  554. activeTexUnits[videoTextureUnits[i] - 1] = textures[i];
  555. gl.bindTextureToUnit(textures[i], videoTextureUnits[i], false);
  556. }
  557. }
  558. gl.setTextureUnit(0);
  559. }
  560. void Shader::checkSetScreenParams()
  561. {
  562. OpenGL::Viewport view = gl.getViewport();
  563. if (view == lastViewport && lastCanvas == Canvas::current)
  564. return;
  565. // In the shader, we do pixcoord.y = gl_FragCoord.y * params.z + params.w.
  566. // This lets us flip pixcoord.y when needed, to be consistent (drawing with
  567. // no Canvas active makes the y-values for pixel coordinates flipped.)
  568. GLfloat params[] = {
  569. (GLfloat) view.w, (GLfloat) view.h,
  570. 0.0f, 0.0f,
  571. };
  572. if (Canvas::current != nullptr)
  573. {
  574. // No flipping: pixcoord.y = gl_FragCoord.y * 1.0 + 0.0.
  575. params[2] = 1.0f;
  576. params[3] = 0.0f;
  577. }
  578. else
  579. {
  580. // gl_FragCoord.y is flipped when drawing to the screen, so we un-flip:
  581. // pixcoord.y = gl_FragCoord.y * -1.0 + height.
  582. params[2] = -1.0f;
  583. params[3] = (GLfloat) view.h;
  584. }
  585. GLint location = builtinUniforms[BUILTIN_SCREEN_SIZE];
  586. if (location >= 0)
  587. {
  588. TemporaryAttacher attacher(this);
  589. glUniform4fv(location, 1, params);
  590. }
  591. lastCanvas = Canvas::current;
  592. lastViewport = view;
  593. }
  594. void Shader::checkSetPointSize(float size)
  595. {
  596. if (size == lastPointSize)
  597. return;
  598. GLint location = builtinUniforms[BUILTIN_POINT_SIZE];
  599. if (location >= 0)
  600. {
  601. TemporaryAttacher attacher(this);
  602. glUniform1f(location, size);
  603. }
  604. lastPointSize = size;
  605. }
  606. void Shader::checkSetBuiltinUniforms()
  607. {
  608. checkSetScreenParams();
  609. // We use a more efficient method for sending transformation matrices to
  610. // the GPU on desktop GL.
  611. if (GLAD_ES_VERSION_2_0)
  612. {
  613. checkSetPointSize(gl.getPointSize());
  614. const Matrix4 &curxform = gl.matrices.transform.back();
  615. const Matrix4 &curproj = gl.matrices.projection.back();
  616. TemporaryAttacher attacher(this);
  617. bool tpmatrixneedsupdate = false;
  618. // Only upload the matrices if they've changed.
  619. if (memcmp(curxform.getElements(), lastTransformMatrix.getElements(), sizeof(float) * 16) != 0)
  620. {
  621. GLint location = builtinUniforms[BUILTIN_TRANSFORM_MATRIX];
  622. if (location >= 0)
  623. glUniformMatrix4fv(location, 1, GL_FALSE, curxform.getElements());
  624. // Also upload the re-calculated normal matrix, if possible. The
  625. // normal matrix is the transpose of the inverse of the rotation
  626. // portion (top-left 3x3) of the transform matrix.
  627. location = builtinUniforms[BUILTIN_NORMAL_MATRIX];
  628. if (location >= 0)
  629. {
  630. Matrix3 normalmatrix = Matrix3(curxform).transposedInverse();
  631. glUniformMatrix3fv(location, 1, GL_FALSE, normalmatrix.getElements());
  632. }
  633. tpmatrixneedsupdate = true;
  634. lastTransformMatrix = curxform;
  635. }
  636. if (memcmp(curproj.getElements(), lastProjectionMatrix.getElements(), sizeof(float) * 16) != 0)
  637. {
  638. GLint location = builtinUniforms[BUILTIN_PROJECTION_MATRIX];
  639. if (location >= 0)
  640. glUniformMatrix4fv(location, 1, GL_FALSE, curproj.getElements());
  641. tpmatrixneedsupdate = true;
  642. lastProjectionMatrix = curproj;
  643. }
  644. if (tpmatrixneedsupdate)
  645. {
  646. GLint location = builtinUniforms[BUILTIN_TRANSFORM_PROJECTION_MATRIX];
  647. if (location >= 0)
  648. {
  649. Matrix4 tp_matrix(curproj * curxform);
  650. glUniformMatrix4fv(location, 1, GL_FALSE, tp_matrix.getElements());
  651. }
  652. }
  653. }
  654. }
  655. const std::map<std::string, Object *> &Shader::getBoundRetainables() const
  656. {
  657. return boundRetainables;
  658. }
  659. std::string Shader::getGLSLVersion()
  660. {
  661. const char *tmp = (const char *) glGetString(GL_SHADING_LANGUAGE_VERSION);
  662. if (tmp == nullptr)
  663. return "0.0";
  664. // the version string always begins with a version number of the format
  665. // major_number.minor_number
  666. // or
  667. // major_number.minor_number.release_number
  668. // we can keep release_number, since it does not affect the check below.
  669. std::string versionstring(tmp);
  670. size_t minorendpos = versionstring.find(' ');
  671. return versionstring.substr(0, minorendpos);
  672. }
  673. bool Shader::isSupported()
  674. {
  675. return GLAD_ES_VERSION_2_0 || (getGLSLVersion() >= "1.2");
  676. }
  677. int Shader::getUniformTypeSize(GLenum type) const
  678. {
  679. switch (type)
  680. {
  681. case GL_INT:
  682. case GL_FLOAT:
  683. case GL_BOOL:
  684. case GL_SAMPLER_1D:
  685. case GL_SAMPLER_2D:
  686. case GL_SAMPLER_3D:
  687. return 1;
  688. case GL_INT_VEC2:
  689. case GL_FLOAT_VEC2:
  690. case GL_FLOAT_MAT2:
  691. case GL_BOOL_VEC2:
  692. return 2;
  693. case GL_INT_VEC3:
  694. case GL_FLOAT_VEC3:
  695. case GL_FLOAT_MAT3:
  696. case GL_BOOL_VEC3:
  697. return 3;
  698. case GL_INT_VEC4:
  699. case GL_FLOAT_VEC4:
  700. case GL_FLOAT_MAT4:
  701. case GL_BOOL_VEC4:
  702. return 4;
  703. default:
  704. return 1;
  705. }
  706. }
  707. Shader::UniformType Shader::getUniformBaseType(GLenum type) const
  708. {
  709. switch (type)
  710. {
  711. case GL_INT:
  712. case GL_INT_VEC2:
  713. case GL_INT_VEC3:
  714. case GL_INT_VEC4:
  715. return UNIFORM_INT;
  716. case GL_FLOAT:
  717. case GL_FLOAT_VEC2:
  718. case GL_FLOAT_VEC3:
  719. case GL_FLOAT_VEC4:
  720. case GL_FLOAT_MAT2:
  721. case GL_FLOAT_MAT3:
  722. case GL_FLOAT_MAT4:
  723. case GL_FLOAT_MAT2x3:
  724. case GL_FLOAT_MAT2x4:
  725. case GL_FLOAT_MAT3x2:
  726. case GL_FLOAT_MAT3x4:
  727. case GL_FLOAT_MAT4x2:
  728. case GL_FLOAT_MAT4x3:
  729. return UNIFORM_FLOAT;
  730. case GL_BOOL:
  731. case GL_BOOL_VEC2:
  732. case GL_BOOL_VEC3:
  733. case GL_BOOL_VEC4:
  734. return UNIFORM_BOOL;
  735. case GL_SAMPLER_1D:
  736. case GL_SAMPLER_1D_SHADOW:
  737. case GL_SAMPLER_1D_ARRAY:
  738. case GL_SAMPLER_1D_ARRAY_SHADOW:
  739. case GL_SAMPLER_2D:
  740. case GL_SAMPLER_2D_MULTISAMPLE:
  741. case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
  742. case GL_SAMPLER_2D_RECT:
  743. case GL_SAMPLER_2D_RECT_SHADOW:
  744. case GL_SAMPLER_2D_SHADOW:
  745. case GL_SAMPLER_2D_ARRAY:
  746. case GL_SAMPLER_2D_ARRAY_SHADOW:
  747. case GL_SAMPLER_3D:
  748. case GL_SAMPLER_CUBE:
  749. case GL_SAMPLER_CUBE_SHADOW:
  750. case GL_SAMPLER_CUBE_MAP_ARRAY:
  751. case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
  752. return UNIFORM_SAMPLER;
  753. default:
  754. return UNIFORM_UNKNOWN;
  755. }
  756. }
  757. bool Shader::getConstant(const char *in, UniformType &out)
  758. {
  759. return uniformTypes.find(in, out);
  760. }
  761. bool Shader::getConstant(UniformType in, const char *&out)
  762. {
  763. return uniformTypes.find(in, out);
  764. }
  765. bool Shader::getConstant(const char *in, VertexAttribID &out)
  766. {
  767. return attribNames.find(in, out);
  768. }
  769. bool Shader::getConstant(VertexAttribID in, const char *&out)
  770. {
  771. return attribNames.find(in, out);
  772. }
  773. StringMap<Shader::ShaderStage, Shader::STAGE_MAX_ENUM>::Entry Shader::stageNameEntries[] =
  774. {
  775. {"vertex", Shader::STAGE_VERTEX},
  776. {"pixel", Shader::STAGE_PIXEL},
  777. };
  778. StringMap<Shader::ShaderStage, Shader::STAGE_MAX_ENUM> Shader::stageNames(Shader::stageNameEntries, sizeof(Shader::stageNameEntries));
  779. StringMap<Shader::UniformType, Shader::UNIFORM_MAX_ENUM>::Entry Shader::uniformTypeEntries[] =
  780. {
  781. {"float", Shader::UNIFORM_FLOAT},
  782. {"int", Shader::UNIFORM_INT},
  783. {"bool", Shader::UNIFORM_BOOL},
  784. {"image", Shader::UNIFORM_SAMPLER},
  785. {"unknown", Shader::UNIFORM_UNKNOWN},
  786. };
  787. StringMap<Shader::UniformType, Shader::UNIFORM_MAX_ENUM> Shader::uniformTypes(Shader::uniformTypeEntries, sizeof(Shader::uniformTypeEntries));
  788. StringMap<VertexAttribID, ATTRIB_MAX_ENUM>::Entry Shader::attribNameEntries[] =
  789. {
  790. {"VertexPosition", ATTRIB_POS},
  791. {"VertexTexCoord", ATTRIB_TEXCOORD},
  792. {"VertexColor", ATTRIB_COLOR},
  793. {"ConstantColor", ATTRIB_CONSTANTCOLOR},
  794. };
  795. StringMap<VertexAttribID, ATTRIB_MAX_ENUM> Shader::attribNames(Shader::attribNameEntries, sizeof(Shader::attribNameEntries));
  796. StringMap<Shader::BuiltinUniform, Shader::BUILTIN_MAX_ENUM>::Entry Shader::builtinNameEntries[] =
  797. {
  798. {"TransformMatrix", Shader::BUILTIN_TRANSFORM_MATRIX},
  799. {"ProjectionMatrix", Shader::BUILTIN_PROJECTION_MATRIX},
  800. {"TransformProjectionMatrix", Shader::BUILTIN_TRANSFORM_PROJECTION_MATRIX},
  801. {"NormalMatrix", Shader::BUILTIN_NORMAL_MATRIX},
  802. {"love_PointSize", Shader::BUILTIN_POINT_SIZE},
  803. {"love_ScreenSize", Shader::BUILTIN_SCREEN_SIZE},
  804. {"love_VideoYChannel", Shader::BUILTIN_VIDEO_Y_CHANNEL},
  805. {"love_VideoCbChannel", Shader::BUILTIN_VIDEO_CB_CHANNEL},
  806. {"love_VideoCrChannel", Shader::BUILTIN_VIDEO_CR_CHANNEL},
  807. };
  808. StringMap<Shader::BuiltinUniform, Shader::BUILTIN_MAX_ENUM> Shader::builtinNames(Shader::builtinNameEntries, sizeof(Shader::builtinNameEntries));
  809. } // opengl
  810. } // graphics
  811. } // love