ShaderProgramResource.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // Copyright (C) 2009-2020, 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. namespace anki
  13. {
  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)) != ShaderTypeBit::NONE)
  153. {
  154. ANKI_RESOURCE_LOGE("Any and closest hit shaders shouldn't coexist with other stages");
  155. return Error::USER_DATA;
  156. }
  157. if((m_shaderStages & ~(ShaderTypeBit::MISS | ShaderTypeBit::RAY_GEN)) != ShaderTypeBit::NONE)
  158. {
  159. ANKI_RESOURCE_LOGE("Miss and ray gen shaders shouldn't coexist with other stages");
  160. return Error::USER_DATA;
  161. }
  162. }
  163. return Error::NONE;
  164. }
  165. Error ShaderProgramResource::parseConst(CString constName, U32& componentIdx, U32& componentCount, CString& name)
  166. {
  167. const CString prefixName = "_anki_const_";
  168. const PtrSize prefix = constName.find(prefixName);
  169. if(prefix != 0)
  170. {
  171. // Simple name
  172. componentIdx = 0;
  173. componentCount = 1;
  174. name = constName;
  175. return Error::NONE;
  176. }
  177. Array<char, 2> number;
  178. number[0] = constName[prefixName.getLength()];
  179. number[1] = '\0';
  180. ANKI_CHECK(CString(number.getBegin()).toNumber(componentIdx));
  181. number[0] = constName[prefixName.getLength() + 2];
  182. ANKI_CHECK(CString(number.getBegin()).toNumber(componentCount));
  183. name = constName.getBegin() + prefixName.getLength() + 4;
  184. return Error::NONE;
  185. }
  186. void ShaderProgramResource::getOrCreateVariant(const ShaderProgramResourceVariantInitInfo& info,
  187. const ShaderProgramResourceVariant*& variant) const
  188. {
  189. // Sanity checks
  190. ANKI_ASSERT(info.m_setMutators.getEnabledBitCount() == m_mutators.getSize());
  191. ANKI_ASSERT(info.m_setConstants.getEnabledBitCount() == m_consts.getSize());
  192. // Compute variant hash
  193. U64 hash = 0;
  194. if(m_mutators.getSize())
  195. {
  196. hash = computeHash(info.m_mutation.getBegin(), m_mutators.getSize() * sizeof(info.m_mutation[0]));
  197. }
  198. if(m_consts.getSize())
  199. {
  200. hash =
  201. appendHash(info.m_constantValues.getBegin(), m_consts.getSize() * sizeof(info.m_constantValues[0]), hash);
  202. }
  203. // Check if the variant is in the cache
  204. {
  205. RLockGuard<RWMutex> lock(m_mtx);
  206. auto it = m_variants.find(hash);
  207. variant = (it != m_variants.getEnd()) ? *it : nullptr;
  208. if(variant != nullptr)
  209. {
  210. // Done
  211. return;
  212. }
  213. }
  214. // Create the variant
  215. WLockGuard<RWMutex> lock(m_mtx);
  216. // Check again
  217. auto it = m_variants.find(hash);
  218. variant = (it != m_variants.getEnd()) ? *it : nullptr;
  219. if(variant != nullptr)
  220. {
  221. // Done
  222. return;
  223. }
  224. // Create
  225. ShaderProgramResourceVariant* v = getAllocator().newInstance<ShaderProgramResourceVariant>();
  226. initVariant(info, *v);
  227. m_variants.emplace(getAllocator(), hash, v);
  228. variant = v;
  229. }
  230. void ShaderProgramResource::initVariant(const ShaderProgramResourceVariantInitInfo& info,
  231. ShaderProgramResourceVariant& variant) const
  232. {
  233. const ShaderProgramBinary& binary = m_binary.getBinary();
  234. // Get the binary program variant
  235. const ShaderProgramBinaryVariant* binaryVariant = nullptr;
  236. U64 mutationHash = 0;
  237. if(m_mutators.getSize())
  238. {
  239. // Create the mutation hash
  240. mutationHash = computeHash(info.m_mutation.getBegin(), m_mutators.getSize() * sizeof(info.m_mutation[0]));
  241. // Search for the mutation in the binary
  242. // TODO optimize the search
  243. for(const ShaderProgramBinaryMutation& mutation : binary.m_mutations)
  244. {
  245. if(mutation.m_hash == mutationHash)
  246. {
  247. binaryVariant = &binary.m_variants[mutation.m_variantIndex];
  248. break;
  249. }
  250. }
  251. }
  252. else
  253. {
  254. ANKI_ASSERT(binary.m_variants.getSize() == 1);
  255. binaryVariant = &binary.m_variants[0];
  256. }
  257. ANKI_ASSERT(binaryVariant);
  258. variant.m_binaryVariant = binaryVariant;
  259. // Set the constant values
  260. Array<ShaderSpecializationConstValue, 64> constValues;
  261. U32 constValueCount = 0;
  262. for(const ShaderProgramBinaryConstantInstance& instance : binaryVariant->m_constants)
  263. {
  264. const ShaderProgramBinaryConstant& c = binary.m_constants[instance.m_index];
  265. const U32 inputIdx = m_constBinaryMapping[instance.m_index].m_constsIdx;
  266. const U32 component = m_constBinaryMapping[instance.m_index].m_component;
  267. // Get value
  268. const ShaderProgramResourceConstantValue* value = nullptr;
  269. for(U32 i = 0; i < m_consts.getSize(); ++i)
  270. {
  271. if(info.m_constantValues[i].m_constantIndex == inputIdx)
  272. {
  273. value = &info.m_constantValues[i];
  274. break;
  275. }
  276. }
  277. ANKI_ASSERT(value && "Forgot to set the value of a constant");
  278. constValues[constValueCount].m_constantId = c.m_constantId;
  279. constValues[constValueCount].m_dataType = c.m_type;
  280. constValues[constValueCount].m_int = value->m_ivec4[component];
  281. ++constValueCount;
  282. }
  283. // Get the workgroup sizes
  284. if(!!(m_shaderStages & ShaderTypeBit::COMPUTE))
  285. {
  286. for(U32 i = 0; i < 3; ++i)
  287. {
  288. if(binaryVariant->m_workgroupSizes[i] != MAX_U32)
  289. {
  290. // Size didn't come from specialization const
  291. variant.m_workgroupSizes[i] = binaryVariant->m_workgroupSizes[i];
  292. }
  293. else
  294. {
  295. // Size is specialization const
  296. ANKI_ASSERT(binaryVariant->m_workgroupSizesConstants[i] != MAX_U32);
  297. const U32 binaryConstIdx = binaryVariant->m_workgroupSizesConstants[i];
  298. const U32 constIdx = m_constBinaryMapping[binaryConstIdx].m_constsIdx;
  299. const U32 component = m_constBinaryMapping[binaryConstIdx].m_component;
  300. const Const& c = m_consts[constIdx];
  301. (void)c;
  302. ANKI_ASSERT(c.m_dataType == ShaderVariableDataType::U32 || c.m_dataType == ShaderVariableDataType::UVEC2
  303. || c.m_dataType == ShaderVariableDataType::UVEC3
  304. || c.m_dataType == ShaderVariableDataType::UVEC4);
  305. // Find the value
  306. for(U32 i = 0; i < m_consts.getSize(); ++i)
  307. {
  308. if(info.m_constantValues[i].m_constantIndex == constIdx)
  309. {
  310. const I32 value = info.m_constantValues[i].m_ivec4[component];
  311. ANKI_ASSERT(value > 0);
  312. variant.m_workgroupSizes[i] = U32(value);
  313. break;
  314. }
  315. }
  316. }
  317. ANKI_ASSERT(variant.m_workgroupSizes[i] != MAX_U32);
  318. }
  319. }
  320. // Time to init the shaders
  321. if(!!(m_shaderStages & (ShaderTypeBit::ALL_GRAPHICS | ShaderTypeBit::COMPUTE)))
  322. {
  323. // Create the program name
  324. StringAuto progName(getTempAllocator());
  325. getFilepathFilename(getFilename(), progName);
  326. char* cprogName = const_cast<char*>(progName.cstr());
  327. if(progName.getLength() > MAX_GR_OBJECT_NAME_LENGTH)
  328. {
  329. cprogName[MAX_GR_OBJECT_NAME_LENGTH] = '\0';
  330. }
  331. ShaderProgramInitInfo progInf(cprogName);
  332. for(ShaderType shaderType : EnumIterable<ShaderType>())
  333. {
  334. if(!(ShaderTypeBit(1 << shaderType) & m_shaderStages))
  335. {
  336. continue;
  337. }
  338. ShaderInitInfo inf(cprogName);
  339. inf.m_shaderType = shaderType;
  340. inf.m_binary = binary.m_codeBlocks[binaryVariant->m_codeBlockIndices[shaderType]].m_binary;
  341. inf.m_constValues.setArray((constValueCount) ? constValues.getBegin() : nullptr, constValueCount);
  342. ShaderPtr shader = getManager().getGrManager().newShader(inf);
  343. const ShaderTypeBit shaderBit = ShaderTypeBit(1 << shaderType);
  344. if(!!(shaderBit & ShaderTypeBit::ALL_GRAPHICS))
  345. {
  346. progInf.m_graphicsShaders[shaderType] = shader;
  347. }
  348. else if(shaderType == ShaderType::COMPUTE)
  349. {
  350. progInf.m_computeShader = shader;
  351. }
  352. else
  353. {
  354. ANKI_ASSERT(0);
  355. }
  356. }
  357. // Create the program
  358. variant.m_prog = getManager().getGrManager().newShaderProgram(progInf);
  359. }
  360. else
  361. {
  362. ANKI_ASSERT(!!(m_shaderStages & ShaderTypeBit::ALL_RAY_TRACING));
  363. // Find the library
  364. CString libName = &binary.m_libraryName[0];
  365. ANKI_ASSERT(libName.getLength() > 0);
  366. const ShaderProgramResourceSystem& progSystem = getManager().getShaderProgramResourceSystem();
  367. const ShaderProgramRaytracingLibrary* foundLib = nullptr;
  368. for(const ShaderProgramRaytracingLibrary& lib : progSystem.getRayTracingLibraries())
  369. {
  370. if(lib.getLibraryName() == libName)
  371. {
  372. foundLib = &lib;
  373. break;
  374. }
  375. }
  376. ANKI_ASSERT(foundLib);
  377. variant.m_prog = foundLib->getShaderProgram();
  378. // Set the group handle
  379. const U32 groupHandleSize = getManager().getGrManager().getDeviceCapabilities().m_shaderGroupHandleSize;
  380. variant.m_hitShaderGroupHandleSize = U8(groupHandleSize);
  381. ANKI_ASSERT(sizeof(variant.m_hitShaderGroupHandle) >= groupHandleSize);
  382. WeakArray<U8> handle(&variant.m_hitShaderGroupHandle[0], groupHandleSize);
  383. if(m_shaderStages == ShaderTypeBit::RAY_GEN)
  384. {
  385. foundLib->getRayGenShaderGroupHandle(handle);
  386. }
  387. else if(m_shaderStages == ShaderTypeBit::MISS)
  388. {
  389. const U32 rayType = binary.m_rayType;
  390. foundLib->getMissShaderGroupHandle(rayType, handle);
  391. }
  392. else
  393. {
  394. ANKI_ASSERT(!!(m_shaderStages & (ShaderTypeBit::ANY_HIT | ShaderTypeBit::CLOSEST_HIT)));
  395. foundLib->getHitShaderGroupHandle(getFilename(), mutationHash, handle);
  396. }
  397. }
  398. }
  399. } // end namespace anki