BsGLSLParamParser.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. #include "BsGLSLParamParser.h"
  2. namespace BansheeEngine
  3. {
  4. INT32 GLSLAttribute::matchesName(const String& name)
  5. {
  6. if (name.length() >= mName.length())
  7. {
  8. if (name.substr(0, mName.length()) == mName)
  9. {
  10. String indexStr = name.substr(mName.length(), name.length());
  11. return parseUnsignedInt(indexStr, 0);
  12. }
  13. }
  14. return -1;
  15. }
  16. VertexDeclaration::VertexElementList GLSLParamParser::buildVertexDeclaration(GLuint glProgram)
  17. {
  18. GLint numAttributes = 0;
  19. glGetProgramiv(glProgram, GL_ACTIVE_ATTRIBUTES, &numAttributes);
  20. GLint maxNameSize = 0;
  21. glGetProgramiv(glProgram, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxNameSize);
  22. GLchar* attributeName = (GLchar*)bs_alloc<ScratchAlloc>(sizeof(GLchar)* maxNameSize);
  23. VertexDeclaration::VertexElementList elementList;
  24. for (GLint i = 0; i < numAttributes; i++)
  25. {
  26. GLint attribSize = 0;
  27. GLenum attribType = 0;
  28. glGetActiveAttrib(glProgram, i, maxNameSize, nullptr, &attribSize, &attribType, attributeName);
  29. VertexElementSemantic semantic = VES_POSITION;
  30. UINT16 index = 0;
  31. if (attribNameToElementSemantic(attributeName, semantic, index))
  32. {
  33. VertexElementType type = glTypeToAttributeType(attribType);
  34. elementList.push_back(VertexElement(0, i, type, semantic, index));
  35. }
  36. else
  37. {
  38. LOGWRN("Cannot determine vertex input attribute type for attribute: " + String(attributeName));
  39. }
  40. }
  41. bs_free<ScratchAlloc>(attributeName);
  42. return elementList;
  43. }
  44. VertexElementType GLSLParamParser::glTypeToAttributeType(GLenum glType)
  45. {
  46. switch (glType)
  47. {
  48. case GL_FLOAT:
  49. return VET_FLOAT1;
  50. case GL_FLOAT_VEC2:
  51. return VET_FLOAT2;
  52. case GL_FLOAT_VEC3:
  53. return VET_FLOAT3;
  54. case GL_FLOAT_VEC4:
  55. return VET_FLOAT4;
  56. default:
  57. BS_EXCEPT(NotImplementedException, "OpenGL render system currently only supports float parameters.");
  58. }
  59. }
  60. bool GLSLParamParser::attribNameToElementSemantic(const String& name, VertexElementSemantic& semantic, UINT16& index)
  61. {
  62. static GLSLAttribute attributes[] =
  63. {
  64. GLSLAttribute("bs_position", VES_POSITION),
  65. GLSLAttribute("bs_normal", VES_NORMAL),
  66. GLSLAttribute("bs_tangent", VES_TANGENT),
  67. GLSLAttribute("bs_bitangent", VES_BITANGENT),
  68. GLSLAttribute("bs_texcoord", VES_TEXCOORD),
  69. GLSLAttribute("bs_color", VES_COLOR),
  70. GLSLAttribute("bs_blendweights", VES_BLEND_WEIGHTS),
  71. GLSLAttribute("bs_blendindices", VES_BLEND_INDICES)
  72. };
  73. static const UINT32 numAttribs = sizeof(attributes) / sizeof(attributes[0]);
  74. for (UINT32 i = 0; i < numAttribs; i++)
  75. {
  76. INT32 attribIndex = attributes[i].matchesName(name);
  77. if (attribIndex != -1)
  78. {
  79. index = attribIndex;
  80. semantic = attributes[i].getSemantic();
  81. return true;
  82. }
  83. }
  84. return false;
  85. }
  86. void GLSLParamParser::buildUniformDescriptions(GLuint glProgram, GpuParamDesc& returnParamDesc)
  87. {
  88. // scan through the active uniforms and add them to the reference list
  89. GLint maxBufferSize = 0;
  90. glGetProgramiv(glProgram, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxBufferSize);
  91. GLint maxBlockNameBufferSize = 0;
  92. glGetProgramiv(glProgram, GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH, &maxBlockNameBufferSize);
  93. if (maxBlockNameBufferSize > maxBufferSize)
  94. maxBufferSize = maxBlockNameBufferSize;
  95. GLchar* uniformName = (GLchar*)bs_alloc<ScratchAlloc>(sizeof(GLchar)* maxBufferSize);
  96. GpuParamBlockDesc newGlobalBlockDesc;
  97. newGlobalBlockDesc.slot = 0;
  98. newGlobalBlockDesc.name = "BS_INTERNAL_Globals";
  99. newGlobalBlockDesc.blockSize = 0;
  100. newGlobalBlockDesc.isShareable = false;
  101. UINT32 textureSlot = 0;
  102. returnParamDesc.paramBlocks[newGlobalBlockDesc.name] = newGlobalBlockDesc;
  103. GpuParamBlockDesc& globalBlockDesc = returnParamDesc.paramBlocks[newGlobalBlockDesc.name];
  104. GLint uniformBlockCount = 0;
  105. glGetProgramiv(glProgram, GL_ACTIVE_UNIFORM_BLOCKS, &uniformBlockCount);
  106. Map<UINT32, String> blockSlotToName;
  107. Set<String> blockNames;
  108. for (GLuint index = 0; index < (GLuint)uniformBlockCount; index++)
  109. {
  110. GLsizei unusedSize = 0;
  111. glGetActiveUniformBlockName(glProgram, index, maxBufferSize, &unusedSize, uniformName);
  112. GpuParamBlockDesc newBlockDesc;
  113. newBlockDesc.slot = index + 1;
  114. newBlockDesc.name = uniformName;
  115. newBlockDesc.blockSize = 0;
  116. newBlockDesc.isShareable = true;
  117. returnParamDesc.paramBlocks[newBlockDesc.name] = newBlockDesc;
  118. blockSlotToName.insert(std::make_pair(newBlockDesc.slot, newBlockDesc.name));
  119. blockNames.insert(newBlockDesc.name);
  120. }
  121. Map<String, UINT32> foundFirstArrayIndex;
  122. Map<String, GpuParamDataDesc> foundStructs;
  123. // get the number of active uniforms
  124. GLint uniformCount = 0;
  125. glGetProgramiv(glProgram, GL_ACTIVE_UNIFORMS, &uniformCount);
  126. // Loop over each of the active uniforms, and add them to the reference container
  127. // only do this for user defined uniforms, ignore built in gl state uniforms
  128. for (GLuint index = 0; index < (GLuint)uniformCount; index++)
  129. {
  130. GLsizei arraySize = 0;
  131. glGetActiveUniformName(glProgram, index, maxBufferSize, &arraySize, uniformName);
  132. String paramName = String(uniformName);
  133. // Naming rules and packing rules used here are described in
  134. // OpenGL Core Specification 2.11.4
  135. // Check if parameter is a part of a struct
  136. Vector<String> nameElements = StringUtil::tokenise(paramName, ".");
  137. bool inStruct = false;
  138. String structName;
  139. if (nameElements.size() > 1)
  140. {
  141. auto uniformBlockFind = blockNames.find(nameElements[0]);
  142. // Check if the name is not a struct, and instead a Uniform block namespace
  143. if (uniformBlockFind != blockNames.end())
  144. {
  145. // Possibly it's a struct inside a named uniform block
  146. if (nameElements.size() > 2)
  147. {
  148. inStruct = true;
  149. structName = nameElements[1];
  150. }
  151. }
  152. else
  153. {
  154. inStruct = true;
  155. structName = nameElements[0];
  156. }
  157. }
  158. String cleanParamName = paramName; // Param name without array indexes
  159. // Check if the parameter is in an array
  160. UINT32 arrayIdx = 0;
  161. bool isInArray = false;
  162. if (inStruct)
  163. {
  164. // If the uniform name has a "[" in it then its an array element uniform.
  165. String::size_type arrayStart = structName.find("[");
  166. String::size_type arrayEnd = structName.find("]");
  167. if (arrayStart != String::npos)
  168. {
  169. String strArrIdx = structName.substr(arrayStart + 1, arrayEnd - (arrayStart + 1));
  170. arrayIdx = parseUnsignedInt(strArrIdx, 0);
  171. isInArray = true;
  172. structName = structName.substr(0, arrayStart);
  173. }
  174. }
  175. else
  176. {
  177. // If the uniform name has a "[" in it then its an array element uniform.
  178. String::size_type arrayStart = cleanParamName.find("[");
  179. String::size_type arrayEnd = cleanParamName.find("]");
  180. if (arrayStart != String::npos)
  181. {
  182. String strArrIdx = cleanParamName.substr(arrayStart + 1, arrayEnd - (arrayStart + 1));
  183. arrayIdx = parseUnsignedInt(strArrIdx, 0);
  184. isInArray = true;
  185. cleanParamName = cleanParamName.substr(0, arrayStart);
  186. }
  187. }
  188. if (inStruct)
  189. {
  190. // OpenGL makes struct management really difficult, which is why I have given up on implementing this so far
  191. // Some of the issues I encountered:
  192. // - Elements will be optimized out if they are not used. This makes it hard to determine proper structure size.
  193. // - If struct is within a Uniform buffer block, then it is possible because the element won't be optimized out of the buffer
  194. // - If the struct is within a global buffer, it is impossible to determine actual size, since the element will be optimized out of the buffer too
  195. // - Same issue happens with arrays, as OpenGL will optimize out array elements. With global buffers this makes it impossible to determine
  196. // actual array size (e.g. suppose OpenGL optimized out few last elements)
  197. // - Normal arrays work fine as OpenGL has utilities for reporting their actual size, but those do not work with structs
  198. BS_EXCEPT(NotImplementedException, "Structs are not supported.")
  199. }
  200. // GLSL will optimize out unused array indexes, so there's no guarantee that 0 is the first,
  201. // so we store the first one here
  202. int firstArrayIndex = 0;
  203. if (isInArray)
  204. {
  205. String& nameToSearch = cleanParamName;
  206. if (inStruct)
  207. nameToSearch = structName;
  208. auto arrayIndexFind = foundFirstArrayIndex.find(nameToSearch);
  209. if (arrayIndexFind == foundFirstArrayIndex.end())
  210. {
  211. foundFirstArrayIndex[nameToSearch] = arrayIdx;
  212. }
  213. firstArrayIndex = foundFirstArrayIndex[nameToSearch];
  214. }
  215. GLint uniformType;
  216. glGetActiveUniformsiv(glProgram, 1, &index, GL_UNIFORM_TYPE, &uniformType);
  217. bool isSampler = false;
  218. switch (uniformType)
  219. {
  220. case GL_SAMPLER_1D:
  221. case GL_SAMPLER_2D:
  222. case GL_SAMPLER_3D:
  223. case GL_SAMPLER_CUBE:
  224. isSampler = true;
  225. }
  226. if (isSampler)
  227. {
  228. GpuParamObjectDesc samplerParam;
  229. samplerParam.name = paramName;
  230. samplerParam.slot = glGetUniformLocation(glProgram, uniformName);
  231. GpuParamObjectDesc textureParam;
  232. textureParam.name = paramName;
  233. textureParam.slot = samplerParam.slot;
  234. switch (uniformType)
  235. {
  236. case GL_SAMPLER_1D:
  237. samplerParam.type = GPOT_SAMPLER1D;
  238. textureParam.type = GPOT_TEXTURE1D;
  239. break;
  240. case GL_SAMPLER_2D:
  241. samplerParam.type = GPOT_SAMPLER2D;
  242. textureParam.type = GPOT_TEXTURE2D;
  243. break;
  244. case GL_SAMPLER_3D:
  245. samplerParam.type = GPOT_SAMPLER3D;
  246. textureParam.type = GPOT_TEXTURE3D;
  247. break;
  248. case GL_SAMPLER_CUBE:
  249. samplerParam.type = GPOT_SAMPLERCUBE;
  250. textureParam.type = GPOT_TEXTURECUBE;
  251. break;
  252. }
  253. returnParamDesc.samplers.insert(std::make_pair(paramName, samplerParam));
  254. returnParamDesc.textures.insert(std::make_pair(paramName, textureParam));
  255. }
  256. else
  257. {
  258. // If array index is larger than 0 and uniform is not a part of a struct,
  259. // it means we already processed it (struct arrays are processed differently)
  260. if (!inStruct && arrayIdx != 0)
  261. continue;
  262. GLint blockIndex;
  263. glGetActiveUniformsiv(glProgram, 1, &index, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
  264. GpuParamDataDesc gpuParam;
  265. if (isInArray)
  266. gpuParam.name = cleanParamName;
  267. else
  268. gpuParam.name = paramName;
  269. determineParamInfo(gpuParam, paramName, glProgram, index);
  270. if (blockIndex != -1)
  271. {
  272. GLint blockOffset;
  273. glGetActiveUniformsiv(glProgram, 1, &index, GL_UNIFORM_OFFSET, &blockOffset);
  274. blockOffset = blockOffset / 4;
  275. gpuParam.gpuMemOffset = blockOffset;
  276. gpuParam.paramBlockSlot = blockIndex + 1; // 0 is reserved for globals
  277. String& blockName = blockSlotToName[gpuParam.paramBlockSlot];
  278. GpuParamBlockDesc& curBlockDesc = returnParamDesc.paramBlocks[blockName];
  279. gpuParam.cpuMemOffset = blockOffset;
  280. curBlockDesc.blockSize = std::max(curBlockDesc.blockSize, gpuParam.cpuMemOffset + gpuParam.arrayElementStride * gpuParam.arraySize);
  281. }
  282. else
  283. {
  284. gpuParam.gpuMemOffset = glGetUniformLocation(glProgram, uniformName);
  285. gpuParam.paramBlockSlot = 0;
  286. gpuParam.cpuMemOffset = globalBlockDesc.blockSize;
  287. globalBlockDesc.blockSize = std::max(globalBlockDesc.blockSize, gpuParam.cpuMemOffset + gpuParam.arrayElementStride * gpuParam.arraySize);
  288. }
  289. // If parameter is not a part of a struct we're done
  290. if (!inStruct)
  291. {
  292. returnParamDesc.params.insert(std::make_pair(gpuParam.name, gpuParam));
  293. continue;
  294. }
  295. // If the parameter is part of a struct, then we need to update the struct definition
  296. auto findExistingStruct = foundStructs.find(structName);
  297. // Create new definition if one doesn't exist
  298. if (findExistingStruct == foundStructs.end())
  299. {
  300. foundStructs[structName] = GpuParamDataDesc();
  301. GpuParamDataDesc& structDesc = foundStructs[structName];
  302. structDesc.type = GPDT_STRUCT;
  303. structDesc.name = structName;
  304. structDesc.arraySize = 1;
  305. structDesc.elementSize = 0;
  306. structDesc.arrayElementStride = 0;
  307. structDesc.gpuMemOffset = gpuParam.gpuMemOffset;
  308. structDesc.cpuMemOffset = gpuParam.cpuMemOffset;
  309. structDesc.paramBlockSlot = gpuParam.paramBlockSlot;
  310. }
  311. // Update struct with size of the new parameter
  312. GpuParamDataDesc& structDesc = foundStructs[structName];
  313. assert(gpuParam.cpuMemOffset >= structDesc.cpuMemOffset);
  314. if (arrayIdx == firstArrayIndex) // Determine element size only using the first array element
  315. {
  316. structDesc.elementSize = std::max(structDesc.elementSize, (gpuParam.cpuMemOffset - structDesc.cpuMemOffset) + gpuParam.arrayElementStride * gpuParam.arraySize);
  317. structDesc.arrayElementStride = structDesc.elementSize;
  318. }
  319. // New array element reached, determine arrayElementStride
  320. if (arrayIdx != firstArrayIndex)
  321. {
  322. UINT32 numElements = arrayIdx - firstArrayIndex;
  323. structDesc.arrayElementStride = (gpuParam.cpuMemOffset - structDesc.cpuMemOffset) / numElements;
  324. }
  325. structDesc.arraySize = std::max(structDesc.arraySize, arrayIdx + 1);
  326. }
  327. }
  328. for (auto iter = foundStructs.begin(); iter != foundStructs.end(); ++iter)
  329. returnParamDesc.params.insert(std::make_pair(iter->first, iter->second));
  330. // Param blocks alway needs to be a multiple of 4, so make it so
  331. for (auto iter = returnParamDesc.paramBlocks.begin(); iter != returnParamDesc.paramBlocks.end(); ++iter)
  332. {
  333. GpuParamBlockDesc& blockDesc = iter->second;
  334. if (blockDesc.blockSize % 4 != 0)
  335. blockDesc.blockSize += (4 - (blockDesc.blockSize % 4));
  336. }
  337. #if BS_DEBUG_MODE
  338. // Check if manually calculated and OpenGL buffer sizes match
  339. for (auto iter = returnParamDesc.paramBlocks.begin(); iter != returnParamDesc.paramBlocks.end(); ++iter)
  340. {
  341. if (iter->second.slot == 0)
  342. continue;
  343. GLint blockSize = 0;
  344. glGetActiveUniformBlockiv(glProgram, iter->second.slot - 1, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize);
  345. assert(blockSize % 4 == 0);
  346. blockSize = blockSize / 4;
  347. if (iter->second.blockSize != blockSize)
  348. BS_EXCEPT(InternalErrorException, "OpenGL specified and manual uniform block buffer sizes don't match!");
  349. }
  350. #endif
  351. bs_free<ScratchAlloc>(uniformName);
  352. }
  353. void GLSLParamParser::determineParamInfo(GpuParamDataDesc& desc, const String& paramName, GLuint programHandle, GLuint uniformIndex)
  354. {
  355. GLint arraySize;
  356. glGetActiveUniformsiv(programHandle, 1, &uniformIndex, GL_UNIFORM_SIZE, &arraySize);
  357. desc.arraySize = arraySize;
  358. GLint uniformType;
  359. glGetActiveUniformsiv(programHandle, 1, &uniformIndex, GL_UNIFORM_TYPE, &uniformType);
  360. switch (uniformType)
  361. {
  362. case GL_BOOL:
  363. desc.type = GPDT_BOOL;
  364. desc.elementSize = 1;
  365. break;
  366. case GL_FLOAT:
  367. desc.type = GPDT_FLOAT1;
  368. desc.elementSize = 1;
  369. break;
  370. case GL_FLOAT_VEC2:
  371. desc.type = GPDT_FLOAT2;
  372. desc.elementSize = 2;
  373. break;
  374. case GL_FLOAT_VEC3:
  375. desc.type = GPDT_FLOAT3;
  376. desc.elementSize = 3;
  377. break;
  378. case GL_FLOAT_VEC4:
  379. desc.type = GPDT_FLOAT4;
  380. desc.elementSize = 4;
  381. break;
  382. case GL_INT:
  383. desc.type = GPDT_INT1;
  384. desc.elementSize = 1;
  385. break;
  386. case GL_INT_VEC2:
  387. desc.type = GPDT_INT2;
  388. desc.elementSize = 2;
  389. break;
  390. case GL_INT_VEC3:
  391. desc.type = GPDT_INT3;
  392. desc.elementSize = 3;
  393. break;
  394. case GL_INT_VEC4:
  395. desc.type = GPDT_INT4;
  396. desc.elementSize = 4;
  397. break;
  398. case GL_FLOAT_MAT2:
  399. desc.type = GPDT_MATRIX_2X2;
  400. desc.elementSize = 4;
  401. break;
  402. case GL_FLOAT_MAT3:
  403. desc.type = GPDT_MATRIX_3X3;
  404. desc.elementSize = 9;
  405. break;
  406. case GL_FLOAT_MAT4:
  407. desc.type = GPDT_MATRIX_4X4;
  408. desc.elementSize = 16;
  409. break;
  410. case GL_FLOAT_MAT2x3:
  411. desc.type = GPDT_MATRIX_2X3;
  412. desc.elementSize = 6;
  413. break;
  414. case GL_FLOAT_MAT3x2:
  415. desc.type = GPDT_MATRIX_3X2;
  416. desc.elementSize = 6;
  417. break;
  418. case GL_FLOAT_MAT2x4:
  419. desc.type = GPDT_MATRIX_2X4;
  420. desc.elementSize = 8;
  421. break;
  422. case GL_FLOAT_MAT4x2:
  423. desc.type = GPDT_MATRIX_4X2;
  424. desc.elementSize = 8;
  425. break;
  426. case GL_FLOAT_MAT3x4:
  427. desc.type = GPDT_MATRIX_3X4;
  428. desc.elementSize = 12;
  429. break;
  430. case GL_FLOAT_MAT4x3:
  431. desc.type = GPDT_MATRIX_4X3;
  432. desc.elementSize = 12;
  433. break;
  434. default:
  435. BS_EXCEPT(InternalErrorException, "Invalid shader parameter type: " + toString(uniformType) + " for parameter " + paramName);
  436. }
  437. if (arraySize > 1)
  438. {
  439. GLint arrayStride;
  440. glGetActiveUniformsiv(programHandle, 1, &uniformIndex, GL_UNIFORM_ARRAY_STRIDE, &arrayStride);
  441. if (arrayStride > 0)
  442. {
  443. assert(arrayStride % 4 == 0);
  444. desc.arrayElementStride = arrayStride / 4;
  445. }
  446. else
  447. desc.arrayElementStride = desc.elementSize;
  448. }
  449. else
  450. desc.arrayElementStride = desc.elementSize;
  451. }
  452. }