Shader.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. /**
  2. * Copyright (c) 2006-2020 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 "ShaderStage.h"
  24. #include "Graphics.h"
  25. #include "graphics/vertex.h"
  26. // C++
  27. #include <algorithm>
  28. #include <limits>
  29. #include <sstream>
  30. namespace love
  31. {
  32. namespace graphics
  33. {
  34. namespace opengl
  35. {
  36. static bool isBuffer(Shader::UniformType utype)
  37. {
  38. return utype == Shader::UNIFORM_TEXELBUFFER || utype == Shader::UNIFORM_STORAGEBUFFER;
  39. }
  40. Shader::Shader(love::graphics::ShaderStage *vertex, love::graphics::ShaderStage *pixel)
  41. : love::graphics::Shader(vertex, pixel)
  42. , program(0)
  43. , builtinUniforms()
  44. , builtinUniformInfo()
  45. {
  46. // load shader source and create program object
  47. loadVolatile();
  48. }
  49. Shader::~Shader()
  50. {
  51. unloadVolatile();
  52. for (const auto &p : uniforms)
  53. {
  54. // Allocated with malloc().
  55. if (p.second.data != nullptr)
  56. free(p.second.data);
  57. if (p.second.baseType == UNIFORM_SAMPLER)
  58. {
  59. for (int i = 0; i < p.second.count; i++)
  60. {
  61. if (p.second.textures[i] != nullptr)
  62. p.second.textures[i]->release();
  63. }
  64. delete[] p.second.textures;
  65. }
  66. else if (isBuffer(p.second.baseType))
  67. {
  68. for (int i = 0; i < p.second.count; i++)
  69. {
  70. if (p.second.buffers[i] != nullptr)
  71. p.second.buffers[i]->release();
  72. }
  73. delete[] p.second.buffers;
  74. }
  75. }
  76. }
  77. void Shader::mapActiveUniforms()
  78. {
  79. // Built-in uniform locations default to -1 (nonexistent.)
  80. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  81. {
  82. builtinUniforms[i] = -1;
  83. builtinUniformInfo[i] = nullptr;
  84. }
  85. GLint activeprogram = 0;
  86. glGetIntegerv(GL_CURRENT_PROGRAM, &activeprogram);
  87. gl.useProgram(program);
  88. GLint numuniforms;
  89. glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &numuniforms);
  90. GLchar cname[256];
  91. const GLint bufsize = (GLint) (sizeof(cname) / sizeof(GLchar));
  92. std::map<std::string, UniformInfo> olduniforms = uniforms;
  93. uniforms.clear();
  94. for (int uindex = 0; uindex < numuniforms; uindex++)
  95. {
  96. GLsizei namelen = 0;
  97. GLenum gltype = 0;
  98. UniformInfo u = {};
  99. glGetActiveUniform(program, (GLuint) uindex, bufsize, &namelen, &u.count, &gltype, cname);
  100. u.name = std::string(cname, (size_t) namelen);
  101. u.location = glGetUniformLocation(program, u.name.c_str());
  102. u.baseType = getUniformBaseType(gltype);
  103. u.textureType = getUniformTextureType(gltype);
  104. u.dataBaseType = getUniformTexelBaseType(gltype);
  105. u.isDepthSampler = isDepthTextureType(gltype);
  106. if (u.baseType == UNIFORM_MATRIX)
  107. u.matrix = getMatrixSize(gltype);
  108. else
  109. u.components = getUniformTypeComponents(gltype);
  110. // glGetActiveUniform appends "[0]" to the end of array uniform names...
  111. if (u.name.length() > 3)
  112. {
  113. size_t findpos = u.name.find("[0]");
  114. if (findpos != std::string::npos && findpos == u.name.length() - 3)
  115. u.name.erase(u.name.length() - 3);
  116. }
  117. // If this is a built-in (LOVE-created) uniform, store the location.
  118. BuiltinUniform builtin = BUILTIN_MAX_ENUM;
  119. if (getConstant(u.name.c_str(), builtin))
  120. builtinUniforms[int(builtin)] = u.location;
  121. if (u.location == -1)
  122. continue;
  123. if ((u.baseType == UNIFORM_SAMPLER && builtin != BUILTIN_TEXTURE_MAIN) || u.baseType == UNIFORM_TEXELBUFFER)
  124. {
  125. TextureUnit unit;
  126. unit.type = u.textureType;
  127. unit.active = true;
  128. if (u.baseType == UNIFORM_TEXELBUFFER)
  129. {
  130. unit.isTexelBuffer = true;
  131. unit.texture = gl.getDefaultTexelBuffer();
  132. }
  133. else
  134. {
  135. unit.isTexelBuffer = false;
  136. unit.texture = gl.getDefaultTexture(u.textureType);
  137. }
  138. for (int i = 0; i < u.count; i++)
  139. textureUnits.push_back(unit);
  140. }
  141. // Make sure previously set uniform data is preserved, and shader-
  142. // initialized values are retrieved.
  143. auto oldu = olduniforms.find(u.name);
  144. if (oldu != olduniforms.end())
  145. {
  146. u.data = oldu->second.data;
  147. u.dataSize = oldu->second.dataSize;
  148. u.textures = oldu->second.textures;
  149. updateUniform(&u, u.count, true);
  150. }
  151. else
  152. {
  153. u.dataSize = 0;
  154. switch (u.baseType)
  155. {
  156. case UNIFORM_FLOAT:
  157. u.dataSize = sizeof(float) * u.components * u.count;
  158. u.data = malloc(u.dataSize);
  159. break;
  160. case UNIFORM_INT:
  161. case UNIFORM_BOOL:
  162. case UNIFORM_SAMPLER:
  163. case UNIFORM_TEXELBUFFER:
  164. u.dataSize = sizeof(int) * u.components * u.count;
  165. u.data = malloc(u.dataSize);
  166. break;
  167. case UNIFORM_UINT:
  168. u.dataSize = sizeof(unsigned int) * u.components * u.count;
  169. u.data = malloc(u.dataSize);
  170. break;
  171. case UNIFORM_MATRIX:
  172. u.dataSize = sizeof(float) * ((size_t)u.matrix.rows * u.matrix.columns) * u.count;
  173. u.data = malloc(u.dataSize);
  174. break;
  175. default:
  176. break;
  177. }
  178. if (u.dataSize > 0)
  179. {
  180. memset(u.data, 0, u.dataSize);
  181. if (u.baseType == UNIFORM_SAMPLER || u.baseType == UNIFORM_TEXELBUFFER)
  182. {
  183. int startunit = (int) textureUnits.size() - u.count;
  184. if (builtin == BUILTIN_TEXTURE_MAIN)
  185. startunit = 0;
  186. for (int i = 0; i < u.count; i++)
  187. u.ints[i] = startunit + i;
  188. glUniform1iv(u.location, u.count, u.ints);
  189. if (u.baseType == UNIFORM_TEXELBUFFER)
  190. {
  191. u.buffers = new love::graphics::Buffer*[u.count];
  192. memset(u.buffers, 0, sizeof(Buffer *) * u.count);
  193. }
  194. else
  195. {
  196. u.textures = new love::graphics::Texture*[u.count];
  197. memset(u.textures, 0, sizeof(Texture *) * u.count);
  198. }
  199. }
  200. }
  201. size_t offset = 0;
  202. // Store any shader-initialized values in our own memory.
  203. for (int i = 0; i < u.count; i++)
  204. {
  205. GLint location = u.location;
  206. if (u.count > 1)
  207. {
  208. std::ostringstream ss;
  209. ss << i;
  210. std::string indexname = u.name + "[" + ss.str() + "]";
  211. location = glGetUniformLocation(program, indexname.c_str());
  212. }
  213. if (location == -1)
  214. continue;
  215. switch (u.baseType)
  216. {
  217. case UNIFORM_FLOAT:
  218. glGetUniformfv(program, location, &u.floats[offset]);
  219. offset += u.components;
  220. break;
  221. case UNIFORM_INT:
  222. case UNIFORM_BOOL:
  223. glGetUniformiv(program, location, &u.ints[offset]);
  224. offset += u.components;
  225. break;
  226. case UNIFORM_UINT:
  227. glGetUniformuiv(program, location, &u.uints[offset]);
  228. offset += u.components;
  229. break;
  230. case UNIFORM_MATRIX:
  231. glGetUniformfv(program, location, &u.floats[offset]);
  232. offset += (size_t)u.matrix.rows * u.matrix.columns;
  233. break;
  234. default:
  235. break;
  236. }
  237. }
  238. }
  239. uniforms[u.name] = u;
  240. if (builtin != BUILTIN_MAX_ENUM)
  241. builtinUniformInfo[(int)builtin] = &uniforms[u.name];
  242. if (u.baseType == UNIFORM_SAMPLER)
  243. {
  244. // Make sure all stored textures have their Volatiles loaded before
  245. // the sendTextures call, since it calls getHandle().
  246. for (int i = 0; i < u.count; i++)
  247. {
  248. if (u.textures[i] == nullptr)
  249. continue;
  250. Volatile *v = dynamic_cast<Volatile *>(u.textures[i]);
  251. if (v != nullptr)
  252. v->loadVolatile();
  253. }
  254. sendTextures(&u, u.textures, u.count, true);
  255. }
  256. else if (u.baseType == UNIFORM_TEXELBUFFER)
  257. {
  258. for (int i = 0; i < u.count; i++)
  259. {
  260. if (u.buffers[i] == nullptr)
  261. continue;
  262. Volatile *v = dynamic_cast<Volatile *>(u.buffers[i]);
  263. if (v != nullptr)
  264. v->loadVolatile();
  265. }
  266. sendBuffers(&u, u.buffers, u.count, true);
  267. }
  268. }
  269. if (gl.isBufferUsageSupported(BUFFERUSAGE_SHADER_STORAGE))
  270. {
  271. GLint numstoragebuffers = 0;
  272. glGetProgramInterfaceiv(program, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &numstoragebuffers);
  273. char namebuffer[2048] = { '\0' };
  274. for (int sindex = 0; sindex < numstoragebuffers; sindex++)
  275. {
  276. UniformInfo u = {};
  277. u.baseType = UNIFORM_STORAGEBUFFER;
  278. GLsizei namelength = 0;
  279. glGetProgramResourceName(program, GL_SHADER_STORAGE_BLOCK, sindex, 2048, &namelength, namebuffer);
  280. u.name = std::string(namebuffer, namelength);
  281. u.count = 1;
  282. const auto reflectionit = validationReflection.storageBuffers.find(u.name);
  283. if (reflectionit != validationReflection.storageBuffers.end())
  284. {
  285. u.bufferStride = reflectionit->second.stride;
  286. u.bufferMemberCount = reflectionit->second.memberCount;
  287. }
  288. // Make sure previously set uniform data is preserved, and shader-
  289. // initialized values are retrieved.
  290. auto oldu = olduniforms.find(u.name);
  291. if (oldu != olduniforms.end())
  292. {
  293. u.data = oldu->second.data;
  294. u.dataSize = oldu->second.dataSize;
  295. u.buffers = oldu->second.buffers;
  296. }
  297. else
  298. {
  299. u.dataSize = sizeof(int) * 1;
  300. u.data = malloc(u.dataSize);
  301. u.ints[0] = -1;
  302. u.buffers = new love::graphics::Buffer * [u.count];
  303. memset(u.buffers, 0, sizeof(Buffer*)* u.count);
  304. }
  305. GLenum props[] = { GL_BUFFER_BINDING };
  306. glGetProgramResourceiv(program, GL_SHADER_STORAGE_BLOCK, sindex, 1, props, 1, nullptr, u.ints);
  307. BufferBinding binding;
  308. binding.bindingindex = u.ints[0];
  309. binding.buffer = gl.getDefaultStorageBuffer();
  310. if (binding.bindingindex >= 0)
  311. {
  312. int activeindex = (int)activeStorageBufferBindings.size();
  313. storageBufferBindingIndexToActiveBinding[binding.bindingindex] = activeindex;
  314. activeStorageBufferBindings.push_back(binding);
  315. }
  316. uniforms[u.name] = u;
  317. for (int i = 0; i < u.count; i++)
  318. {
  319. if (u.buffers[i] == nullptr)
  320. continue;
  321. Volatile* v = dynamic_cast<Volatile*>(u.buffers[i]);
  322. if (v != nullptr)
  323. v->loadVolatile();
  324. }
  325. sendBuffers(&u, u.buffers, u.count, true);
  326. }
  327. }
  328. // Make sure uniforms that existed before but don't exist anymore are
  329. // cleaned up. This theoretically shouldn't happen, but...
  330. for (const auto &p : olduniforms)
  331. {
  332. if (uniforms.find(p.first) == uniforms.end())
  333. {
  334. if (p.second.data != nullptr)
  335. free(p.second.data);
  336. if (p.second.baseType == UNIFORM_SAMPLER)
  337. {
  338. for (int i = 0; i < p.second.count; i++)
  339. {
  340. if (p.second.textures[i] != nullptr)
  341. p.second.textures[i]->release();
  342. }
  343. delete[] p.second.textures;
  344. }
  345. else if (isBuffer(p.second.baseType))
  346. {
  347. for (int i = 0; i < p.second.count; i++)
  348. {
  349. if (p.second.buffers[i] != nullptr)
  350. p.second.buffers[i]->release();
  351. }
  352. delete[] p.second.buffers;
  353. }
  354. }
  355. }
  356. gl.useProgram(activeprogram);
  357. }
  358. bool Shader::loadVolatile()
  359. {
  360. OpenGL::TempDebugGroup debuggroup("Shader load");
  361. // zero out active texture list
  362. textureUnits.clear();
  363. textureUnits.push_back(TextureUnit());
  364. storageBufferBindingIndexToActiveBinding.resize(gl.getMaxShaderStorageBufferBindings(), -1);
  365. activeStorageBufferBindings.clear();
  366. for (const auto &stage : stages)
  367. {
  368. if (stage.get() != nullptr)
  369. ((ShaderStage*)stage.get())->loadVolatile();
  370. }
  371. program = glCreateProgram();
  372. if (program == 0)
  373. throw love::Exception("Cannot create shader program object.");
  374. for (const auto &stage : stages)
  375. {
  376. if (stage.get() != nullptr)
  377. glAttachShader(program, (GLuint) stage->getHandle());
  378. }
  379. // Bind generic vertex attribute indices to names in the shader.
  380. for (int i = 0; i < int(ATTRIB_MAX_ENUM); i++)
  381. {
  382. const char *name = nullptr;
  383. if (graphics::getConstant((BuiltinVertexAttribute) i, name))
  384. glBindAttribLocation(program, i, (const GLchar *) name);
  385. }
  386. glLinkProgram(program);
  387. GLint status;
  388. glGetProgramiv(program, GL_LINK_STATUS, &status);
  389. if (status == GL_FALSE)
  390. {
  391. std::string warnings = getProgramWarnings();
  392. glDeleteProgram(program);
  393. program = 0;
  394. throw love::Exception("Cannot link shader program object:\n%s", warnings.c_str());
  395. }
  396. // Get all active uniform variables in this shader from OpenGL.
  397. mapActiveUniforms();
  398. if (current == this)
  399. {
  400. // make sure glUseProgram gets called.
  401. current = nullptr;
  402. attach();
  403. }
  404. return true;
  405. }
  406. void Shader::unloadVolatile()
  407. {
  408. if (program != 0)
  409. {
  410. if (current == this)
  411. gl.useProgram(0);
  412. glDeleteProgram(program);
  413. program = 0;
  414. }
  415. // active texture list is probably invalid, clear it
  416. textureUnits.clear();
  417. textureUnits.push_back(TextureUnit());
  418. attributes.clear();
  419. // And the locations of any built-in uniform variables.
  420. for (int i = 0; i < int(BUILTIN_MAX_ENUM); i++)
  421. builtinUniforms[i] = -1;
  422. }
  423. std::string Shader::getProgramWarnings() const
  424. {
  425. GLint strsize, nullpos;
  426. glGetProgramiv(program, GL_INFO_LOG_LENGTH, &strsize);
  427. if (strsize == 0)
  428. return "";
  429. char *tempstr = new char[strsize];
  430. // be extra sure that the error string will be 0-terminated
  431. memset(tempstr, '\0', strsize);
  432. glGetProgramInfoLog(program, strsize, &nullpos, tempstr);
  433. tempstr[nullpos] = '\0';
  434. std::string warnings(tempstr);
  435. delete[] tempstr;
  436. return warnings;
  437. }
  438. std::string Shader::getWarnings() const
  439. {
  440. std::string warnings;
  441. const char *stagestr;
  442. for (const auto &stage : stages)
  443. {
  444. if (stage.get() == nullptr)
  445. continue;
  446. const std::string &stagewarnings = stage->getWarnings();
  447. if (ShaderStage::getConstant(stage->getStageType(), stagestr))
  448. warnings += std::string(stagestr) + std::string(" shader:\n") + stagewarnings;
  449. }
  450. warnings += getProgramWarnings();
  451. return warnings;
  452. }
  453. void Shader::attach()
  454. {
  455. if (current != this)
  456. {
  457. Graphics::flushBatchedDrawsGlobal();
  458. gl.useProgram(program);
  459. current = this;
  460. // retain/release happens in Graphics::setShader.
  461. // Make sure all textures are bound to their respective texture units.
  462. for (int i = 0; i < (int) textureUnits.size(); ++i)
  463. {
  464. const TextureUnit &unit = textureUnits[i];
  465. if (unit.active)
  466. {
  467. if (unit.isTexelBuffer)
  468. gl.bindBufferTextureToUnit(unit.texture, i, false, false);
  469. else
  470. gl.bindTextureToUnit(unit.type, unit.texture, i, false, false);
  471. }
  472. }
  473. for (auto bufferbinding : activeStorageBufferBindings)
  474. gl.bindIndexedBuffer(bufferbinding.buffer, BUFFERUSAGE_SHADER_STORAGE, bufferbinding.bindingindex);
  475. // send any pending uniforms to the shader program.
  476. for (const auto &p : pendingUniformUpdates)
  477. updateUniform(p.first, p.second, true);
  478. pendingUniformUpdates.clear();
  479. }
  480. }
  481. const Shader::UniformInfo *Shader::getUniformInfo(const std::string &name) const
  482. {
  483. const auto it = uniforms.find(name);
  484. if (it == uniforms.end())
  485. return nullptr;
  486. return &(it->second);
  487. }
  488. const Shader::UniformInfo *Shader::getUniformInfo(BuiltinUniform builtin) const
  489. {
  490. return builtinUniformInfo[(int)builtin];
  491. }
  492. void Shader::updateUniform(const UniformInfo *info, int count)
  493. {
  494. updateUniform(info, count, false);
  495. }
  496. void Shader::updateUniform(const UniformInfo *info, int count, bool internalupdate)
  497. {
  498. if (current != this && !internalupdate)
  499. {
  500. pendingUniformUpdates.push_back(std::make_pair(info, count));
  501. return;
  502. }
  503. if (!internalupdate)
  504. flushBatchedDraws();
  505. int location = info->location;
  506. UniformType type = info->baseType;
  507. if (type == UNIFORM_FLOAT)
  508. {
  509. switch (info->components)
  510. {
  511. case 1:
  512. glUniform1fv(location, count, info->floats);
  513. break;
  514. case 2:
  515. glUniform2fv(location, count, info->floats);
  516. break;
  517. case 3:
  518. glUniform3fv(location, count, info->floats);
  519. break;
  520. case 4:
  521. glUniform4fv(location, count, info->floats);
  522. break;
  523. }
  524. }
  525. else if (type == UNIFORM_INT || type == UNIFORM_BOOL || type == UNIFORM_SAMPLER || type == UNIFORM_TEXELBUFFER)
  526. {
  527. switch (info->components)
  528. {
  529. case 1:
  530. glUniform1iv(location, count, info->ints);
  531. break;
  532. case 2:
  533. glUniform2iv(location, count, info->ints);
  534. break;
  535. case 3:
  536. glUniform3iv(location, count, info->ints);
  537. break;
  538. case 4:
  539. glUniform4iv(location, count, info->ints);
  540. break;
  541. }
  542. }
  543. else if (type == UNIFORM_UINT)
  544. {
  545. switch (info->components)
  546. {
  547. case 1:
  548. glUniform1uiv(location, count, info->uints);
  549. break;
  550. case 2:
  551. glUniform2uiv(location, count, info->uints);
  552. break;
  553. case 3:
  554. glUniform3uiv(location, count, info->uints);
  555. break;
  556. case 4:
  557. glUniform4uiv(location, count, info->uints);
  558. break;
  559. }
  560. }
  561. else if (type == UNIFORM_MATRIX)
  562. {
  563. int columns = info->matrix.columns;
  564. int rows = info->matrix.rows;
  565. if (columns == 2 && rows == 2)
  566. glUniformMatrix2fv(location, count, GL_FALSE, info->floats);
  567. else if (columns == 3 && rows == 3)
  568. glUniformMatrix3fv(location, count, GL_FALSE, info->floats);
  569. else if (columns == 4 && rows == 4)
  570. glUniformMatrix4fv(location, count, GL_FALSE, info->floats);
  571. else if (columns == 2 && rows == 3)
  572. glUniformMatrix2x3fv(location, count, GL_FALSE, info->floats);
  573. else if (columns == 2 && rows == 4)
  574. glUniformMatrix2x4fv(location, count, GL_FALSE, info->floats);
  575. else if (columns == 3 && rows == 2)
  576. glUniformMatrix3x2fv(location, count, GL_FALSE, info->floats);
  577. else if (columns == 3 && rows == 4)
  578. glUniformMatrix3x4fv(location, count, GL_FALSE, info->floats);
  579. else if (columns == 4 && rows == 2)
  580. glUniformMatrix4x2fv(location, count, GL_FALSE, info->floats);
  581. else if (columns == 4 && rows == 3)
  582. glUniformMatrix4x3fv(location, count, GL_FALSE, info->floats);
  583. }
  584. }
  585. void Shader::sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count)
  586. {
  587. Shader::sendTextures(info, textures, count, false);
  588. }
  589. void Shader::sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count, bool internalUpdate)
  590. {
  591. if (info->baseType != UNIFORM_SAMPLER)
  592. return;
  593. bool shaderactive = current == this;
  594. if (!internalUpdate && shaderactive)
  595. flushBatchedDraws();
  596. count = std::min(count, info->count);
  597. // Bind the textures to the texture units.
  598. for (int i = 0; i < count; i++)
  599. {
  600. love::graphics::Texture *tex = textures[i];
  601. if (tex != nullptr)
  602. {
  603. if (!validateTexture(info, tex, internalUpdate))
  604. continue;
  605. tex->retain();
  606. }
  607. if (info->textures[i] != nullptr)
  608. info->textures[i]->release();
  609. info->textures[i] = tex;
  610. GLuint gltex = 0;
  611. if (textures[i] != nullptr)
  612. gltex = (GLuint) tex->getHandle();
  613. else
  614. gltex = gl.getDefaultTexture(info->textureType);
  615. int texunit = info->ints[i];
  616. if (shaderactive)
  617. gl.bindTextureToUnit(info->textureType, gltex, texunit, false, false);
  618. // Store texture id so it can be re-bound to the texture unit later.
  619. textureUnits[texunit].texture = gltex;
  620. }
  621. }
  622. void Shader::sendBuffers(const UniformInfo *info, love::graphics::Buffer **buffers, int count)
  623. {
  624. Shader::sendBuffers(info, buffers, count, false);
  625. }
  626. void Shader::sendBuffers(const UniformInfo *info, love::graphics::Buffer **buffers, int count, bool internalUpdate)
  627. {
  628. bool texelbinding = info->baseType == UNIFORM_TEXELBUFFER;
  629. bool storagebinding = info->baseType == UNIFORM_STORAGEBUFFER;
  630. if (!texelbinding && !storagebinding)
  631. return;
  632. bool shaderactive = current == this;
  633. if (!internalUpdate && shaderactive)
  634. flushBatchedDraws();
  635. count = std::min(count, info->count);
  636. // Bind the textures to the texture units.
  637. for (int i = 0; i < count; i++)
  638. {
  639. love::graphics::Buffer *buffer = buffers[i];
  640. if (buffer != nullptr)
  641. {
  642. if (!validateBuffer(info, buffer, internalUpdate))
  643. continue;
  644. buffer->retain();
  645. }
  646. if (info->buffers[i] != nullptr)
  647. info->buffers[i]->release();
  648. info->buffers[i] = buffer;
  649. if (texelbinding)
  650. {
  651. GLuint gltex = 0;
  652. if (buffers[i] != nullptr)
  653. gltex = (GLuint) buffer->getTexelBufferHandle();
  654. else
  655. gltex = gl.getDefaultTexelBuffer();
  656. int texunit = info->ints[i];
  657. if (shaderactive)
  658. gl.bindBufferTextureToUnit(gltex, texunit, false, false);
  659. // Store texture id so it can be re-bound to the texture unit later.
  660. textureUnits[texunit].texture = gltex;
  661. }
  662. else if (storagebinding)
  663. {
  664. int bindingindex = info->ints[i];
  665. GLuint glbuffer = 0;
  666. if (buffers[i] != nullptr)
  667. glbuffer = (GLuint) buffer->getHandle();
  668. else
  669. glbuffer = gl.getDefaultStorageBuffer();
  670. if (shaderactive)
  671. gl.bindIndexedBuffer(glbuffer, BUFFERUSAGE_SHADER_STORAGE, bindingindex);
  672. int activeindex = storageBufferBindingIndexToActiveBinding[bindingindex];
  673. if (activeindex >= 0)
  674. activeStorageBufferBindings[activeindex].buffer = glbuffer;
  675. }
  676. }
  677. }
  678. void Shader::flushBatchedDraws() const
  679. {
  680. if (current == this)
  681. Graphics::flushBatchedDrawsGlobal();
  682. }
  683. bool Shader::hasUniform(const std::string &name) const
  684. {
  685. return uniforms.find(name) != uniforms.end();
  686. }
  687. ptrdiff_t Shader::getHandle() const
  688. {
  689. return program;
  690. }
  691. int Shader::getVertexAttributeIndex(const std::string &name)
  692. {
  693. auto it = attributes.find(name);
  694. if (it != attributes.end())
  695. return it->second;
  696. GLint location = glGetAttribLocation(program, name.c_str());
  697. attributes[name] = location;
  698. return location;
  699. }
  700. void Shader::setVideoTextures(love::graphics::Texture *ytexture, love::graphics::Texture *cbtexture, love::graphics::Texture *crtexture)
  701. {
  702. const BuiltinUniform builtins[3] = {
  703. BUILTIN_TEXTURE_VIDEO_Y,
  704. BUILTIN_TEXTURE_VIDEO_CB,
  705. BUILTIN_TEXTURE_VIDEO_CR,
  706. };
  707. love::graphics::Texture *textures[3] = {ytexture, cbtexture, crtexture};
  708. for (int i = 0; i < 3; i++)
  709. {
  710. const UniformInfo *info = builtinUniformInfo[builtins[i]];
  711. if (info != nullptr)
  712. sendTextures(info, &textures[i], 1, true);
  713. }
  714. }
  715. void Shader::updateBuiltinUniforms(love::graphics::Graphics *gfx, int viewportW, int viewportH)
  716. {
  717. if (current != this)
  718. return;
  719. BuiltinUniformData data;
  720. data.transformMatrix = gfx->getTransform();
  721. data.projectionMatrix = gfx->getProjection();
  722. // The normal matrix is the transpose of the inverse of the rotation portion
  723. // (top-left 3x3) of the transform matrix.
  724. {
  725. Matrix3 normalmatrix = Matrix3(data.transformMatrix).transposedInverse();
  726. const float *e = normalmatrix.getElements();
  727. for (int i = 0; i < 3; i++)
  728. {
  729. data.normalMatrix[i].x = e[i * 3 + 0];
  730. data.normalMatrix[i].y = e[i * 3 + 1];
  731. data.normalMatrix[i].z = e[i * 3 + 2];
  732. data.normalMatrix[i].w = 0.0f;
  733. }
  734. }
  735. // Store DPI scale in an unused component of another vector.
  736. data.normalMatrix[0].w = (float) gfx->getCurrentDPIScale();
  737. // Same with point size.
  738. data.normalMatrix[1].w = gfx->getPointSize();
  739. data.screenSizeParams.x = viewportW;
  740. data.screenSizeParams.y = viewportH;
  741. // The shader does pixcoord.y = gl_FragCoord.y * params.z + params.w.
  742. // This lets us flip pixcoord.y when needed, to be consistent (drawing
  743. // with no RT active makes the pixel coordinates y-flipped.)
  744. if (gfx->isRenderTargetActive())
  745. {
  746. // No flipping: pixcoord.y = gl_FragCoord.y * 1.0 + 0.0.
  747. data.screenSizeParams.z = 1.0f;
  748. data.screenSizeParams.w = 0.0f;
  749. }
  750. else
  751. {
  752. // gl_FragCoord.y is flipped when drawing to the screen, so we
  753. // un-flip: pixcoord.y = gl_FragCoord.y * -1.0 + height.
  754. data.screenSizeParams.z = -1.0f;
  755. data.screenSizeParams.w = viewportH;
  756. }
  757. data.constantColor = gfx->getColor();
  758. gammaCorrectColor(data.constantColor);
  759. GLint location = builtinUniforms[BUILTIN_UNIFORMS_PER_DRAW];
  760. if (location >= 0)
  761. glUniform4fv(location, 13, (const GLfloat *) &data);
  762. }
  763. int Shader::getUniformTypeComponents(GLenum type) const
  764. {
  765. UniformType basetype = getUniformBaseType(type);
  766. if (basetype == UNIFORM_SAMPLER || basetype == UNIFORM_TEXELBUFFER)
  767. return 1;
  768. switch (type)
  769. {
  770. case GL_INT:
  771. case GL_UNSIGNED_INT:
  772. case GL_FLOAT:
  773. case GL_BOOL:
  774. return 1;
  775. case GL_INT_VEC2:
  776. case GL_UNSIGNED_INT_VEC2:
  777. case GL_FLOAT_VEC2:
  778. case GL_FLOAT_MAT2:
  779. case GL_BOOL_VEC2:
  780. return 2;
  781. case GL_INT_VEC3:
  782. case GL_UNSIGNED_INT_VEC3:
  783. case GL_FLOAT_VEC3:
  784. case GL_FLOAT_MAT3:
  785. case GL_BOOL_VEC3:
  786. return 3;
  787. case GL_INT_VEC4:
  788. case GL_UNSIGNED_INT_VEC4:
  789. case GL_FLOAT_VEC4:
  790. case GL_FLOAT_MAT4:
  791. case GL_BOOL_VEC4:
  792. return 4;
  793. default:
  794. return 1;
  795. }
  796. }
  797. Shader::MatrixSize Shader::getMatrixSize(GLenum type) const
  798. {
  799. MatrixSize m;
  800. switch (type)
  801. {
  802. case GL_FLOAT_MAT2:
  803. m.columns = m.rows = 2;
  804. break;
  805. case GL_FLOAT_MAT3:
  806. m.columns = m.rows = 3;
  807. break;
  808. case GL_FLOAT_MAT4:
  809. m.columns = m.rows = 4;
  810. break;
  811. case GL_FLOAT_MAT2x3:
  812. m.columns = 2;
  813. m.rows = 3;
  814. break;
  815. case GL_FLOAT_MAT2x4:
  816. m.columns = 2;
  817. m.rows = 4;
  818. break;
  819. case GL_FLOAT_MAT3x2:
  820. m.columns = 3;
  821. m.rows = 2;
  822. break;
  823. case GL_FLOAT_MAT3x4:
  824. m.columns = 3;
  825. m.rows = 4;
  826. break;
  827. case GL_FLOAT_MAT4x2:
  828. m.columns = 4;
  829. m.rows = 2;
  830. break;
  831. case GL_FLOAT_MAT4x3:
  832. m.columns = 4;
  833. m.rows = 3;
  834. break;
  835. }
  836. return m;
  837. }
  838. Shader::UniformType Shader::getUniformBaseType(GLenum type) const
  839. {
  840. switch (type)
  841. {
  842. case GL_INT:
  843. case GL_INT_VEC2:
  844. case GL_INT_VEC3:
  845. case GL_INT_VEC4:
  846. return UNIFORM_INT;
  847. case GL_UNSIGNED_INT:
  848. case GL_UNSIGNED_INT_VEC2:
  849. case GL_UNSIGNED_INT_VEC3:
  850. case GL_UNSIGNED_INT_VEC4:
  851. return UNIFORM_UINT;
  852. case GL_FLOAT:
  853. case GL_FLOAT_VEC2:
  854. case GL_FLOAT_VEC3:
  855. case GL_FLOAT_VEC4:
  856. return UNIFORM_FLOAT;
  857. case GL_FLOAT_MAT2:
  858. case GL_FLOAT_MAT3:
  859. case GL_FLOAT_MAT4:
  860. case GL_FLOAT_MAT2x3:
  861. case GL_FLOAT_MAT2x4:
  862. case GL_FLOAT_MAT3x2:
  863. case GL_FLOAT_MAT3x4:
  864. case GL_FLOAT_MAT4x2:
  865. case GL_FLOAT_MAT4x3:
  866. return UNIFORM_MATRIX;
  867. case GL_BOOL:
  868. case GL_BOOL_VEC2:
  869. case GL_BOOL_VEC3:
  870. case GL_BOOL_VEC4:
  871. return UNIFORM_BOOL;
  872. case GL_SAMPLER_1D:
  873. case GL_SAMPLER_1D_SHADOW:
  874. case GL_SAMPLER_1D_ARRAY:
  875. case GL_SAMPLER_1D_ARRAY_SHADOW:
  876. case GL_SAMPLER_2D:
  877. case GL_SAMPLER_2D_MULTISAMPLE:
  878. case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
  879. case GL_SAMPLER_2D_RECT:
  880. case GL_SAMPLER_2D_RECT_SHADOW:
  881. case GL_SAMPLER_2D_SHADOW:
  882. case GL_SAMPLER_2D_ARRAY:
  883. case GL_SAMPLER_2D_ARRAY_SHADOW:
  884. case GL_SAMPLER_3D:
  885. case GL_SAMPLER_CUBE:
  886. case GL_SAMPLER_CUBE_SHADOW:
  887. case GL_SAMPLER_CUBE_MAP_ARRAY:
  888. case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
  889. return UNIFORM_SAMPLER;
  890. case GL_SAMPLER_BUFFER:
  891. case GL_INT_SAMPLER_BUFFER:
  892. case GL_UNSIGNED_INT_SAMPLER_BUFFER:
  893. return UNIFORM_TEXELBUFFER;
  894. default:
  895. return UNIFORM_UNKNOWN;
  896. }
  897. }
  898. TextureType Shader::getUniformTextureType(GLenum type) const
  899. {
  900. switch (type)
  901. {
  902. case GL_SAMPLER_1D:
  903. case GL_SAMPLER_1D_SHADOW:
  904. case GL_SAMPLER_1D_ARRAY:
  905. case GL_SAMPLER_1D_ARRAY_SHADOW:
  906. // 1D-typed textures are not supported.
  907. return TEXTURE_MAX_ENUM;
  908. case GL_SAMPLER_2D:
  909. case GL_SAMPLER_2D_SHADOW:
  910. return TEXTURE_2D;
  911. case GL_SAMPLER_2D_MULTISAMPLE:
  912. case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
  913. // Multisample textures are not supported.
  914. return TEXTURE_MAX_ENUM;
  915. case GL_SAMPLER_2D_RECT:
  916. case GL_SAMPLER_2D_RECT_SHADOW:
  917. // Rectangle textures are not supported.
  918. return TEXTURE_MAX_ENUM;
  919. case GL_SAMPLER_2D_ARRAY:
  920. case GL_SAMPLER_2D_ARRAY_SHADOW:
  921. return TEXTURE_2D_ARRAY;
  922. case GL_SAMPLER_3D:
  923. return TEXTURE_VOLUME;
  924. case GL_SAMPLER_CUBE:
  925. case GL_SAMPLER_CUBE_SHADOW:
  926. return TEXTURE_CUBE;
  927. case GL_SAMPLER_CUBE_MAP_ARRAY:
  928. case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
  929. // Cubemap array textures are not supported.
  930. return TEXTURE_MAX_ENUM;
  931. default:
  932. return TEXTURE_MAX_ENUM;
  933. }
  934. }
  935. DataBaseType Shader::getUniformTexelBaseType(GLenum type) const
  936. {
  937. switch (type)
  938. {
  939. case GL_SAMPLER_BUFFER:
  940. return DATA_BASETYPE_FLOAT;
  941. case GL_INT_SAMPLER_BUFFER:
  942. return DATA_BASETYPE_INT;
  943. case GL_UNSIGNED_INT_SAMPLER_BUFFER:
  944. return DATA_BASETYPE_UINT;
  945. default:
  946. return DATA_BASETYPE_MAX_ENUM;
  947. }
  948. }
  949. bool Shader::isDepthTextureType(GLenum type) const
  950. {
  951. switch (type)
  952. {
  953. case GL_SAMPLER_1D_SHADOW:
  954. case GL_SAMPLER_1D_ARRAY_SHADOW:
  955. case GL_SAMPLER_2D_SHADOW:
  956. case GL_SAMPLER_2D_ARRAY_SHADOW:
  957. case GL_SAMPLER_CUBE_SHADOW:
  958. case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW:
  959. return true;
  960. default:
  961. return false;
  962. }
  963. }
  964. } // opengl
  965. } // graphics
  966. } // love