OGLShaderProgram.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //
  2. // Copyright (c) 2008-2018 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../../Precompiled.h"
  23. #include "../../Graphics/ConstantBuffer.h"
  24. #include "../../Graphics/Graphics.h"
  25. #include "../../Graphics/GraphicsImpl.h"
  26. #include "../../Graphics/ShaderProgram.h"
  27. #include "../../Graphics/ShaderVariation.h"
  28. #include "../../IO/Log.h"
  29. #include "../../DebugNew.h"
  30. namespace Urho3D
  31. {
  32. static const char* shaderParameterGroups[] = {
  33. "frame",
  34. "camera",
  35. "zone",
  36. "light",
  37. "material",
  38. "object",
  39. "custom"
  40. };
  41. static unsigned NumberPostfix(const String& str)
  42. {
  43. for (unsigned i = 0; i < str.Length(); ++i)
  44. {
  45. if (IsDigit(str[i]))
  46. return ToUInt(str.CString() + i);
  47. }
  48. return M_MAX_UNSIGNED;
  49. }
  50. unsigned ShaderProgram::globalFrameNumber = 0;
  51. const void* ShaderProgram::globalParameterSources[MAX_SHADER_PARAMETER_GROUPS];
  52. ShaderProgram::ShaderProgram(Graphics* graphics, ShaderVariation* vertexShader, ShaderVariation* pixelShader) :
  53. GPUObject(graphics),
  54. vertexShader_(vertexShader),
  55. pixelShader_(pixelShader)
  56. {
  57. for (auto& parameterSource : parameterSources_)
  58. parameterSource = (const void*)M_MAX_UNSIGNED;
  59. }
  60. ShaderProgram::~ShaderProgram()
  61. {
  62. Release();
  63. }
  64. void ShaderProgram::OnDeviceLost()
  65. {
  66. GPUObject::OnDeviceLost();
  67. if (graphics_ && graphics_->GetShaderProgram() == this)
  68. graphics_->SetShaders(nullptr, nullptr);
  69. linkerOutput_.Clear();
  70. }
  71. void ShaderProgram::Release()
  72. {
  73. if (object_.name_)
  74. {
  75. if (!graphics_)
  76. return;
  77. if (!graphics_->IsDeviceLost())
  78. {
  79. if (graphics_->GetShaderProgram() == this)
  80. graphics_->SetShaders(nullptr, nullptr);
  81. glDeleteProgram(object_.name_);
  82. }
  83. object_.name_ = 0;
  84. linkerOutput_.Clear();
  85. shaderParameters_.Clear();
  86. vertexAttributes_.Clear();
  87. usedVertexAttributes_ = 0;
  88. for (bool& useTextureUnit : useTextureUnits_)
  89. useTextureUnit = false;
  90. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  91. constantBuffers_[i].Reset();
  92. }
  93. }
  94. bool ShaderProgram::Link()
  95. {
  96. Release();
  97. if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObjectName() || !pixelShader_->GetGPUObjectName())
  98. return false;
  99. object_.name_ = glCreateProgram();
  100. if (!object_.name_)
  101. {
  102. linkerOutput_ = "Could not create shader program";
  103. return false;
  104. }
  105. glAttachShader(object_.name_, vertexShader_->GetGPUObjectName());
  106. glAttachShader(object_.name_, pixelShader_->GetGPUObjectName());
  107. glLinkProgram(object_.name_);
  108. int linked, length;
  109. glGetProgramiv(object_.name_, GL_LINK_STATUS, &linked);
  110. if (!linked)
  111. {
  112. glGetProgramiv(object_.name_, GL_INFO_LOG_LENGTH, &length);
  113. linkerOutput_.Resize((unsigned)length);
  114. int outLength;
  115. glGetProgramInfoLog(object_.name_, length, &outLength, &linkerOutput_[0]);
  116. glDeleteProgram(object_.name_);
  117. object_.name_ = 0;
  118. }
  119. else
  120. linkerOutput_.Clear();
  121. if (!object_.name_)
  122. return false;
  123. const int MAX_NAME_LENGTH = 256;
  124. char nameBuffer[MAX_NAME_LENGTH];
  125. int attributeCount, uniformCount, elementCount, nameLength;
  126. GLenum type;
  127. glUseProgram(object_.name_);
  128. // Check for vertex attributes
  129. glGetProgramiv(object_.name_, GL_ACTIVE_ATTRIBUTES, &attributeCount);
  130. for (int i = 0; i < attributeCount; ++i)
  131. {
  132. glGetActiveAttrib(object_.name_, i, (GLsizei)MAX_NAME_LENGTH, &nameLength, &elementCount, &type, nameBuffer);
  133. String name = String(nameBuffer, nameLength);
  134. VertexElementSemantic semantic = MAX_VERTEX_ELEMENT_SEMANTICS;
  135. unsigned char semanticIndex = 0;
  136. // Go in reverse order so that "binormal" is detected before "normal"
  137. for (unsigned j = MAX_VERTEX_ELEMENT_SEMANTICS - 1; j < MAX_VERTEX_ELEMENT_SEMANTICS; --j)
  138. {
  139. if (name.Contains(ShaderVariation::elementSemanticNames[j], false))
  140. {
  141. semantic = (VertexElementSemantic)j;
  142. unsigned index = NumberPostfix(name);
  143. if (index != M_MAX_UNSIGNED)
  144. semanticIndex = (unsigned char)index;
  145. break;
  146. }
  147. }
  148. if (semantic == MAX_VERTEX_ELEMENT_SEMANTICS)
  149. {
  150. URHO3D_LOGWARNING("Found vertex attribute " + name + " with no known semantic in shader program " +
  151. vertexShader_->GetFullName() + " " + pixelShader_->GetFullName());
  152. continue;
  153. }
  154. int location = glGetAttribLocation(object_.name_, name.CString());
  155. vertexAttributes_[MakePair((unsigned char)semantic, semanticIndex)] = location;
  156. usedVertexAttributes_ |= (1 << location);
  157. }
  158. // Check for constant buffers
  159. #ifndef GL_ES_VERSION_2_0
  160. HashMap<unsigned, unsigned> blockToBinding;
  161. if (Graphics::GetGL3Support())
  162. {
  163. int numUniformBlocks = 0;
  164. glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
  165. for (int i = 0; i < numUniformBlocks; ++i)
  166. {
  167. glGetActiveUniformBlockName(object_.name_, (GLuint)i, MAX_NAME_LENGTH, &nameLength, nameBuffer);
  168. String name(nameBuffer, (unsigned)nameLength);
  169. unsigned blockIndex = glGetUniformBlockIndex(object_.name_, name.CString());
  170. unsigned group = M_MAX_UNSIGNED;
  171. // Try to recognize the use of the buffer from its name
  172. for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
  173. {
  174. if (name.Contains(shaderParameterGroups[j], false))
  175. {
  176. group = j;
  177. break;
  178. }
  179. }
  180. // If name is not recognized, search for a digit in the name and use that as the group index
  181. if (group == M_MAX_UNSIGNED)
  182. group = NumberPostfix(name);
  183. if (group >= MAX_SHADER_PARAMETER_GROUPS)
  184. {
  185. URHO3D_LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
  186. " " + pixelShader_->GetFullName());
  187. continue;
  188. }
  189. // Find total constant buffer data size
  190. int dataSize;
  191. glGetActiveUniformBlockiv(object_.name_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
  192. if (!dataSize)
  193. continue;
  194. unsigned bindingIndex = group;
  195. // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
  196. // from that point onward
  197. ShaderType shaderType = VS;
  198. if (name.Contains("PS", false))
  199. {
  200. bindingIndex += MAX_SHADER_PARAMETER_GROUPS;
  201. shaderType = PS;
  202. }
  203. glUniformBlockBinding(object_.name_, blockIndex, bindingIndex);
  204. blockToBinding[blockIndex] = bindingIndex;
  205. constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(shaderType, bindingIndex, (unsigned)dataSize);
  206. }
  207. }
  208. #endif
  209. // Check for shader parameters and texture units
  210. glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORMS, &uniformCount);
  211. for (int i = 0; i < uniformCount; ++i)
  212. {
  213. glGetActiveUniform(object_.name_, (GLuint)i, MAX_NAME_LENGTH, nullptr, &elementCount, &type, nameBuffer);
  214. int location = glGetUniformLocation(object_.name_, nameBuffer);
  215. // Check for array index included in the name and strip it
  216. String name(nameBuffer);
  217. unsigned index = name.Find('[');
  218. if (index != String::NPOS)
  219. {
  220. // If not the first index, skip
  221. if (name.Find("[0]", index) == String::NPOS)
  222. continue;
  223. name = name.Substring(0, index);
  224. }
  225. if (name[0] == 'c')
  226. {
  227. // Store constant uniform
  228. String paramName = name.Substring(1);
  229. ShaderParameter parameter{paramName, type, location};
  230. bool store = location >= 0;
  231. #ifndef GL_ES_VERSION_2_0
  232. // If running OpenGL 3, the uniform may be inside a constant buffer
  233. if (parameter.location_ < 0 && Graphics::GetGL3Support())
  234. {
  235. int blockIndex, blockOffset;
  236. glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
  237. glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
  238. if (blockIndex >= 0)
  239. {
  240. parameter.offset_ = blockOffset;
  241. parameter.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]];
  242. store = true;
  243. }
  244. }
  245. #endif
  246. if (store)
  247. shaderParameters_[StringHash(paramName)] = parameter;
  248. }
  249. else if (location >= 0 && name[0] == 's')
  250. {
  251. // Set the samplers here so that they do not have to be set later
  252. unsigned unit = graphics_->GetTextureUnit(name.Substring(1));
  253. if (unit >= MAX_TEXTURE_UNITS)
  254. unit = NumberPostfix(name);
  255. if (unit < MAX_TEXTURE_UNITS)
  256. {
  257. useTextureUnits_[unit] = true;
  258. glUniform1iv(location, 1, reinterpret_cast<int*>(&unit));
  259. }
  260. }
  261. }
  262. // Rehash the parameter & vertex attributes maps to ensure minimal load factor
  263. vertexAttributes_.Rehash(NextPowerOfTwo(vertexAttributes_.Size()));
  264. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  265. return true;
  266. }
  267. ShaderVariation* ShaderProgram::GetVertexShader() const
  268. {
  269. return vertexShader_;
  270. }
  271. ShaderVariation* ShaderProgram::GetPixelShader() const
  272. {
  273. return pixelShader_;
  274. }
  275. bool ShaderProgram::HasParameter(StringHash param) const
  276. {
  277. return shaderParameters_.Find(param) != shaderParameters_.End();
  278. }
  279. const ShaderParameter* ShaderProgram::GetParameter(StringHash param) const
  280. {
  281. HashMap<StringHash, ShaderParameter>::ConstIterator i = shaderParameters_.Find(param);
  282. if (i != shaderParameters_.End())
  283. return &i->second_;
  284. else
  285. return nullptr;
  286. }
  287. bool ShaderProgram::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  288. {
  289. // If global framenumber has changed, invalidate all per-program parameter sources now
  290. if (globalFrameNumber != frameNumber_)
  291. {
  292. for (auto& parameterSource : parameterSources_)
  293. parameterSource = (const void*)M_MAX_UNSIGNED;
  294. frameNumber_ = globalFrameNumber;
  295. }
  296. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  297. #ifndef GL_ES_VERSION_2_0
  298. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  299. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  300. bool needUpdate = false;
  301. if (useBuffer && globalParameterSources[group] != source)
  302. {
  303. globalParameterSources[group] = source;
  304. needUpdate = true;
  305. }
  306. if (useIndividual && parameterSources_[group] != source)
  307. {
  308. parameterSources_[group] = source;
  309. needUpdate = true;
  310. }
  311. return needUpdate;
  312. #else
  313. if (parameterSources_[group] != source)
  314. {
  315. parameterSources_[group] = source;
  316. return true;
  317. }
  318. else
  319. return false;
  320. #endif
  321. }
  322. void ShaderProgram::ClearParameterSource(ShaderParameterGroup group)
  323. {
  324. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  325. #ifndef GL_ES_VERSION_2_0
  326. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  327. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  328. if (useBuffer)
  329. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  330. if (useIndividual)
  331. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  332. #else
  333. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  334. #endif
  335. }
  336. void ShaderProgram::ClearParameterSources()
  337. {
  338. ++globalFrameNumber;
  339. if (!globalFrameNumber)
  340. ++globalFrameNumber;
  341. #ifndef GL_ES_VERSION_2_0
  342. for (auto& globalParameterSource : globalParameterSources)
  343. globalParameterSource = (const void*)M_MAX_UNSIGNED;
  344. #endif
  345. }
  346. void ShaderProgram::ClearGlobalParameterSource(ShaderParameterGroup group)
  347. {
  348. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  349. }
  350. }