OGLShaderProgram.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. //
  2. // Copyright (c) 2008-2017 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. usedVertexAttributes_(0),
  57. frameNumber_(0)
  58. {
  59. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  60. useTextureUnit_[i] = false;
  61. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  62. parameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  63. }
  64. ShaderProgram::~ShaderProgram()
  65. {
  66. Release();
  67. }
  68. void ShaderProgram::OnDeviceLost()
  69. {
  70. GPUObject::OnDeviceLost();
  71. if (graphics_ && graphics_->GetShaderProgram() == this)
  72. graphics_->SetShaders(0, 0);
  73. linkerOutput_.Clear();
  74. }
  75. void ShaderProgram::Release()
  76. {
  77. if (object_.name_)
  78. {
  79. if (!graphics_)
  80. return;
  81. if (!graphics_->IsDeviceLost())
  82. {
  83. if (graphics_->GetShaderProgram() == this)
  84. graphics_->SetShaders(0, 0);
  85. glDeleteProgram(object_.name_);
  86. }
  87. object_.name_ = 0;
  88. linkerOutput_.Clear();
  89. shaderParameters_.Clear();
  90. vertexAttributes_.Clear();
  91. usedVertexAttributes_ = 0;
  92. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  93. useTextureUnit_[i] = false;
  94. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  95. constantBuffers_[i].Reset();
  96. }
  97. }
  98. bool ShaderProgram::Link()
  99. {
  100. Release();
  101. if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObjectName() || !pixelShader_->GetGPUObjectName())
  102. return false;
  103. object_.name_ = glCreateProgram();
  104. if (!object_.name_)
  105. {
  106. linkerOutput_ = "Could not create shader program";
  107. return false;
  108. }
  109. glAttachShader(object_.name_, vertexShader_->GetGPUObjectName());
  110. glAttachShader(object_.name_, pixelShader_->GetGPUObjectName());
  111. glLinkProgram(object_.name_);
  112. int linked, length;
  113. glGetProgramiv(object_.name_, GL_LINK_STATUS, &linked);
  114. if (!linked)
  115. {
  116. glGetProgramiv(object_.name_, GL_INFO_LOG_LENGTH, &length);
  117. linkerOutput_.Resize((unsigned)length);
  118. int outLength;
  119. glGetProgramInfoLog(object_.name_, length, &outLength, &linkerOutput_[0]);
  120. glDeleteProgram(object_.name_);
  121. object_.name_ = 0;
  122. }
  123. else
  124. linkerOutput_.Clear();
  125. if (!object_.name_)
  126. return false;
  127. const int MAX_NAME_LENGTH = 256;
  128. char nameBuffer[MAX_NAME_LENGTH];
  129. int attributeCount, uniformCount, elementCount, nameLength;
  130. GLenum type;
  131. glUseProgram(object_.name_);
  132. // Check for vertex attributes
  133. glGetProgramiv(object_.name_, GL_ACTIVE_ATTRIBUTES, &attributeCount);
  134. for (int i = 0; i < attributeCount; ++i)
  135. {
  136. glGetActiveAttrib(object_.name_, i, (GLsizei)MAX_NAME_LENGTH, &nameLength, &elementCount, &type, nameBuffer);
  137. String name = String(nameBuffer, nameLength);
  138. VertexElementSemantic semantic = MAX_VERTEX_ELEMENT_SEMANTICS;
  139. unsigned char semanticIndex = 0;
  140. // Go in reverse order so that "binormal" is detected before "normal"
  141. for (unsigned j = MAX_VERTEX_ELEMENT_SEMANTICS - 1; j < MAX_VERTEX_ELEMENT_SEMANTICS; --j)
  142. {
  143. if (name.Contains(ShaderVariation::elementSemanticNames[j], false))
  144. {
  145. semantic = (VertexElementSemantic)j;
  146. unsigned index = NumberPostfix(name);
  147. if (index != M_MAX_UNSIGNED)
  148. semanticIndex = (unsigned char)index;
  149. break;
  150. }
  151. }
  152. if (semantic == MAX_VERTEX_ELEMENT_SEMANTICS)
  153. {
  154. URHO3D_LOGWARNING("Found vertex attribute " + name + " with no known semantic in shader program " +
  155. vertexShader_->GetFullName() + " " + pixelShader_->GetFullName());
  156. continue;
  157. }
  158. int location = glGetAttribLocation(object_.name_, name.CString());
  159. vertexAttributes_[MakePair((unsigned char)semantic, semanticIndex)] = location;
  160. usedVertexAttributes_ |= (1 << location);
  161. }
  162. // Check for constant buffers
  163. #ifndef GL_ES_VERSION_2_0
  164. HashMap<unsigned, unsigned> blockToBinding;
  165. if (Graphics::GetGL3Support())
  166. {
  167. int numUniformBlocks = 0;
  168. glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
  169. for (int i = 0; i < numUniformBlocks; ++i)
  170. {
  171. glGetActiveUniformBlockName(object_.name_, (GLuint)i, MAX_NAME_LENGTH, &nameLength, nameBuffer);
  172. String name(nameBuffer, (unsigned)nameLength);
  173. unsigned blockIndex = glGetUniformBlockIndex(object_.name_, name.CString());
  174. unsigned group = M_MAX_UNSIGNED;
  175. // Try to recognize the use of the buffer from its name
  176. for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
  177. {
  178. if (name.Contains(shaderParameterGroups[j], false))
  179. {
  180. group = j;
  181. break;
  182. }
  183. }
  184. // If name is not recognized, search for a digit in the name and use that as the group index
  185. if (group == M_MAX_UNSIGNED)
  186. group = NumberPostfix(name);
  187. if (group >= MAX_SHADER_PARAMETER_GROUPS)
  188. {
  189. URHO3D_LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
  190. " " + pixelShader_->GetFullName());
  191. continue;
  192. }
  193. // Find total constant buffer data size
  194. int dataSize;
  195. glGetActiveUniformBlockiv(object_.name_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
  196. if (!dataSize)
  197. continue;
  198. unsigned bindingIndex = group;
  199. // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
  200. // from that point onward
  201. ShaderType shaderType = VS;
  202. if (name.Contains("PS", false))
  203. {
  204. bindingIndex += MAX_SHADER_PARAMETER_GROUPS;
  205. shaderType = PS;
  206. }
  207. glUniformBlockBinding(object_.name_, blockIndex, bindingIndex);
  208. blockToBinding[blockIndex] = bindingIndex;
  209. constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(shaderType, bindingIndex, (unsigned)dataSize);
  210. }
  211. }
  212. #endif
  213. // Check for shader parameters and texture units
  214. glGetProgramiv(object_.name_, GL_ACTIVE_UNIFORMS, &uniformCount);
  215. for (int i = 0; i < uniformCount; ++i)
  216. {
  217. glGetActiveUniform(object_.name_, (GLuint)i, MAX_NAME_LENGTH, 0, &elementCount, &type, nameBuffer);
  218. int location = glGetUniformLocation(object_.name_, nameBuffer);
  219. // Check for array index included in the name and strip it
  220. String name(nameBuffer);
  221. unsigned index = name.Find('[');
  222. if (index != String::NPOS)
  223. {
  224. // If not the first index, skip
  225. if (name.Find("[0]", index) == String::NPOS)
  226. continue;
  227. name = name.Substring(0, index);
  228. }
  229. if (name[0] == 'c')
  230. {
  231. // Store constant uniform
  232. String paramName = name.Substring(1);
  233. ShaderParameter parameter;
  234. parameter.name_ = paramName;
  235. parameter.glType_ = type;
  236. parameter.location_ = location;
  237. bool store = location >= 0;
  238. #ifndef GL_ES_VERSION_2_0
  239. // If running OpenGL 3, the uniform may be inside a constant buffer
  240. if (parameter.location_ < 0 && Graphics::GetGL3Support())
  241. {
  242. int blockIndex, blockOffset;
  243. glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
  244. glGetActiveUniformsiv(object_.name_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
  245. if (blockIndex >= 0)
  246. {
  247. parameter.offset_ = blockOffset;
  248. parameter.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]];
  249. store = true;
  250. }
  251. }
  252. #endif
  253. if (store)
  254. shaderParameters_[StringHash(paramName)] = parameter;
  255. }
  256. else if (location >= 0 && name[0] == 's')
  257. {
  258. // Set the samplers here so that they do not have to be set later
  259. unsigned unit = graphics_->GetTextureUnit(name.Substring(1));
  260. if (unit >= MAX_TEXTURE_UNITS)
  261. unit = NumberPostfix(name);
  262. if (unit < MAX_TEXTURE_UNITS)
  263. {
  264. useTextureUnit_[unit] = true;
  265. glUniform1iv(location, 1, reinterpret_cast<int*>(&unit));
  266. }
  267. }
  268. }
  269. // Rehash the parameter & vertex attributes maps to ensure minimal load factor
  270. vertexAttributes_.Rehash(NextPowerOfTwo(vertexAttributes_.Size()));
  271. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  272. return true;
  273. }
  274. ShaderVariation* ShaderProgram::GetVertexShader() const
  275. {
  276. return vertexShader_;
  277. }
  278. ShaderVariation* ShaderProgram::GetPixelShader() const
  279. {
  280. return pixelShader_;
  281. }
  282. bool ShaderProgram::HasParameter(StringHash param) const
  283. {
  284. return shaderParameters_.Find(param) != shaderParameters_.End();
  285. }
  286. const ShaderParameter* ShaderProgram::GetParameter(StringHash param) const
  287. {
  288. HashMap<StringHash, ShaderParameter>::ConstIterator i = shaderParameters_.Find(param);
  289. if (i != shaderParameters_.End())
  290. return &i->second_;
  291. else
  292. return 0;
  293. }
  294. bool ShaderProgram::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  295. {
  296. // If global framenumber has changed, invalidate all per-program parameter sources now
  297. if (globalFrameNumber != frameNumber_)
  298. {
  299. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  300. parameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  301. frameNumber_ = globalFrameNumber;
  302. }
  303. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  304. #ifndef GL_ES_VERSION_2_0
  305. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  306. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  307. bool needUpdate = false;
  308. if (useBuffer && globalParameterSources[group] != source)
  309. {
  310. globalParameterSources[group] = source;
  311. needUpdate = true;
  312. }
  313. if (useIndividual && parameterSources_[group] != source)
  314. {
  315. parameterSources_[group] = source;
  316. needUpdate = true;
  317. }
  318. return needUpdate;
  319. #else
  320. if (parameterSources_[group] != source)
  321. {
  322. parameterSources_[group] = source;
  323. return true;
  324. }
  325. else
  326. return false;
  327. #endif
  328. }
  329. void ShaderProgram::ClearParameterSource(ShaderParameterGroup group)
  330. {
  331. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  332. #ifndef GL_ES_VERSION_2_0
  333. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  334. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  335. if (useBuffer)
  336. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  337. if (useIndividual)
  338. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  339. #else
  340. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  341. #endif
  342. }
  343. void ShaderProgram::ClearParameterSources()
  344. {
  345. ++globalFrameNumber;
  346. if (!globalFrameNumber)
  347. ++globalFrameNumber;
  348. #ifndef GL_ES_VERSION_2_0
  349. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  350. globalParameterSources[i] = (const void*)M_MAX_UNSIGNED;
  351. #endif
  352. }
  353. void ShaderProgram::ClearGlobalParameterSource(ShaderParameterGroup group)
  354. {
  355. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  356. }
  357. }