ShaderProgramParser.cpp 25 KB

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