OGLShaderProgram.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. //
  2. // Copyright (c) 2008-2015 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 "../../Graphics/ConstantBuffer.h"
  23. #include "../../Graphics/Graphics.h"
  24. #include "../../Graphics/GraphicsImpl.h"
  25. #include "../../Graphics/ShaderProgram.h"
  26. #include "../../Graphics/ShaderVariation.h"
  27. #include "../../IO/Log.h"
  28. #include "../../DebugNew.h"
  29. namespace Urho3D
  30. {
  31. const char* shaderParameterGroups[] = {
  32. "frame",
  33. "camera",
  34. "zone",
  35. "light",
  36. "material",
  37. "object",
  38. "custom"
  39. };
  40. unsigned ShaderProgram::globalFrameNumber = 0;
  41. const void* ShaderProgram::globalParameterSources[MAX_SHADER_PARAMETER_GROUPS];
  42. ShaderProgram::ShaderProgram(Graphics* graphics, ShaderVariation* vertexShader, ShaderVariation* pixelShader) :
  43. GPUObject(graphics),
  44. vertexShader_(vertexShader),
  45. pixelShader_(pixelShader),
  46. frameNumber_(0)
  47. {
  48. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  49. useTextureUnit_[i] = false;
  50. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  51. parameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  52. }
  53. ShaderProgram::~ShaderProgram()
  54. {
  55. Release();
  56. }
  57. void ShaderProgram::OnDeviceLost()
  58. {
  59. GPUObject::OnDeviceLost();
  60. if (graphics_ && graphics_->GetShaderProgram() == this)
  61. graphics_->SetShaders(0, 0);
  62. linkerOutput_.Clear();
  63. }
  64. void ShaderProgram::Release()
  65. {
  66. if (object_)
  67. {
  68. if (!graphics_)
  69. return;
  70. if (!graphics_->IsDeviceLost())
  71. {
  72. if (graphics_->GetShaderProgram() == this)
  73. graphics_->SetShaders(0, 0);
  74. glDeleteProgram(object_);
  75. }
  76. object_ = 0;
  77. linkerOutput_.Clear();
  78. shaderParameters_.Clear();
  79. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  80. useTextureUnit_[i] = false;
  81. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  82. constantBuffers_[i].Reset();
  83. }
  84. }
  85. bool ShaderProgram::Link()
  86. {
  87. Release();
  88. if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObject() || !pixelShader_->GetGPUObject())
  89. return false;
  90. object_ = glCreateProgram();
  91. if (!object_)
  92. {
  93. linkerOutput_ = "Could not create shader program";
  94. return false;
  95. }
  96. // Bind vertex attribute locations to ensure they are the same in all shaders
  97. // Note: this is not the same order as in VertexBuffer, instead a remapping is used to ensure everything except cube texture
  98. // coordinates fit to the first 8 for better GLES2 device compatibility
  99. glBindAttribLocation(object_, 0, "iPos");
  100. glBindAttribLocation(object_, 1, "iNormal");
  101. glBindAttribLocation(object_, 2, "iColor");
  102. glBindAttribLocation(object_, 3, "iTexCoord");
  103. glBindAttribLocation(object_, 4, "iTexCoord2");
  104. glBindAttribLocation(object_, 5, "iTangent");
  105. glBindAttribLocation(object_, 6, "iBlendWeights");
  106. glBindAttribLocation(object_, 7, "iBlendIndices");
  107. glBindAttribLocation(object_, 8, "iCubeTexCoord");
  108. glBindAttribLocation(object_, 9, "iCubeTexCoord2");
  109. #ifndef GL_ES_VERSION_2_0
  110. glBindAttribLocation(object_, 10, "iInstanceMatrix1");
  111. glBindAttribLocation(object_, 11, "iInstanceMatrix2");
  112. glBindAttribLocation(object_, 12, "iInstanceMatrix3");
  113. #endif
  114. glAttachShader(object_, vertexShader_->GetGPUObject());
  115. glAttachShader(object_, pixelShader_->GetGPUObject());
  116. glLinkProgram(object_);
  117. int linked, length;
  118. glGetProgramiv(object_, GL_LINK_STATUS, &linked);
  119. if (!linked)
  120. {
  121. glGetProgramiv(object_, GL_INFO_LOG_LENGTH, &length);
  122. linkerOutput_.Resize(length);
  123. int outLength;
  124. glGetProgramInfoLog(object_, length, &outLength, &linkerOutput_[0]);
  125. glDeleteProgram(object_);
  126. object_ = 0;
  127. }
  128. else
  129. linkerOutput_.Clear();
  130. if (!object_)
  131. return false;
  132. const int MAX_PARAMETER_NAME_LENGTH = 256;
  133. char uniformName[MAX_PARAMETER_NAME_LENGTH];
  134. int uniformCount;
  135. glUseProgram(object_);
  136. glGetProgramiv(object_, GL_ACTIVE_UNIFORMS, &uniformCount);
  137. // Check for constant buffers
  138. #ifndef GL_ES_VERSION_2_0
  139. HashMap<unsigned, unsigned> blockToBinding;
  140. if (Graphics::GetGL3Support())
  141. {
  142. int numUniformBlocks = 0;
  143. glGetProgramiv(object_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
  144. for (int i = 0; i < numUniformBlocks; ++i)
  145. {
  146. int nameLength;
  147. glGetActiveUniformBlockName(object_, i, MAX_PARAMETER_NAME_LENGTH, &nameLength, uniformName);
  148. String name(uniformName, nameLength);
  149. unsigned blockIndex = glGetUniformBlockIndex(object_, name.CString());
  150. unsigned group = M_MAX_UNSIGNED;
  151. // Try to recognize the use of the buffer from its name
  152. for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
  153. {
  154. if (name.Contains(shaderParameterGroups[j], false))
  155. {
  156. group = j;
  157. break;
  158. }
  159. }
  160. // If name is not recognized, search for a digit in the name and use that as the group index
  161. if (group == M_MAX_UNSIGNED)
  162. {
  163. for (unsigned j = 1; j < name.Length(); ++j)
  164. {
  165. if (name[j] >= '0' && name[j] <= '5')
  166. {
  167. group = name[j] - '0';
  168. break;
  169. }
  170. }
  171. }
  172. if (group >= MAX_SHADER_PARAMETER_GROUPS)
  173. {
  174. LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
  175. " " + pixelShader_->GetFullName());
  176. continue;
  177. }
  178. // Find total constant buffer data size
  179. int dataSize;
  180. glGetActiveUniformBlockiv(object_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
  181. if (!dataSize)
  182. continue;
  183. unsigned bindingIndex = group;
  184. // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
  185. // from that point onward
  186. if (name.Contains("PS", false))
  187. bindingIndex += MAX_SHADER_PARAMETER_GROUPS;
  188. glUniformBlockBinding(object_, blockIndex, bindingIndex);
  189. blockToBinding[blockIndex] = bindingIndex;
  190. constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(bindingIndex, dataSize);
  191. }
  192. }
  193. #endif
  194. // Check for shader parameters and texture units
  195. for (int i = 0; i < uniformCount; ++i)
  196. {
  197. unsigned type;
  198. int count;
  199. glGetActiveUniform(object_, i, MAX_PARAMETER_NAME_LENGTH, 0, &count, &type, uniformName);
  200. int location = glGetUniformLocation(object_, uniformName);
  201. // Check for array index included in the name and strip it
  202. String name(uniformName);
  203. unsigned index = name.Find('[');
  204. if (index != String::NPOS)
  205. {
  206. // If not the first index, skip
  207. if (name.Find("[0]", index) == String::NPOS)
  208. continue;
  209. name = name.Substring(0, index);
  210. }
  211. if (name[0] == 'c')
  212. {
  213. // Store constant uniform
  214. String paramName = name.Substring(1);
  215. ShaderParameter newParam;
  216. newParam.type_ = type;
  217. newParam.location_ = location;
  218. #ifndef GL_ES_VERSION_2_0
  219. // If running OpenGL 3, the uniform may be inside a constant buffer
  220. if (newParam.location_ < 0 && Graphics::GetGL3Support())
  221. {
  222. int blockIndex, blockOffset;
  223. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
  224. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
  225. if (blockIndex >= 0)
  226. {
  227. newParam.location_ = blockOffset;
  228. newParam.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]];
  229. }
  230. }
  231. #endif
  232. if (newParam.location_ >= 0)
  233. shaderParameters_[StringHash(paramName)] = newParam;
  234. }
  235. else if (location >= 0 && name[0] == 's')
  236. {
  237. // Set the samplers here so that they do not have to be set later
  238. int unit = graphics_->GetTextureUnit(name.Substring(1));
  239. if (unit >= MAX_TEXTURE_UNITS)
  240. {
  241. // If texture unit name is not recognized, search for a digit in the name and use that as the unit index
  242. for (unsigned j = 1; j < name.Length(); ++j)
  243. {
  244. if (name[j] >= '0' && name[j] <= '9')
  245. {
  246. unit = name[j] - '0';
  247. break;
  248. }
  249. }
  250. }
  251. if (unit < MAX_TEXTURE_UNITS)
  252. {
  253. useTextureUnit_[unit] = true;
  254. glUniform1iv(location, 1, &unit);
  255. }
  256. }
  257. }
  258. // Rehash the parameter map to ensure minimal load factor
  259. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  260. return true;
  261. }
  262. ShaderVariation* ShaderProgram::GetVertexShader() const
  263. {
  264. return vertexShader_;
  265. }
  266. ShaderVariation* ShaderProgram::GetPixelShader() const
  267. {
  268. return pixelShader_;
  269. }
  270. bool ShaderProgram::HasParameter(StringHash param) const
  271. {
  272. return shaderParameters_.Find(param) != shaderParameters_.End();
  273. }
  274. const ShaderParameter* ShaderProgram::GetParameter(StringHash param) const
  275. {
  276. HashMap<StringHash, ShaderParameter>::ConstIterator i = shaderParameters_.Find(param);
  277. if (i != shaderParameters_.End())
  278. return &i->second_;
  279. else
  280. return 0;
  281. }
  282. bool ShaderProgram::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  283. {
  284. // If global framenumber has changed, invalidate all per-program parameter sources now
  285. if (globalFrameNumber != frameNumber_)
  286. {
  287. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  288. parameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  289. frameNumber_ = globalFrameNumber;
  290. }
  291. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  292. #ifndef GL_ES_VERSION_2_0
  293. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  294. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  295. bool needUpdate = false;
  296. if (useBuffer && globalParameterSources[group] != source)
  297. {
  298. globalParameterSources[group] = source;
  299. needUpdate = true;
  300. }
  301. if (useIndividual && parameterSources_[group] != source)
  302. {
  303. parameterSources_[group] = source;
  304. needUpdate = true;
  305. }
  306. return needUpdate;
  307. #else
  308. if (parameterSources_[group] != source)
  309. {
  310. parameterSources_[group] = source;
  311. return true;
  312. }
  313. else
  314. return false;
  315. #endif
  316. }
  317. void ShaderProgram::ClearParameterSource(ShaderParameterGroup group)
  318. {
  319. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  320. #ifndef GL_ES_VERSION_2_0
  321. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  322. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  323. if (useBuffer)
  324. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  325. if (useIndividual)
  326. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  327. #else
  328. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  329. #endif
  330. }
  331. void ShaderProgram::ClearParameterSources()
  332. {
  333. ++globalFrameNumber;
  334. if (!globalFrameNumber)
  335. ++globalFrameNumber;
  336. #ifndef GL_ES_VERSION_2_0
  337. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  338. globalParameterSources[i] = (const void*)M_MAX_UNSIGNED;
  339. #endif
  340. }
  341. void ShaderProgram::ClearGlobalParameterSource(ShaderParameterGroup group)
  342. {
  343. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  344. }
  345. }