OGLShaderProgram.cpp 14 KB

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