ShaderProgramParser.cpp 26 KB

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