ShaderProgramResource.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Resource/ShaderProgramResource.h>
  6. #include <AnKi/Resource/ResourceManager.h>
  7. #include <AnKi/Resource/ShaderProgramResourceSystem.h>
  8. #include <AnKi/Gr/ShaderProgram.h>
  9. #include <AnKi/Gr/GrManager.h>
  10. #include <AnKi/Util/Filesystem.h>
  11. #include <AnKi/Util/Functions.h>
  12. #include <AnKi/ShaderCompiler/MaliOfflineCompiler.h>
  13. namespace anki {
  14. ShaderProgramResourceVariant::ShaderProgramResourceVariant()
  15. {
  16. }
  17. ShaderProgramResourceVariant::~ShaderProgramResourceVariant()
  18. {
  19. }
  20. ShaderProgramResource::ShaderProgramResource(ResourceManager* manager)
  21. : ResourceObject(manager)
  22. , m_binary(getAllocator())
  23. {
  24. }
  25. ShaderProgramResource::~ShaderProgramResource()
  26. {
  27. m_mutators.destroy(getAllocator());
  28. for(ShaderProgramResourceConstant& c : m_consts)
  29. {
  30. c.m_name.destroy(getAllocator());
  31. }
  32. m_consts.destroy(getAllocator());
  33. m_constBinaryMapping.destroy(getAllocator());
  34. for(auto it : m_variants)
  35. {
  36. ShaderProgramResourceVariant* variant = &(*it);
  37. getAllocator().deleteInstance(variant);
  38. }
  39. m_variants.destroy(getAllocator());
  40. }
  41. Error ShaderProgramResource::load(const ResourceFilename& filename, Bool async)
  42. {
  43. // Load the binary from the cache. It should have been compiled there
  44. StringAuto baseFilename(getTempAllocator());
  45. getFilepathFilename(filename, baseFilename);
  46. StringAuto binaryFilename(getTempAllocator());
  47. binaryFilename.sprintf("%s/%sbin", getManager().getCacheDirectory().cstr(), baseFilename.cstr());
  48. ANKI_CHECK(m_binary.deserializeFromFile(binaryFilename));
  49. const ShaderProgramBinary& binary = m_binary.getBinary();
  50. // Create the mutators
  51. if(binary.m_mutators.getSize() > 0)
  52. {
  53. m_mutators.create(getAllocator(), binary.m_mutators.getSize());
  54. for(U32 i = 0; i < binary.m_mutators.getSize(); ++i)
  55. {
  56. m_mutators[i].m_name = binary.m_mutators[i].m_name.getBegin();
  57. ANKI_ASSERT(m_mutators[i].m_name.getLength() > 0);
  58. m_mutators[i].m_values = binary.m_mutators[i].m_values;
  59. }
  60. }
  61. // Create the constants
  62. for(const ShaderProgramBinaryConstant& c : binary.m_constants)
  63. {
  64. U32 componentIdx;
  65. U32 componentCount;
  66. CString name;
  67. ANKI_CHECK(parseConst(c.m_name.getBegin(), componentIdx, componentCount, name));
  68. // Do the mapping
  69. ConstMapping mapping;
  70. mapping.m_component = componentIdx;
  71. if(componentIdx > 0)
  72. {
  73. const ShaderProgramResourceConstant* other = tryFindConstant(name);
  74. ANKI_ASSERT(other);
  75. mapping.m_constsIdx = U32(other - m_consts.getBegin());
  76. }
  77. else
  78. {
  79. mapping.m_constsIdx = m_consts.getSize();
  80. }
  81. m_constBinaryMapping.emplaceBack(getAllocator(), mapping);
  82. // Skip if const is there
  83. if(componentIdx > 0)
  84. {
  85. continue;
  86. }
  87. // Create new one
  88. ShaderProgramResourceConstant& in = *m_consts.emplaceBack(getAllocator());
  89. in.m_name.create(getAllocator(), name);
  90. in.m_index = m_consts.getSize() - 1;
  91. if(componentCount == 1)
  92. {
  93. in.m_dataType = c.m_type;
  94. }
  95. else if(componentCount == 2)
  96. {
  97. if(c.m_type == ShaderVariableDataType::U32)
  98. {
  99. in.m_dataType = ShaderVariableDataType::UVEC2;
  100. }
  101. else if(c.m_type == ShaderVariableDataType::I32)
  102. {
  103. in.m_dataType = ShaderVariableDataType::IVEC2;
  104. }
  105. else
  106. {
  107. ANKI_ASSERT(c.m_type == ShaderVariableDataType::F32);
  108. in.m_dataType = ShaderVariableDataType::VEC2;
  109. }
  110. }
  111. else if(componentCount == 3)
  112. {
  113. if(c.m_type == ShaderVariableDataType::U32)
  114. {
  115. in.m_dataType = ShaderVariableDataType::UVEC3;
  116. }
  117. else if(c.m_type == ShaderVariableDataType::I32)
  118. {
  119. in.m_dataType = ShaderVariableDataType::IVEC3;
  120. }
  121. else
  122. {
  123. ANKI_ASSERT(c.m_type == ShaderVariableDataType::F32);
  124. in.m_dataType = ShaderVariableDataType::VEC3;
  125. }
  126. }
  127. else if(componentCount == 4)
  128. {
  129. if(c.m_type == ShaderVariableDataType::U32)
  130. {
  131. in.m_dataType = ShaderVariableDataType::UVEC4;
  132. }
  133. else if(c.m_type == ShaderVariableDataType::I32)
  134. {
  135. in.m_dataType = ShaderVariableDataType::IVEC4;
  136. }
  137. else
  138. {
  139. ANKI_ASSERT(c.m_type == ShaderVariableDataType::F32);
  140. in.m_dataType = ShaderVariableDataType::VEC4;
  141. }
  142. }
  143. else
  144. {
  145. ANKI_ASSERT(0);
  146. }
  147. }
  148. m_shaderStages = binary.m_presentShaderTypes;
  149. // Do some RT checks
  150. if(!!(m_shaderStages & ShaderTypeBit::ALL_RAY_TRACING))
  151. {
  152. if(m_shaderStages != (ShaderTypeBit::ANY_HIT | ShaderTypeBit::CLOSEST_HIT)
  153. && m_shaderStages != ShaderTypeBit::MISS && m_shaderStages != ShaderTypeBit::RAY_GEN)
  154. {
  155. ANKI_RESOURCE_LOGE("Any and closest hit shaders shouldn't coexist with other stages. Miss can't coexist "
  156. "with other stages. Raygen can't coexist with other stages as well");
  157. return Error::USER_DATA;
  158. }
  159. }
  160. return Error::NONE;
  161. }
  162. Error ShaderProgramResource::parseConst(CString constName, U32& componentIdx, U32& componentCount, CString& name)
  163. {
  164. const CString prefixName = "_anki_const_";
  165. const PtrSize prefix = constName.find(prefixName);
  166. if(prefix != 0)
  167. {
  168. // Simple name
  169. componentIdx = 0;
  170. componentCount = 1;
  171. name = constName;
  172. return Error::NONE;
  173. }
  174. Array<char, 2> number;
  175. number[0] = constName[prefixName.getLength()];
  176. number[1] = '\0';
  177. ANKI_CHECK(CString(number.getBegin()).toNumber(componentIdx));
  178. number[0] = constName[prefixName.getLength() + 2];
  179. ANKI_CHECK(CString(number.getBegin()).toNumber(componentCount));
  180. name = constName.getBegin() + prefixName.getLength() + 4;
  181. return Error::NONE;
  182. }
  183. void ShaderProgramResource::getOrCreateVariant(const ShaderProgramResourceVariantInitInfo& info,
  184. const ShaderProgramResourceVariant*& variant) const
  185. {
  186. // Sanity checks
  187. ANKI_ASSERT(info.m_setMutators.getEnabledBitCount() == m_mutators.getSize());
  188. ANKI_ASSERT(info.m_setConstants.getEnabledBitCount() == m_consts.getSize());
  189. // Compute variant hash
  190. U64 hash = 0;
  191. if(m_mutators.getSize())
  192. {
  193. hash = computeHash(info.m_mutation.getBegin(), m_mutators.getSize() * sizeof(info.m_mutation[0]));
  194. }
  195. if(m_consts.getSize())
  196. {
  197. hash =
  198. appendHash(info.m_constantValues.getBegin(), m_consts.getSize() * sizeof(info.m_constantValues[0]), hash);
  199. }
  200. // Check if the variant is in the cache
  201. {
  202. RLockGuard<RWMutex> lock(m_mtx);
  203. auto it = m_variants.find(hash);
  204. variant = (it != m_variants.getEnd()) ? *it : nullptr;
  205. if(variant != nullptr)
  206. {
  207. // Done
  208. return;
  209. }
  210. }
  211. // Create the variant
  212. WLockGuard<RWMutex> lock(m_mtx);
  213. // Check again
  214. auto it = m_variants.find(hash);
  215. variant = (it != m_variants.getEnd()) ? *it : nullptr;
  216. if(variant != nullptr)
  217. {
  218. // Done
  219. return;
  220. }
  221. // Create
  222. ShaderProgramResourceVariant* v = getAllocator().newInstance<ShaderProgramResourceVariant>();
  223. initVariant(info, *v);
  224. m_variants.emplace(getAllocator(), hash, v);
  225. variant = v;
  226. }
  227. void ShaderProgramResource::initVariant(const ShaderProgramResourceVariantInitInfo& info,
  228. ShaderProgramResourceVariant& variant) const
  229. {
  230. const ShaderProgramBinary& binary = m_binary.getBinary();
  231. // Get the binary program variant
  232. const ShaderProgramBinaryVariant* binaryVariant = nullptr;
  233. U64 mutationHash = 0;
  234. if(m_mutators.getSize())
  235. {
  236. // Create the mutation hash
  237. mutationHash = computeHash(info.m_mutation.getBegin(), m_mutators.getSize() * sizeof(info.m_mutation[0]));
  238. // Search for the mutation in the binary
  239. // TODO optimize the search
  240. for(const ShaderProgramBinaryMutation& mutation : binary.m_mutations)
  241. {
  242. if(mutation.m_hash == mutationHash)
  243. {
  244. binaryVariant = &binary.m_variants[mutation.m_variantIndex];
  245. break;
  246. }
  247. }
  248. }
  249. else
  250. {
  251. ANKI_ASSERT(binary.m_variants.getSize() == 1);
  252. binaryVariant = &binary.m_variants[0];
  253. }
  254. ANKI_ASSERT(binaryVariant);
  255. variant.m_binaryVariant = binaryVariant;
  256. // Set the constant values
  257. Array<ShaderSpecializationConstValue, 64> constValues;
  258. U32 constValueCount = 0;
  259. for(const ShaderProgramBinaryConstantInstance& instance : binaryVariant->m_constants)
  260. {
  261. const ShaderProgramBinaryConstant& c = binary.m_constants[instance.m_index];
  262. const U32 inputIdx = m_constBinaryMapping[instance.m_index].m_constsIdx;
  263. const U32 component = m_constBinaryMapping[instance.m_index].m_component;
  264. // Get value
  265. const ShaderProgramResourceConstantValue* value = nullptr;
  266. for(U32 i = 0; i < m_consts.getSize(); ++i)
  267. {
  268. if(info.m_constantValues[i].m_constantIndex == inputIdx)
  269. {
  270. value = &info.m_constantValues[i];
  271. break;
  272. }
  273. }
  274. ANKI_ASSERT(value && "Forgot to set the value of a constant");
  275. constValues[constValueCount].m_constantId = c.m_constantId;
  276. constValues[constValueCount].m_dataType = c.m_type;
  277. constValues[constValueCount].m_int = value->m_ivec4[component];
  278. ++constValueCount;
  279. }
  280. // Get the workgroup sizes
  281. if(!!(m_shaderStages & ShaderTypeBit::COMPUTE))
  282. {
  283. for(U32 i = 0; i < 3; ++i)
  284. {
  285. if(binaryVariant->m_workgroupSizes[i] != MAX_U32)
  286. {
  287. // Size didn't come from specialization const
  288. variant.m_workgroupSizes[i] = binaryVariant->m_workgroupSizes[i];
  289. }
  290. else
  291. {
  292. // Size is specialization const
  293. ANKI_ASSERT(binaryVariant->m_workgroupSizesConstants[i] != MAX_U32);
  294. const U32 binaryConstIdx = binaryVariant->m_workgroupSizesConstants[i];
  295. const U32 constIdx = m_constBinaryMapping[binaryConstIdx].m_constsIdx;
  296. const U32 component = m_constBinaryMapping[binaryConstIdx].m_component;
  297. const Const& c = m_consts[constIdx];
  298. (void)c;
  299. ANKI_ASSERT(c.m_dataType == ShaderVariableDataType::U32 || c.m_dataType == ShaderVariableDataType::UVEC2
  300. || c.m_dataType == ShaderVariableDataType::UVEC3
  301. || c.m_dataType == ShaderVariableDataType::UVEC4);
  302. // Find the value
  303. for(U32 i = 0; i < m_consts.getSize(); ++i)
  304. {
  305. if(info.m_constantValues[i].m_constantIndex == constIdx)
  306. {
  307. const I32 value = info.m_constantValues[i].m_ivec4[component];
  308. ANKI_ASSERT(value > 0);
  309. variant.m_workgroupSizes[i] = U32(value);
  310. break;
  311. }
  312. }
  313. }
  314. ANKI_ASSERT(variant.m_workgroupSizes[i] != MAX_U32);
  315. }
  316. }
  317. // Time to init the shaders
  318. if(!!(m_shaderStages & (ShaderTypeBit::ALL_GRAPHICS | ShaderTypeBit::COMPUTE)))
  319. {
  320. // Create the program name
  321. StringAuto progName(getTempAllocator());
  322. getFilepathFilename(getFilename(), progName);
  323. char* cprogName = const_cast<char*>(progName.cstr());
  324. if(progName.getLength() > MAX_GR_OBJECT_NAME_LENGTH)
  325. {
  326. cprogName[MAX_GR_OBJECT_NAME_LENGTH] = '\0';
  327. }
  328. ShaderProgramInitInfo progInf(cprogName);
  329. for(ShaderType shaderType : EnumIterable<ShaderType>())
  330. {
  331. if(!(ShaderTypeBit(1 << shaderType) & m_shaderStages))
  332. {
  333. continue;
  334. }
  335. ShaderInitInfo inf(cprogName);
  336. inf.m_shaderType = shaderType;
  337. inf.m_binary = binary.m_codeBlocks[binaryVariant->m_codeBlockIndices[shaderType]].m_binary;
  338. inf.m_constValues.setArray((constValueCount) ? constValues.getBegin() : nullptr, constValueCount);
  339. ShaderPtr shader = getManager().getGrManager().newShader(inf);
  340. if(true && (ANKI_OS_LINUX || ANKI_OS_WINDOWS))
  341. {
  342. MaliOfflineCompilerOut maliocOut;
  343. const Error err =
  344. runMaliOfflineCompiler(ANKI_SOURCE_DIRECTORY "/ThirdParty/Bin/MaliOfflineCompiler/malioc",
  345. binary.m_codeBlocks[binaryVariant->m_codeBlockIndices[shaderType]].m_binary,
  346. inf.m_shaderType, getAllocator(), maliocOut);
  347. if(!err)
  348. {
  349. StringAuto maliocOutStr(getAllocator());
  350. maliocOut.toString(maliocOutStr);
  351. ANKI_RESOURCE_LOGI("Mali offline compiler: %s: %s", cprogName, maliocOutStr.cstr());
  352. }
  353. }
  354. const ShaderTypeBit shaderBit = ShaderTypeBit(1 << shaderType);
  355. if(!!(shaderBit & ShaderTypeBit::ALL_GRAPHICS))
  356. {
  357. progInf.m_graphicsShaders[shaderType] = shader;
  358. }
  359. else if(shaderType == ShaderType::COMPUTE)
  360. {
  361. progInf.m_computeShader = shader;
  362. }
  363. else
  364. {
  365. ANKI_ASSERT(0);
  366. }
  367. }
  368. // Create the program
  369. variant.m_prog = getManager().getGrManager().newShaderProgram(progInf);
  370. }
  371. else
  372. {
  373. ANKI_ASSERT(!!(m_shaderStages & ShaderTypeBit::ALL_RAY_TRACING));
  374. // Find the library
  375. CString libName = &binary.m_libraryName[0];
  376. ANKI_ASSERT(libName.getLength() > 0);
  377. const ShaderProgramResourceSystem& progSystem = getManager().getShaderProgramResourceSystem();
  378. const ShaderProgramRaytracingLibrary* foundLib = nullptr;
  379. for(const ShaderProgramRaytracingLibrary& lib : progSystem.getRayTracingLibraries())
  380. {
  381. if(lib.getLibraryName() == libName)
  382. {
  383. foundLib = &lib;
  384. break;
  385. }
  386. }
  387. ANKI_ASSERT(foundLib);
  388. variant.m_prog = foundLib->getShaderProgram();
  389. // Set the group handle index
  390. variant.m_shaderGroupHandleIndex = foundLib->getShaderGroupHandleIndex(getFilename(), mutationHash);
  391. }
  392. }
  393. } // end namespace anki