OGLShaderProgram.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. ShaderProgram::ShaderProgram(Graphics* graphics, ShaderVariation* vertexShader, ShaderVariation* pixelShader) :
  41. GPUObject(graphics),
  42. vertexShader_(vertexShader),
  43. pixelShader_(pixelShader),
  44. individualUniforms_(false)
  45. {
  46. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  47. useTextureUnit_[i] = false;
  48. }
  49. ShaderProgram::~ShaderProgram()
  50. {
  51. Release();
  52. }
  53. void ShaderProgram::OnDeviceLost()
  54. {
  55. GPUObject::OnDeviceLost();
  56. if (graphics_ && graphics_->GetShaderProgram() == this)
  57. graphics_->SetShaders(0, 0);
  58. linkerOutput_.Clear();
  59. }
  60. void ShaderProgram::Release()
  61. {
  62. if (object_)
  63. {
  64. if (!graphics_)
  65. return;
  66. if (!graphics_->IsDeviceLost())
  67. {
  68. if (graphics_->GetShaderProgram() == this)
  69. graphics_->SetShaders(0, 0);
  70. glDeleteProgram(object_);
  71. }
  72. object_ = 0;
  73. linkerOutput_.Clear();
  74. shaderParameters_.Clear();
  75. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  76. useTextureUnit_[i] = false;
  77. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  78. constantBuffers_[i].Reset();
  79. individualUniforms_ = false;
  80. }
  81. }
  82. bool ShaderProgram::Link()
  83. {
  84. Release();
  85. if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObject() || !pixelShader_->GetGPUObject())
  86. return false;
  87. object_ = glCreateProgram();
  88. if (!object_)
  89. {
  90. linkerOutput_ = "Could not create shader program";
  91. return false;
  92. }
  93. // Bind vertex attribute locations to ensure they are the same in all shaders
  94. // Note: this is not the same order as in VertexBuffer, instead a remapping is used to ensure everything except cube texture
  95. // coordinates fit to the first 8 for better GLES2 device compatibility
  96. glBindAttribLocation(object_, 0, "iPos");
  97. glBindAttribLocation(object_, 1, "iNormal");
  98. glBindAttribLocation(object_, 2, "iColor");
  99. glBindAttribLocation(object_, 3, "iTexCoord");
  100. glBindAttribLocation(object_, 4, "iTexCoord2");
  101. glBindAttribLocation(object_, 5, "iTangent");
  102. glBindAttribLocation(object_, 6, "iBlendWeights");
  103. glBindAttribLocation(object_, 7, "iBlendIndices");
  104. glBindAttribLocation(object_, 8, "iCubeTexCoord");
  105. glBindAttribLocation(object_, 9, "iCubeTexCoord2");
  106. #ifndef GL_ES_VERSION_2_0
  107. glBindAttribLocation(object_, 10, "iInstanceMatrix1");
  108. glBindAttribLocation(object_, 11, "iInstanceMatrix2");
  109. glBindAttribLocation(object_, 12, "iInstanceMatrix3");
  110. #endif
  111. glAttachShader(object_, vertexShader_->GetGPUObject());
  112. glAttachShader(object_, pixelShader_->GetGPUObject());
  113. glLinkProgram(object_);
  114. int linked, length;
  115. glGetProgramiv(object_, GL_LINK_STATUS, &linked);
  116. if (!linked)
  117. {
  118. glGetProgramiv(object_, GL_INFO_LOG_LENGTH, &length);
  119. linkerOutput_.Resize(length);
  120. int outLength;
  121. glGetProgramInfoLog(object_, length, &outLength, &linkerOutput_[0]);
  122. glDeleteProgram(object_);
  123. object_ = 0;
  124. }
  125. else
  126. linkerOutput_.Clear();
  127. if (!object_)
  128. return false;
  129. const int MAX_PARAMETER_NAME_LENGTH = 256;
  130. char uniformName[MAX_PARAMETER_NAME_LENGTH];
  131. int uniformCount;
  132. glUseProgram(object_);
  133. glGetProgramiv(object_, GL_ACTIVE_UNIFORMS, &uniformCount);
  134. // Check for constant buffers
  135. #ifndef GL_ES_VERSION_2_0
  136. HashMap<unsigned, unsigned> blockToBinding;
  137. if (Graphics::GetGL3Support())
  138. {
  139. int numUniformBlocks = 0;
  140. glGetProgramiv(object_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
  141. for (int i = 0; i < numUniformBlocks; ++i)
  142. {
  143. int nameLength;
  144. glGetActiveUniformBlockName(object_, i, MAX_PARAMETER_NAME_LENGTH, &nameLength, uniformName);
  145. String name(uniformName, nameLength);
  146. unsigned blockIndex = glGetUniformBlockIndex(object_, name.CString());
  147. unsigned group = M_MAX_UNSIGNED;
  148. // Try to recognize the use of the buffer from its name
  149. for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
  150. {
  151. if (name.Contains(shaderParameterGroups[j], false))
  152. {
  153. group = j;
  154. break;
  155. }
  156. }
  157. // If name is not recognized, search for a digit in the name and use that as the group index
  158. if (group == M_MAX_UNSIGNED)
  159. {
  160. for (unsigned j = 1; j < name.Length(); ++j)
  161. {
  162. if (name[j] >= '0' && name[j] <= '5')
  163. {
  164. group = name[j] - '0';
  165. break;
  166. }
  167. }
  168. }
  169. if (group >= MAX_SHADER_PARAMETER_GROUPS)
  170. {
  171. LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
  172. " " + pixelShader_->GetFullName());
  173. continue;
  174. }
  175. // Find total constant buffer data size
  176. int dataSize;
  177. glGetActiveUniformBlockiv(object_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
  178. if (!dataSize)
  179. continue;
  180. unsigned bindingIndex = group;
  181. // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
  182. // from that point onward
  183. if (name.Contains("PS", false))
  184. bindingIndex += MAX_SHADER_PARAMETER_GROUPS;
  185. glUniformBlockBinding(object_, blockIndex, bindingIndex);
  186. blockToBinding[blockIndex] = bindingIndex;
  187. constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(bindingIndex, dataSize);
  188. }
  189. }
  190. #endif
  191. // Check for shader parameters and texture units
  192. individualUniforms_ = false;
  193. for (int i = 0; i < uniformCount; ++i)
  194. {
  195. unsigned type;
  196. int count;
  197. glGetActiveUniform(object_, i, MAX_PARAMETER_NAME_LENGTH, 0, &count, &type, uniformName);
  198. int location = glGetUniformLocation(object_, uniformName);
  199. // Check for array index included in the name and strip it
  200. String name(uniformName);
  201. unsigned index = name.Find('[');
  202. if (index != String::NPOS)
  203. {
  204. // If not the first index, skip
  205. if (name.Find("[0]", index) == String::NPOS)
  206. continue;
  207. name = name.Substring(0, index);
  208. }
  209. if (name[0] == 'c')
  210. {
  211. // Store constant uniform
  212. String paramName = name.Substring(1);
  213. ShaderParameter newParam;
  214. newParam.type_ = type;
  215. newParam.location_ = location;
  216. #ifndef GL_ES_VERSION_2_0
  217. // If running OpenGL 3, the uniform may be inside a constant buffer
  218. if (newParam.location_ < 0 && Graphics::GetGL3Support())
  219. {
  220. int blockIndex, blockOffset;
  221. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
  222. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
  223. if (blockIndex >= 0)
  224. {
  225. newParam.location_ = blockOffset;
  226. newParam.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]];
  227. }
  228. }
  229. #endif
  230. if (!newParam.bufferPtr_)
  231. individualUniforms_ = true;
  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. }