ShaderProgramParser.cpp 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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/ShaderCompiler/ShaderProgramParser.h>
  6. namespace anki
  7. {
  8. #define ANKI_PP_ERROR_MALFORMED() \
  9. ANKI_SHADER_COMPILER_LOGE("%s: Malformed expression: %s", fname.cstr(), line.cstr()); \
  10. return Error::USER_DATA
  11. #define ANKI_PP_ERROR_MALFORMED_MSG(msg_) \
  12. ANKI_SHADER_COMPILER_LOGE("%s: " msg_ ": %s", fname.cstr(), line.cstr()); \
  13. return Error::USER_DATA
  14. static const Array<CString, U32(ShaderType::COUNT)> SHADER_STAGE_NAMES = {
  15. {"VERTEX", "TESSELLATION_CONTROL", "TESSELLATION_EVALUATION", "GEOMETRY", "FRAGMENT", "COMPUTE", "RAY_GEN",
  16. "ANY_HIT", "CLOSEST_HIT", "MISS", "INTERSECTION", "CALLABLE"}};
  17. static const char* SHADER_HEADER = R"(#version 460 core
  18. #define ANKI_%s_SHADER 1
  19. #define gl_VertexID gl_VertexIndex
  20. #extension GL_EXT_control_flow_attributes : require
  21. #define ANKI_UNROLL [[unroll]]
  22. #define ANKI_LOOP [[dont_unroll]]
  23. #define ANKI_BRANCH [[branch]]
  24. #define ANKI_FLATTEN [[flatten]]
  25. #extension GL_KHR_shader_subgroup_vote : require
  26. #extension GL_KHR_shader_subgroup_ballot : require
  27. #extension GL_KHR_shader_subgroup_shuffle : require
  28. #extension GL_KHR_shader_subgroup_arithmetic : require
  29. #extension GL_EXT_samplerless_texture_functions : require
  30. #extension GL_EXT_shader_image_load_formatted : require
  31. #extension GL_EXT_nonuniform_qualifier : enable
  32. #extension GL_EXT_buffer_reference : enable
  33. #extension GL_EXT_buffer_reference2 : enable
  34. #extension GL_EXT_shader_explicit_arithmetic_types : enable
  35. #extension GL_EXT_shader_explicit_arithmetic_types_int8 : enable
  36. #extension GL_EXT_shader_explicit_arithmetic_types_int16 : enable
  37. #extension GL_EXT_shader_explicit_arithmetic_types_int32 : enable
  38. #extension GL_EXT_shader_explicit_arithmetic_types_int64 : enable
  39. #extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable
  40. #extension GL_EXT_shader_explicit_arithmetic_types_float32 : enable
  41. #extension GL_EXT_shader_explicit_arithmetic_types_float64 : enable
  42. #extension GL_EXT_shader_atomic_int64 : enable
  43. #extension GL_EXT_shader_subgroup_extended_types_int64 : enable
  44. #extension GL_EXT_nonuniform_qualifier : enable
  45. #extension GL_EXT_scalar_block_layout : enable
  46. #define ANKI_MAX_BINDLESS_TEXTURES %u
  47. #define ANKI_MAX_BINDLESS_IMAGES %u
  48. #if defined(ANKI_RAY_GEN_SHADER) || defined(ANKI_ANY_HIT_SHADER) || defined(ANKI_CLOSEST_HIT_SHADER) || defined(ANKI_MISS_SHADER) || defined(ANKI_INTERSECTION_SHADER) || defined(ANKI_CALLABLE_SHADER)
  49. # extension GL_EXT_ray_tracing : enable
  50. #endif
  51. #define ANKI_BINDLESS_SET(set_) \
  52. layout(set = set_, binding = 0) uniform utexture2D u_bindlessTextures2dU32[ANKI_MAX_BINDLESS_TEXTURES]; \
  53. layout(set = set_, binding = 0) uniform itexture2D u_bindlessTextures2dI32[ANKI_MAX_BINDLESS_TEXTURES]; \
  54. layout(set = set_, binding = 0) uniform texture2D u_bindlessTextures2dF32[ANKI_MAX_BINDLESS_TEXTURES]; \
  55. layout(set = set_, binding = 1) uniform readonly uimage2D u_bindlessImages2dU32[ANKI_MAX_BINDLESS_IMAGES]; \
  56. layout(set = set_, binding = 1) uniform readonly iimage2D u_bindlessImages2dI32[ANKI_MAX_BINDLESS_IMAGES]; \
  57. layout(set = set_, binding = 1) uniform readonly image2D u_bindlessImages2dF32[ANKI_MAX_BINDLESS_IMAGES]
  58. #define F32 float
  59. #define _ANKI_SIZEOF_float 4u
  60. #define Vec2 vec2
  61. #define _ANKI_SIZEOF_vec2 8u
  62. #define Vec3 vec3
  63. #define _ANKI_SIZEOF_vec3 12u
  64. #define Vec4 vec4
  65. #define _ANKI_SIZEOF_vec4 16u
  66. #define F16 float16_t
  67. #define _ANKI_SIZEOF_float16_t 2u
  68. #define HVec2 f16vec2
  69. #define _ANKI_SIZEOF_f16vec2 4u
  70. #define HVec3 f16vec3
  71. #define _ANKI_SIZEOF_f16vec3 6u
  72. #define HVec4 f16vec4
  73. #define _ANKI_SIZEOF_f16vec4 8u
  74. #define U8 uint8_t
  75. #define _ANKI_SIZEOF_uint8_t 1u
  76. #define U8Vec2 u8vec2
  77. #define _ANKI_SIZEOF_u8vec2 2u
  78. #define U8Vec3 u8vec3
  79. #define _ANKI_SIZEOF_u8vec3 3u
  80. #define U8Vec4 u8vec4
  81. #define _ANKI_SIZEOF_u8vec4 4u
  82. #define I8 int8_t
  83. #define _ANKI_SIZEOF_int8_t 1u
  84. #define I8Vec2 i8vec2
  85. #define _ANKI_SIZEOF_i8vec2 2u
  86. #define I8Vec3 i8vec3
  87. #define _ANKI_SIZEOF_i8vec3 3u
  88. #define I8Vec4 i8vec4
  89. #define _ANKI_SIZEOF_i8vec4 4u
  90. #define U16 uint16_t
  91. #define _ANKI_SIZEOF_uint16_t 2u
  92. #define U16Vec2 u16vec2
  93. #define _ANKI_SIZEOF_u16vec2 4u
  94. #define U16Vec3 u16vec3
  95. #define _ANKI_SIZEOF_u16vec3 6u
  96. #define U16Vec4 u16vec4
  97. #define _ANKI_SIZEOF_u16vec4 8u
  98. #define I16 int16_t
  99. #define _ANKI_SIZEOF_int16_t 2u
  100. #define I16Vec2 i16vec2
  101. #define _ANKI_SIZEOF_i16vec2 4u
  102. #define I16Vec3 i16vec3
  103. #define _ANKI_SIZEOF_i16vec3 6u
  104. #define i16Vec4 i16vec4
  105. #define _ANKI_SIZEOF_i16vec4 8u
  106. #define U32 uint
  107. #define _ANKI_SIZEOF_uint 4u
  108. #define UVec2 uvec2
  109. #define _ANKI_SIZEOF_uvec2 8u
  110. #define UVec3 uvec3
  111. #define _ANKI_SIZEOF_uvec3 12u
  112. #define UVec4 uvec4
  113. #define _ANKI_SIZEOF_uvec4 16u
  114. #define I32 int
  115. #define _ANKI_SIZEOF_int 4u
  116. #define IVec2 ivec2
  117. #define _ANKI_SIZEOF_ivec2 8u
  118. #define IVec3 ivec3
  119. #define _ANKI_SIZEOF_ivec3 12u
  120. #define IVec4 ivec4
  121. #define _ANKI_SIZEOF_ivec4 16u
  122. #define U64 uint64_t
  123. #define _ANKI_SIZEOF_uint64_t 8u
  124. #define U64Vec2 u64vec2
  125. #define _ANKI_SIZEOF_u64vec2 16u
  126. #define U64Vec3 u64vec3
  127. #define _ANKI_SIZEOF_u64vec3 24u
  128. #define U64Vec4 u64vec4
  129. #define _ANKI_SIZEOF_u64vec4 32u
  130. #define I64 int64_t
  131. #define _ANKI_SIZEOF_int64_t 8u
  132. #define I64Vec2 i64vec2
  133. #define _ANKI_SIZEOF_i64vec2 16u
  134. #define I64Vec3 i64vec3
  135. #define _ANKI_SIZEOF_i64vec3 24u
  136. #define I64Vec4 i64vec4
  137. #define _ANKI_SIZEOF_i64vec4 32u
  138. #define Mat3 mat3
  139. #define Mat4 mat4
  140. #define _ANKI_SIZEOF_mat4 64u
  141. #define Mat3x4 mat3x4
  142. #define _ANKI_SIZEOF_mat3x4 48u
  143. #define Bool bool
  144. #define _ANKI_CONCATENATE(a, b) a##b
  145. #define ANKI_CONCATENATE(a, b) _ANKI_CONCATENATE(a, b)
  146. #define ANKI_SIZEOF(type) _ANKI_CONCATENATE(_ANKI_SIZEOF_, type)
  147. #define ANKI_ALIGNOF(type) _ANKI_CONCATENATE(_ANKI_ALIGNOF_, type)
  148. #define _ANKI_SCONST_X(type, n, id) \
  149. layout(constant_id = id) const type n = type(1); \
  150. const U32 ANKI_CONCATENATE(n, _CONST_ID) = id
  151. #define _ANKI_SCONST_X2(type, componentType, n, id, constWorkaround) \
  152. layout(constant_id = id + 0u) const componentType ANKI_CONCATENATE(_anki_const_0_2_, n) = componentType(1); \
  153. layout(constant_id = id + 1u) const componentType ANKI_CONCATENATE(_anki_const_1_2_, n) = componentType(1); \
  154. constWorkaround type n = type(ANKI_CONCATENATE(_anki_const_0_2_, n), ANKI_CONCATENATE(_anki_const_1_2_, n))
  155. #define _ANKI_SCONST_X3(type, componentType, n, id, constWorkaround) \
  156. layout(constant_id = id + 0u) const componentType ANKI_CONCATENATE(_anki_const_0_3_, n) = componentType(1); \
  157. layout(constant_id = id + 1u) const componentType ANKI_CONCATENATE(_anki_const_1_3_, n) = componentType(1); \
  158. layout(constant_id = id + 2u) const componentType ANKI_CONCATENATE(_anki_const_2_3_, n) = componentType(1); \
  159. constWorkaround type n = type(ANKI_CONCATENATE(_anki_const_0_3_, n), ANKI_CONCATENATE(_anki_const_1_3_, n), \
  160. ANKI_CONCATENATE(_anki_const_2_3_, n))
  161. #define _ANKI_SCONST_X4(type, componentType, n, id, constWorkaround) \
  162. layout(constant_id = id + 0u) const componentType ANKI_CONCATENATE(_anki_const_0_4_, n) = componentType(1); \
  163. layout(constant_id = id + 1u) const componentType ANKI_CONCATENATE(_anki_const_1_4_, n) = componentType(1); \
  164. layout(constant_id = id + 2u) const componentType ANKI_CONCATENATE(_anki_const_2_4_, n) = componentType(1); \
  165. layout(constant_id = id + 3u) const componentType ANKI_CONCATENATE(_anki_const_3_4_, n) = componentType(1); \
  166. constWorkaround type n = type(ANKI_CONCATENATE(_anki_const_0_4_, n), ANKI_CONCATENATE(_anki_const_1_4_, n), \
  167. ANKI_CONCATENATE(_anki_const_2_4_, n), ANKI_CONCATENATE(_anki_const_2_4_, n))
  168. #define ANKI_SPECIALIZATION_CONSTANT_I32(n, id) _ANKI_SCONST_X(I32, n, id)
  169. #define ANKI_SPECIALIZATION_CONSTANT_IVEC2(n, id) _ANKI_SCONST_X2(IVec2, I32, n, id, const)
  170. #define ANKI_SPECIALIZATION_CONSTANT_IVEC3(n, id) _ANKI_SCONST_X3(IVec3, I32, n, id, const)
  171. #define ANKI_SPECIALIZATION_CONSTANT_IVEC4(n, id) _ANKI_SCONST_X4(IVec4, I32, n, id, const)
  172. #define ANKI_SPECIALIZATION_CONSTANT_U32(n, id) _ANKI_SCONST_X(U32, n, id)
  173. #define ANKI_SPECIALIZATION_CONSTANT_UVEC2(n, id) _ANKI_SCONST_X2(UVec2, U32, n, id, const)
  174. #define ANKI_SPECIALIZATION_CONSTANT_UVEC3(n, id) _ANKI_SCONST_X3(UVec3, U32, n, id, const)
  175. #define ANKI_SPECIALIZATION_CONSTANT_UVEC4(n, id) _ANKI_SCONST_X4(UVec4, U32, n, id, const)
  176. #define ANKI_SPECIALIZATION_CONSTANT_F32(n, id) _ANKI_SCONST_X(F32, n, id)
  177. #define ANKI_SPECIALIZATION_CONSTANT_VEC2(n, id) _ANKI_SCONST_X2(Vec2, F32, n, id,)
  178. #define ANKI_SPECIALIZATION_CONSTANT_VEC3(n, id) _ANKI_SCONST_X3(Vec3, F32, n, id,)
  179. #define ANKI_SPECIALIZATION_CONSTANT_VEC4(n, id) _ANKI_SCONST_X4(Vec4, F32, n, id,)
  180. #define ANKI_REF(type, alignment) \
  181. layout(buffer_reference, scalar, buffer_reference_align = (alignment)) buffer type##Ref \
  182. { \
  183. type m_value; \
  184. }
  185. #define ANKI_PADDING(bytes) U8 _padding_ ## __LINE__[bytes]
  186. layout(std140, row_major) uniform;
  187. layout(std140, row_major) buffer;
  188. )";
  189. static const U64 SHADER_HEADER_HASH = computeHash(SHADER_HEADER, sizeof(SHADER_HEADER));
  190. ShaderProgramParser::ShaderProgramParser(CString fname, ShaderProgramFilesystemInterface* fsystem,
  191. GenericMemoryPoolAllocator<U8> alloc,
  192. const ShaderCompilerOptions& compilerOptions)
  193. : m_alloc(alloc)
  194. , m_fname(alloc, fname)
  195. , m_fsystem(fsystem)
  196. , m_compilerOptions(compilerOptions)
  197. {
  198. }
  199. ShaderProgramParser::~ShaderProgramParser()
  200. {
  201. }
  202. void ShaderProgramParser::tokenizeLine(CString line, DynamicArrayAuto<StringAuto>& tokens) const
  203. {
  204. ANKI_ASSERT(line.getLength() > 0);
  205. StringAuto l(m_alloc, line);
  206. // Replace all tabs with spaces
  207. for(char& c : l)
  208. {
  209. if(c == '\t')
  210. {
  211. c = ' ';
  212. }
  213. }
  214. // Split
  215. StringListAuto spaceTokens(m_alloc);
  216. spaceTokens.splitString(l, ' ', false);
  217. // Create the array
  218. for(const String& s : spaceTokens)
  219. {
  220. tokens.emplaceBack(m_alloc, s);
  221. }
  222. }
  223. Error ShaderProgramParser::parsePragmaStart(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  224. {
  225. ANKI_ASSERT(begin && end);
  226. if(begin >= end)
  227. {
  228. ANKI_PP_ERROR_MALFORMED();
  229. }
  230. ShaderType shaderType = ShaderType::COUNT;
  231. if(*begin == "vert")
  232. {
  233. shaderType = ShaderType::VERTEX;
  234. }
  235. else if(*begin == "tessc")
  236. {
  237. shaderType = ShaderType::TESSELLATION_CONTROL;
  238. }
  239. else if(*begin == "tesse")
  240. {
  241. }
  242. else if(*begin == "geom")
  243. {
  244. shaderType = ShaderType::GEOMETRY;
  245. }
  246. else if(*begin == "frag")
  247. {
  248. shaderType = ShaderType::FRAGMENT;
  249. }
  250. else if(*begin == "comp")
  251. {
  252. shaderType = ShaderType::COMPUTE;
  253. }
  254. else if(*begin == "rgen")
  255. {
  256. shaderType = ShaderType::RAY_GEN;
  257. }
  258. else if(*begin == "ahit")
  259. {
  260. shaderType = ShaderType::ANY_HIT;
  261. }
  262. else if(*begin == "chit")
  263. {
  264. shaderType = ShaderType::CLOSEST_HIT;
  265. }
  266. else if(*begin == "miss")
  267. {
  268. shaderType = ShaderType::MISS;
  269. }
  270. else if(*begin == "int")
  271. {
  272. shaderType = ShaderType::INTERSECTION;
  273. }
  274. else if(*begin == "call")
  275. {
  276. shaderType = ShaderType::CALLABLE;
  277. }
  278. else
  279. {
  280. ANKI_PP_ERROR_MALFORMED();
  281. }
  282. m_codeLines.pushBackSprintf("#ifdef ANKI_%s_SHADER", SHADER_STAGE_NAMES[shaderType].cstr());
  283. ++begin;
  284. if(begin != end)
  285. {
  286. // Should be the last token
  287. ANKI_PP_ERROR_MALFORMED();
  288. }
  289. // Set the mask
  290. const ShaderTypeBit mask = ShaderTypeBit(1 << shaderType);
  291. if(!!(mask & m_shaderTypes))
  292. {
  293. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start <shader> appearing more than once");
  294. }
  295. m_shaderTypes |= mask;
  296. // Check bounds
  297. if(m_insideShader)
  298. {
  299. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start before you close the previous pragma start");
  300. }
  301. m_insideShader = true;
  302. return Error::NONE;
  303. }
  304. Error ShaderProgramParser::parsePragmaEnd(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  305. {
  306. ANKI_ASSERT(begin && end);
  307. // Check tokens
  308. if(begin != end)
  309. {
  310. ANKI_PP_ERROR_MALFORMED();
  311. }
  312. // Check bounds
  313. if(!m_insideShader)
  314. {
  315. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma end before you open with a pragma start");
  316. }
  317. m_insideShader = false;
  318. // Write code
  319. m_codeLines.pushBack("#endif // Shader guard");
  320. return Error::NONE;
  321. }
  322. Error ShaderProgramParser::parsePragmaMutator(const StringAuto* begin, const StringAuto* end, CString line,
  323. CString fname)
  324. {
  325. ANKI_ASSERT(begin && end);
  326. if(begin >= end)
  327. {
  328. ANKI_PP_ERROR_MALFORMED();
  329. }
  330. m_mutators.emplaceBack(m_alloc);
  331. Mutator& mutator = m_mutators.getBack();
  332. // Name
  333. {
  334. if(begin >= end)
  335. {
  336. // Need to have a name
  337. ANKI_PP_ERROR_MALFORMED();
  338. }
  339. // Check for duplicate mutators
  340. for(U32 i = 0; i < m_mutators.getSize() - 1; ++i)
  341. {
  342. if(m_mutators[i].m_name == *begin)
  343. {
  344. ANKI_PP_ERROR_MALFORMED_MSG("Duplicate mutator");
  345. }
  346. }
  347. if(begin->getLength() > MAX_SHADER_BINARY_NAME_LENGTH)
  348. {
  349. ANKI_PP_ERROR_MALFORMED_MSG("Too big name");
  350. }
  351. mutator.m_name.create(begin->toCString());
  352. ++begin;
  353. }
  354. // Values
  355. {
  356. // Gather them
  357. for(; begin < end; ++begin)
  358. {
  359. MutatorValue value = 0;
  360. if(tokenIsComment(begin->toCString()))
  361. {
  362. break;
  363. }
  364. if(begin->toNumber(value))
  365. {
  366. ANKI_PP_ERROR_MALFORMED();
  367. }
  368. mutator.m_values.emplaceBack(value);
  369. }
  370. // Check for correct count
  371. if(mutator.m_values.getSize() < 2)
  372. {
  373. ANKI_PP_ERROR_MALFORMED_MSG("Mutator with less that 2 values doesn't make sense");
  374. }
  375. std::sort(mutator.m_values.getBegin(), mutator.m_values.getEnd());
  376. // Check for duplicates
  377. for(U32 i = 1; i < mutator.m_values.getSize(); ++i)
  378. {
  379. if(mutator.m_values[i - 1] == mutator.m_values[i])
  380. {
  381. ANKI_PP_ERROR_MALFORMED_MSG("Same value appeared more than once");
  382. }
  383. }
  384. }
  385. return Error::NONE;
  386. }
  387. Error ShaderProgramParser::parsePragmaLibraryName(const StringAuto* begin, const StringAuto* end, CString line,
  388. CString fname)
  389. {
  390. ANKI_ASSERT(begin && end);
  391. if(begin >= end)
  392. {
  393. ANKI_PP_ERROR_MALFORMED();
  394. }
  395. if(m_libName.getLength() > 0)
  396. {
  397. ANKI_PP_ERROR_MALFORMED_MSG("Library name already set");
  398. }
  399. m_libName = *begin;
  400. return Error::NONE;
  401. }
  402. Error ShaderProgramParser::parsePragmaRayType(const StringAuto* begin, const StringAuto* end, CString line,
  403. CString fname)
  404. {
  405. ANKI_ASSERT(begin && end);
  406. if(begin >= end)
  407. {
  408. ANKI_PP_ERROR_MALFORMED();
  409. }
  410. if(m_rayType != MAX_U32)
  411. {
  412. ANKI_PP_ERROR_MALFORMED_MSG("Ray type already set");
  413. }
  414. ANKI_CHECK(begin->toNumber(m_rayType));
  415. if(m_rayType > 128)
  416. {
  417. ANKI_PP_ERROR_MALFORMED_MSG("Ray type has a very large value");
  418. }
  419. return Error::NONE;
  420. }
  421. Error ShaderProgramParser::parsePragmaRewriteMutation(const StringAuto* begin, const StringAuto* end, CString line,
  422. CString fname)
  423. {
  424. ANKI_ASSERT(begin && end);
  425. // Some basic sanity checks
  426. const U tokenCount = end - begin;
  427. constexpr U minTokenCount = 2 + 1 + 2; // Mutator + value + "to" + mutator + value
  428. if(tokenCount < minTokenCount)
  429. {
  430. ANKI_PP_ERROR_MALFORMED();
  431. }
  432. MutationRewrite& rewrite = *m_mutationRewrites.emplaceBack(m_alloc);
  433. Bool servingFrom = true;
  434. do
  435. {
  436. if(*begin == "to")
  437. {
  438. if(servingFrom == false)
  439. {
  440. ANKI_PP_ERROR_MALFORMED();
  441. }
  442. servingFrom = false;
  443. }
  444. else
  445. {
  446. // Mutator & value
  447. // Get mutator and value
  448. const CString mutatorName = *begin;
  449. ++begin;
  450. if(begin == end)
  451. {
  452. ANKI_PP_ERROR_MALFORMED();
  453. }
  454. const CString valueStr = *begin;
  455. MutatorValue value;
  456. if(valueStr.toNumber(value))
  457. {
  458. ANKI_PP_ERROR_MALFORMED_MSG("Malformed value");
  459. }
  460. // Get or create new record
  461. if(servingFrom)
  462. {
  463. MutationRewrite::Record& rec = *rewrite.m_records.emplaceBack();
  464. for(U32 i = 0; i < m_mutators.getSize(); ++i)
  465. {
  466. if(m_mutators[i].getName() == mutatorName)
  467. {
  468. rec.m_mutatorIndex = i;
  469. break;
  470. }
  471. }
  472. if(rec.m_mutatorIndex == MAX_U32)
  473. {
  474. ANKI_PP_ERROR_MALFORMED_MSG("Mutator not found");
  475. }
  476. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  477. {
  478. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  479. }
  480. rec.m_valueFrom = value;
  481. }
  482. else
  483. {
  484. Bool found = false;
  485. for(MutationRewrite::Record& rec : rewrite.m_records)
  486. {
  487. if(m_mutators[rec.m_mutatorIndex].m_name == mutatorName)
  488. {
  489. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  490. {
  491. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  492. }
  493. rec.m_valueTo = value;
  494. found = true;
  495. break;
  496. }
  497. }
  498. if(!found)
  499. {
  500. ANKI_PP_ERROR_MALFORMED();
  501. }
  502. }
  503. }
  504. ++begin;
  505. } while(begin < end && !tokenIsComment(*begin));
  506. // Sort for some later cross checking
  507. std::sort(rewrite.m_records.getBegin(), rewrite.m_records.getEnd(),
  508. [](const MutationRewrite::Record& a, const MutationRewrite::Record& b) {
  509. return a.m_mutatorIndex < b.m_mutatorIndex;
  510. });
  511. // More cross checking
  512. for(U32 i = 1; i < rewrite.m_records.getSize(); ++i)
  513. {
  514. if(rewrite.m_records[i - 1].m_mutatorIndex == rewrite.m_records[i].m_mutatorIndex)
  515. {
  516. ANKI_PP_ERROR_MALFORMED_MSG("Mutator appeared more than once");
  517. }
  518. }
  519. for(U32 i = 0; i < m_mutationRewrites.getSize() - 1; ++i)
  520. {
  521. const MutationRewrite& other = m_mutationRewrites[i];
  522. if(other.m_records.getSize() != rewrite.m_records.getSize())
  523. {
  524. continue;
  525. }
  526. Bool same = true;
  527. for(U32 j = 0; j < rewrite.m_records.getSize(); ++j)
  528. {
  529. if(rewrite.m_records[j] != other.m_records[j])
  530. {
  531. same = false;
  532. break;
  533. }
  534. }
  535. if(same)
  536. {
  537. ANKI_PP_ERROR_MALFORMED_MSG("Mutation already exists");
  538. }
  539. }
  540. return Error::NONE;
  541. }
  542. Error ShaderProgramParser::parseInclude(const StringAuto* begin, const StringAuto* end, CString line, CString fname,
  543. U32 depth)
  544. {
  545. // Gather the path
  546. StringAuto path(m_alloc);
  547. for(; begin < end; ++begin)
  548. {
  549. path.append(*begin);
  550. }
  551. if(path.isEmpty())
  552. {
  553. ANKI_PP_ERROR_MALFORMED();
  554. }
  555. // Check
  556. const char firstChar = path[0];
  557. const char lastChar = path[path.getLength() - 1];
  558. if((firstChar == '\"' && lastChar == '\"') || (firstChar == '<' && lastChar == '>'))
  559. {
  560. StringAuto fname2(m_alloc);
  561. fname2.create(path.begin() + 1, path.begin() + path.getLength() - 1);
  562. if(parseFile(fname2, depth + 1))
  563. {
  564. ANKI_PP_ERROR_MALFORMED_MSG("Error parsing include. See previous errors");
  565. }
  566. }
  567. else
  568. {
  569. ANKI_PP_ERROR_MALFORMED();
  570. }
  571. return Error::NONE;
  572. }
  573. Error ShaderProgramParser::parseLine(CString line, CString fname, Bool& foundPragmaOnce, U32 depth)
  574. {
  575. // Tokenize
  576. DynamicArrayAuto<StringAuto> tokens(m_alloc);
  577. tokenizeLine(line, tokens);
  578. ANKI_ASSERT(tokens.getSize() > 0);
  579. const StringAuto* token = tokens.getBegin();
  580. const StringAuto* end = tokens.getEnd();
  581. // Skip the hash
  582. Bool foundAloneHash = false;
  583. if(*token == "#")
  584. {
  585. ++token;
  586. foundAloneHash = true;
  587. }
  588. if((token < end) && ((foundAloneHash && *token == "include") || *token == "#include"))
  589. {
  590. // We _must_ have an #include
  591. ANKI_CHECK(parseInclude(token + 1, end, line, fname, depth));
  592. }
  593. else if((token < end) && ((foundAloneHash && *token == "pragma") || *token == "#pragma"))
  594. {
  595. // We may have a #pragma once or a #pragma anki or something else
  596. ++token;
  597. if(*token == "once")
  598. {
  599. // Pragma once
  600. if(foundPragmaOnce)
  601. {
  602. ANKI_PP_ERROR_MALFORMED_MSG("Can't have more than one #pragma once per file");
  603. }
  604. if(token + 1 != end)
  605. {
  606. ANKI_PP_ERROR_MALFORMED();
  607. }
  608. // Add the guard unique for this file
  609. foundPragmaOnce = true;
  610. const U64 hash = fname.computeHash();
  611. m_codeLines.pushBackSprintf("#ifndef _ANKI_INCL_GUARD_%llu\n"
  612. "#define _ANKI_INCL_GUARD_%llu",
  613. hash, hash);
  614. }
  615. else if(*token == "anki")
  616. {
  617. // Must be a #pragma anki
  618. ++token;
  619. if(*token == "mutator")
  620. {
  621. ANKI_CHECK(parsePragmaMutator(token + 1, end, line, fname));
  622. }
  623. else if(*token == "start")
  624. {
  625. ANKI_CHECK(parsePragmaStart(token + 1, end, line, fname));
  626. }
  627. else if(*token == "end")
  628. {
  629. ANKI_CHECK(parsePragmaEnd(token + 1, end, line, fname));
  630. }
  631. else if(*token == "rewrite_mutation")
  632. {
  633. ANKI_CHECK(parsePragmaRewriteMutation(token + 1, end, line, fname));
  634. }
  635. else if(*token == "library")
  636. {
  637. ANKI_CHECK(parsePragmaLibraryName(token + 1, end, line, fname));
  638. }
  639. else if(*token == "ray_type")
  640. {
  641. ANKI_CHECK(parsePragmaRayType(token + 1, end, line, fname));
  642. }
  643. else
  644. {
  645. ANKI_PP_ERROR_MALFORMED();
  646. }
  647. // Add the line as a comment because of hashing of the source
  648. m_codeLines.pushBackSprintf("//%s", line.cstr());
  649. }
  650. else
  651. {
  652. // Some other pragma
  653. ANKI_SHADER_COMPILER_LOGW("Ignoring: %s", line.cstr());
  654. m_codeLines.pushBack(line);
  655. }
  656. }
  657. else
  658. {
  659. // Ignore
  660. m_codeLines.pushBack(line);
  661. }
  662. return Error::NONE;
  663. }
  664. Error ShaderProgramParser::parseFile(CString fname, U32 depth)
  665. {
  666. // First check the depth
  667. if(depth > MAX_INCLUDE_DEPTH)
  668. {
  669. ANKI_SHADER_COMPILER_LOGE("The include depth is too high. Probably circular includance");
  670. }
  671. Bool foundPragmaOnce = false;
  672. // Load file in lines
  673. StringAuto txt(m_alloc);
  674. ANKI_CHECK(m_fsystem->readAllText(fname, txt));
  675. StringListAuto lines(m_alloc);
  676. lines.splitString(txt.toCString(), '\n');
  677. if(lines.getSize() < 1)
  678. {
  679. ANKI_SHADER_COMPILER_LOGE("Source is empty");
  680. }
  681. // Parse lines
  682. for(const String& line : lines)
  683. {
  684. if(line.find("pragma") != CString::NPOS || line.find("include") != CString::NPOS)
  685. {
  686. // Possibly a preprocessor directive we care
  687. ANKI_CHECK(parseLine(line.toCString(), fname, foundPragmaOnce, depth));
  688. }
  689. else
  690. {
  691. // Just append the line
  692. m_codeLines.pushBack(line.toCString());
  693. }
  694. }
  695. if(foundPragmaOnce)
  696. {
  697. // Append the guard
  698. m_codeLines.pushBack("#endif // Include guard");
  699. }
  700. return Error::NONE;
  701. }
  702. Error ShaderProgramParser::parse()
  703. {
  704. ANKI_ASSERT(!m_fname.isEmpty());
  705. ANKI_ASSERT(m_codeLines.isEmpty());
  706. const CString fname = m_fname;
  707. // Parse recursively
  708. ANKI_CHECK(parseFile(fname, 0));
  709. // Checks
  710. {
  711. if(!!(m_shaderTypes & ShaderTypeBit::COMPUTE))
  712. {
  713. if(m_shaderTypes != ShaderTypeBit::COMPUTE)
  714. {
  715. ANKI_SHADER_COMPILER_LOGE("Can't combine compute shader with other types of shaders");
  716. return Error::USER_DATA;
  717. }
  718. }
  719. else if(!!(m_shaderTypes & ShaderTypeBit::ALL_GRAPHICS))
  720. {
  721. if(!(m_shaderTypes & ShaderTypeBit::VERTEX))
  722. {
  723. ANKI_SHADER_COMPILER_LOGE("Missing vertex shader");
  724. return Error::USER_DATA;
  725. }
  726. if(!(m_shaderTypes & ShaderTypeBit::FRAGMENT))
  727. {
  728. ANKI_SHADER_COMPILER_LOGE("Missing fragment shader");
  729. return Error::USER_DATA;
  730. }
  731. }
  732. if(m_insideShader)
  733. {
  734. ANKI_SHADER_COMPILER_LOGE("Forgot a \"pragma anki end\"");
  735. return Error::USER_DATA;
  736. }
  737. }
  738. // Create the code lines
  739. if(m_codeLines.getSize())
  740. {
  741. m_codeLines.join("\n", m_codeSource);
  742. m_codeLines.destroy();
  743. }
  744. // Create the hash
  745. {
  746. if(m_codeSource.getLength())
  747. {
  748. m_codeSourceHash = appendHash(m_codeSource.getBegin(), m_codeSource.getLength(), SHADER_HEADER_HASH);
  749. }
  750. if(m_libName.getLength() > 0)
  751. {
  752. m_codeSourceHash = appendHash(m_libName.getBegin(), m_libName.getLength(), m_codeSourceHash);
  753. }
  754. m_codeSourceHash = appendHash(&m_rayType, sizeof(m_rayType), m_codeSourceHash);
  755. }
  756. return Error::NONE;
  757. }
  758. void ShaderProgramParser::generateAnkiShaderHeader(ShaderType shaderType, const ShaderCompilerOptions& compilerOptions,
  759. StringAuto& header)
  760. {
  761. header.sprintf(SHADER_HEADER, SHADER_STAGE_NAMES[shaderType].cstr(),
  762. compilerOptions.m_bindlessLimits.m_bindlessTextureCount,
  763. compilerOptions.m_bindlessLimits.m_bindlessImageCount);
  764. }
  765. Error ShaderProgramParser::generateVariant(ConstWeakArray<MutatorValue> mutation,
  766. ShaderProgramParserVariant& variant) const
  767. {
  768. // Sanity checks
  769. ANKI_ASSERT(m_codeSource.getLength() > 0);
  770. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  771. for(U32 i = 0; i < mutation.getSize(); ++i)
  772. {
  773. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]) && "Value not found");
  774. }
  775. // Init variant
  776. ::new(&variant) ShaderProgramParserVariant();
  777. variant.m_alloc = m_alloc;
  778. // Create the mutator defines
  779. StringAuto mutatorDefines(m_alloc);
  780. for(U32 i = 0; i < mutation.getSize(); ++i)
  781. {
  782. mutatorDefines.append(StringAuto(m_alloc).sprintf("#define %s %d\n", m_mutators[i].m_name.cstr(), mutation[i]));
  783. }
  784. // Generate souce per stage
  785. for(ShaderType shaderType : EnumIterable<ShaderType>())
  786. {
  787. if(!(ShaderTypeBit(1u << shaderType) & m_shaderTypes))
  788. {
  789. continue;
  790. }
  791. // Create the header
  792. StringAuto header(m_alloc);
  793. generateAnkiShaderHeader(shaderType, m_compilerOptions, header);
  794. // Create the final source without the bindings
  795. StringAuto finalSource(m_alloc);
  796. finalSource.append(header);
  797. finalSource.append(mutatorDefines);
  798. finalSource.append(m_codeSource);
  799. // Move the source
  800. variant.m_sources[shaderType] = std::move(finalSource);
  801. }
  802. return Error::NONE;
  803. }
  804. Bool ShaderProgramParser::rewriteMutation(WeakArray<MutatorValue> mutation) const
  805. {
  806. // Checks
  807. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  808. for(U32 i = 0; i < mutation.getSize(); ++i)
  809. {
  810. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]));
  811. }
  812. // Early exit
  813. if(mutation.getSize() == 0)
  814. {
  815. return false;
  816. }
  817. // Find if mutation exists
  818. for(const MutationRewrite& rewrite : m_mutationRewrites)
  819. {
  820. Bool found = true;
  821. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  822. {
  823. if(rewrite.m_records[i].m_valueFrom != mutation[rewrite.m_records[i].m_mutatorIndex])
  824. {
  825. found = false;
  826. break;
  827. }
  828. }
  829. if(found)
  830. {
  831. // Rewrite it
  832. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  833. {
  834. mutation[rewrite.m_records[i].m_mutatorIndex] = rewrite.m_records[i].m_valueTo;
  835. }
  836. return true;
  837. }
  838. }
  839. return false;
  840. }
  841. Bool ShaderProgramParser::mutatorHasValue(const ShaderProgramParserMutator& mutator, MutatorValue value)
  842. {
  843. for(MutatorValue v : mutator.m_values)
  844. {
  845. if(value == v)
  846. {
  847. return true;
  848. }
  849. }
  850. return false;
  851. }
  852. } // end namespace anki