ShaderProgramParser.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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_REF(type, alignment) \
  196. layout(buffer_reference, scalar, buffer_reference_align = (alignment)) buffer type##Ref \
  197. { \
  198. type m_value; \
  199. }
  200. #define ANKI_PADDING(bytes) U8 _padding_ ## __LINE__[bytes]
  201. layout(std140, row_major) uniform;
  202. layout(std140, row_major) buffer;
  203. )";
  204. static const U64 SHADER_HEADER_HASH = computeHash(SHADER_HEADER, sizeof(SHADER_HEADER));
  205. ShaderProgramParser::ShaderProgramParser(CString fname, ShaderProgramFilesystemInterface* fsystem,
  206. GenericMemoryPoolAllocator<U8> alloc,
  207. const ShaderCompilerOptions& compilerOptions)
  208. : m_alloc(alloc)
  209. , m_fname(alloc, fname)
  210. , m_fsystem(fsystem)
  211. , m_compilerOptions(compilerOptions)
  212. {
  213. }
  214. ShaderProgramParser::~ShaderProgramParser()
  215. {
  216. }
  217. void ShaderProgramParser::tokenizeLine(CString line, DynamicArrayAuto<StringAuto>& tokens) const
  218. {
  219. ANKI_ASSERT(line.getLength() > 0);
  220. StringAuto l(m_alloc, line);
  221. // Replace all tabs with spaces
  222. for(char& c : l)
  223. {
  224. if(c == '\t')
  225. {
  226. c = ' ';
  227. }
  228. }
  229. // Split
  230. StringListAuto spaceTokens(m_alloc);
  231. spaceTokens.splitString(l, ' ', false);
  232. // Create the array
  233. for(const String& s : spaceTokens)
  234. {
  235. tokens.emplaceBack(m_alloc, s);
  236. }
  237. }
  238. Error ShaderProgramParser::parsePragmaStart(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  239. {
  240. ANKI_ASSERT(begin && end);
  241. if(begin >= end)
  242. {
  243. ANKI_PP_ERROR_MALFORMED();
  244. }
  245. ShaderType shaderType = ShaderType::COUNT;
  246. if(*begin == "vert")
  247. {
  248. shaderType = ShaderType::VERTEX;
  249. }
  250. else if(*begin == "tessc")
  251. {
  252. shaderType = ShaderType::TESSELLATION_CONTROL;
  253. }
  254. else if(*begin == "tesse")
  255. {
  256. }
  257. else if(*begin == "geom")
  258. {
  259. shaderType = ShaderType::GEOMETRY;
  260. }
  261. else if(*begin == "frag")
  262. {
  263. shaderType = ShaderType::FRAGMENT;
  264. }
  265. else if(*begin == "comp")
  266. {
  267. shaderType = ShaderType::COMPUTE;
  268. }
  269. else if(*begin == "rgen")
  270. {
  271. shaderType = ShaderType::RAY_GEN;
  272. }
  273. else if(*begin == "ahit")
  274. {
  275. shaderType = ShaderType::ANY_HIT;
  276. }
  277. else if(*begin == "chit")
  278. {
  279. shaderType = ShaderType::CLOSEST_HIT;
  280. }
  281. else if(*begin == "miss")
  282. {
  283. shaderType = ShaderType::MISS;
  284. }
  285. else if(*begin == "int")
  286. {
  287. shaderType = ShaderType::INTERSECTION;
  288. }
  289. else if(*begin == "call")
  290. {
  291. shaderType = ShaderType::CALLABLE;
  292. }
  293. else
  294. {
  295. ANKI_PP_ERROR_MALFORMED();
  296. }
  297. m_codeLines.pushBackSprintf("#ifdef ANKI_%s_SHADER", SHADER_STAGE_NAMES[shaderType].cstr());
  298. ++begin;
  299. if(begin != end)
  300. {
  301. // Should be the last token
  302. ANKI_PP_ERROR_MALFORMED();
  303. }
  304. // Set the mask
  305. const ShaderTypeBit mask = ShaderTypeBit(1 << shaderType);
  306. if(!!(mask & m_shaderTypes))
  307. {
  308. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start <shader> appearing more than once");
  309. }
  310. m_shaderTypes |= mask;
  311. // Check bounds
  312. if(m_insideShader)
  313. {
  314. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma start before you close the previous pragma start");
  315. }
  316. m_insideShader = true;
  317. return Error::NONE;
  318. }
  319. Error ShaderProgramParser::parsePragmaEnd(const StringAuto* begin, const StringAuto* end, CString line, CString fname)
  320. {
  321. ANKI_ASSERT(begin && end);
  322. // Check tokens
  323. if(begin != end)
  324. {
  325. ANKI_PP_ERROR_MALFORMED();
  326. }
  327. // Check bounds
  328. if(!m_insideShader)
  329. {
  330. ANKI_PP_ERROR_MALFORMED_MSG("Can't have #pragma end before you open with a pragma start");
  331. }
  332. m_insideShader = false;
  333. // Write code
  334. m_codeLines.pushBack("#endif // Shader guard");
  335. return Error::NONE;
  336. }
  337. Error ShaderProgramParser::parsePragmaMutator(const StringAuto* begin, const StringAuto* end, CString line,
  338. CString fname)
  339. {
  340. ANKI_ASSERT(begin && end);
  341. if(begin >= end)
  342. {
  343. ANKI_PP_ERROR_MALFORMED();
  344. }
  345. m_mutators.emplaceBack(m_alloc);
  346. Mutator& mutator = m_mutators.getBack();
  347. // Name
  348. {
  349. if(begin >= end)
  350. {
  351. // Need to have a name
  352. ANKI_PP_ERROR_MALFORMED();
  353. }
  354. // Check for duplicate mutators
  355. for(U32 i = 0; i < m_mutators.getSize() - 1; ++i)
  356. {
  357. if(m_mutators[i].m_name == *begin)
  358. {
  359. ANKI_PP_ERROR_MALFORMED_MSG("Duplicate mutator");
  360. }
  361. }
  362. if(begin->getLength() > MAX_SHADER_BINARY_NAME_LENGTH)
  363. {
  364. ANKI_PP_ERROR_MALFORMED_MSG("Too big name");
  365. }
  366. mutator.m_name.create(begin->toCString());
  367. ++begin;
  368. }
  369. // Values
  370. {
  371. // Gather them
  372. for(; begin < end; ++begin)
  373. {
  374. MutatorValue value = 0;
  375. if(tokenIsComment(begin->toCString()))
  376. {
  377. break;
  378. }
  379. if(begin->toNumber(value))
  380. {
  381. ANKI_PP_ERROR_MALFORMED();
  382. }
  383. mutator.m_values.emplaceBack(value);
  384. }
  385. // Check for correct count
  386. if(mutator.m_values.getSize() < 2)
  387. {
  388. ANKI_PP_ERROR_MALFORMED_MSG("Mutator with less that 2 values doesn't make sense");
  389. }
  390. std::sort(mutator.m_values.getBegin(), mutator.m_values.getEnd());
  391. // Check for duplicates
  392. for(U32 i = 1; i < mutator.m_values.getSize(); ++i)
  393. {
  394. if(mutator.m_values[i - 1] == mutator.m_values[i])
  395. {
  396. ANKI_PP_ERROR_MALFORMED_MSG("Same value appeared more than once");
  397. }
  398. }
  399. }
  400. return Error::NONE;
  401. }
  402. Error ShaderProgramParser::parsePragmaLibraryName(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_libName.getLength() > 0)
  411. {
  412. ANKI_PP_ERROR_MALFORMED_MSG("Library name already set");
  413. }
  414. m_libName = *begin;
  415. return Error::NONE;
  416. }
  417. Error ShaderProgramParser::parsePragmaRayType(const StringAuto* begin, const StringAuto* end, CString line,
  418. CString fname)
  419. {
  420. ANKI_ASSERT(begin && end);
  421. if(begin >= end)
  422. {
  423. ANKI_PP_ERROR_MALFORMED();
  424. }
  425. if(m_rayType != MAX_U32)
  426. {
  427. ANKI_PP_ERROR_MALFORMED_MSG("Ray type already set");
  428. }
  429. ANKI_CHECK(begin->toNumber(m_rayType));
  430. if(m_rayType > 128)
  431. {
  432. ANKI_PP_ERROR_MALFORMED_MSG("Ray type has a very large value");
  433. }
  434. return Error::NONE;
  435. }
  436. Error ShaderProgramParser::parsePragmaRewriteMutation(const StringAuto* begin, const StringAuto* end, CString line,
  437. CString fname)
  438. {
  439. ANKI_ASSERT(begin && end);
  440. // Some basic sanity checks
  441. const U tokenCount = end - begin;
  442. constexpr U minTokenCount = 2 + 1 + 2; // Mutator + value + "to" + mutator + value
  443. if(tokenCount < minTokenCount)
  444. {
  445. ANKI_PP_ERROR_MALFORMED();
  446. }
  447. MutationRewrite& rewrite = *m_mutationRewrites.emplaceBack(m_alloc);
  448. Bool servingFrom = true;
  449. do
  450. {
  451. if(*begin == "to")
  452. {
  453. if(servingFrom == false)
  454. {
  455. ANKI_PP_ERROR_MALFORMED();
  456. }
  457. servingFrom = false;
  458. }
  459. else
  460. {
  461. // Mutator & value
  462. // Get mutator and value
  463. const CString mutatorName = *begin;
  464. ++begin;
  465. if(begin == end)
  466. {
  467. ANKI_PP_ERROR_MALFORMED();
  468. }
  469. const CString valueStr = *begin;
  470. MutatorValue value;
  471. if(valueStr.toNumber(value))
  472. {
  473. ANKI_PP_ERROR_MALFORMED_MSG("Malformed value");
  474. }
  475. // Get or create new record
  476. if(servingFrom)
  477. {
  478. MutationRewrite::Record& rec = *rewrite.m_records.emplaceBack();
  479. for(U32 i = 0; i < m_mutators.getSize(); ++i)
  480. {
  481. if(m_mutators[i].getName() == mutatorName)
  482. {
  483. rec.m_mutatorIndex = i;
  484. break;
  485. }
  486. }
  487. if(rec.m_mutatorIndex == MAX_U32)
  488. {
  489. ANKI_PP_ERROR_MALFORMED_MSG("Mutator not found");
  490. }
  491. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  492. {
  493. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  494. }
  495. rec.m_valueFrom = value;
  496. }
  497. else
  498. {
  499. Bool found = false;
  500. for(MutationRewrite::Record& rec : rewrite.m_records)
  501. {
  502. if(m_mutators[rec.m_mutatorIndex].m_name == mutatorName)
  503. {
  504. if(!mutatorHasValue(m_mutators[rec.m_mutatorIndex], value))
  505. {
  506. ANKI_PP_ERROR_MALFORMED_MSG("Incorect value for mutator");
  507. }
  508. rec.m_valueTo = value;
  509. found = true;
  510. break;
  511. }
  512. }
  513. if(!found)
  514. {
  515. ANKI_PP_ERROR_MALFORMED();
  516. }
  517. }
  518. }
  519. ++begin;
  520. } while(begin < end && !tokenIsComment(*begin));
  521. // Sort for some later cross checking
  522. std::sort(rewrite.m_records.getBegin(), rewrite.m_records.getEnd(),
  523. [](const MutationRewrite::Record& a, const MutationRewrite::Record& b) {
  524. return a.m_mutatorIndex < b.m_mutatorIndex;
  525. });
  526. // More cross checking
  527. for(U32 i = 1; i < rewrite.m_records.getSize(); ++i)
  528. {
  529. if(rewrite.m_records[i - 1].m_mutatorIndex == rewrite.m_records[i].m_mutatorIndex)
  530. {
  531. ANKI_PP_ERROR_MALFORMED_MSG("Mutator appeared more than once");
  532. }
  533. }
  534. for(U32 i = 0; i < m_mutationRewrites.getSize() - 1; ++i)
  535. {
  536. const MutationRewrite& other = m_mutationRewrites[i];
  537. if(other.m_records.getSize() != rewrite.m_records.getSize())
  538. {
  539. continue;
  540. }
  541. Bool same = true;
  542. for(U32 j = 0; j < rewrite.m_records.getSize(); ++j)
  543. {
  544. if(rewrite.m_records[j] != other.m_records[j])
  545. {
  546. same = false;
  547. break;
  548. }
  549. }
  550. if(same)
  551. {
  552. ANKI_PP_ERROR_MALFORMED_MSG("Mutation already exists");
  553. }
  554. }
  555. return Error::NONE;
  556. }
  557. Error ShaderProgramParser::parseInclude(const StringAuto* begin, const StringAuto* end, CString line, CString fname,
  558. U32 depth)
  559. {
  560. // Gather the path
  561. StringAuto path(m_alloc);
  562. for(; begin < end; ++begin)
  563. {
  564. path.append(*begin);
  565. }
  566. if(path.isEmpty())
  567. {
  568. ANKI_PP_ERROR_MALFORMED();
  569. }
  570. // Check
  571. const char firstChar = path[0];
  572. const char lastChar = path[path.getLength() - 1];
  573. if((firstChar == '\"' && lastChar == '\"') || (firstChar == '<' && lastChar == '>'))
  574. {
  575. StringAuto fname2(m_alloc);
  576. fname2.create(path.begin() + 1, path.begin() + path.getLength() - 1);
  577. const Bool dontIgnore =
  578. fname2.find("AnKi/Shaders/") != String::NPOS || fname2.find("ThirdParty/") != String::NPOS;
  579. if(!dontIgnore)
  580. {
  581. // The shaders can't include C++ files. Ignore the include
  582. return Error::NONE;
  583. }
  584. if(parseFile(fname2, depth + 1))
  585. {
  586. ANKI_PP_ERROR_MALFORMED_MSG("Error parsing include. See previous errors");
  587. }
  588. }
  589. else
  590. {
  591. ANKI_PP_ERROR_MALFORMED();
  592. }
  593. return Error::NONE;
  594. }
  595. Error ShaderProgramParser::parseLine(CString line, CString fname, Bool& foundPragmaOnce, U32 depth)
  596. {
  597. // Tokenize
  598. DynamicArrayAuto<StringAuto> tokens(m_alloc);
  599. tokenizeLine(line, tokens);
  600. ANKI_ASSERT(tokens.getSize() > 0);
  601. const StringAuto* token = tokens.getBegin();
  602. const StringAuto* end = tokens.getEnd();
  603. // Skip the hash
  604. Bool foundAloneHash = false;
  605. if(*token == "#")
  606. {
  607. ++token;
  608. foundAloneHash = true;
  609. }
  610. if((token < end) && ((foundAloneHash && *token == "include") || *token == "#include"))
  611. {
  612. // We _must_ have an #include
  613. ANKI_CHECK(parseInclude(token + 1, end, line, fname, depth));
  614. }
  615. else if((token < end) && ((foundAloneHash && *token == "pragma") || *token == "#pragma"))
  616. {
  617. // We may have a #pragma once or a #pragma anki or something else
  618. ++token;
  619. if(*token == "once")
  620. {
  621. // Pragma once
  622. if(foundPragmaOnce)
  623. {
  624. ANKI_PP_ERROR_MALFORMED_MSG("Can't have more than one #pragma once per file");
  625. }
  626. if(token + 1 != end)
  627. {
  628. ANKI_PP_ERROR_MALFORMED();
  629. }
  630. // Add the guard unique for this file
  631. foundPragmaOnce = true;
  632. const U64 hash = fname.computeHash();
  633. m_codeLines.pushBackSprintf("#ifndef _ANKI_INCL_GUARD_%llu\n"
  634. "#define _ANKI_INCL_GUARD_%llu",
  635. hash, hash);
  636. }
  637. else if(*token == "anki")
  638. {
  639. // Must be a #pragma anki
  640. ++token;
  641. if(*token == "mutator")
  642. {
  643. ANKI_CHECK(parsePragmaMutator(token + 1, end, line, fname));
  644. }
  645. else if(*token == "start")
  646. {
  647. ANKI_CHECK(parsePragmaStart(token + 1, end, line, fname));
  648. }
  649. else if(*token == "end")
  650. {
  651. ANKI_CHECK(parsePragmaEnd(token + 1, end, line, fname));
  652. }
  653. else if(*token == "rewrite_mutation")
  654. {
  655. ANKI_CHECK(parsePragmaRewriteMutation(token + 1, end, line, fname));
  656. }
  657. else if(*token == "library")
  658. {
  659. ANKI_CHECK(parsePragmaLibraryName(token + 1, end, line, fname));
  660. }
  661. else if(*token == "ray_type")
  662. {
  663. ANKI_CHECK(parsePragmaRayType(token + 1, end, line, fname));
  664. }
  665. else
  666. {
  667. ANKI_PP_ERROR_MALFORMED();
  668. }
  669. // Add the line as a comment because of hashing of the source
  670. m_codeLines.pushBackSprintf("//%s", line.cstr());
  671. }
  672. else
  673. {
  674. // Some other pragma
  675. ANKI_SHADER_COMPILER_LOGW("Ignoring: %s", line.cstr());
  676. m_codeLines.pushBack(line);
  677. }
  678. }
  679. else
  680. {
  681. // Ignore
  682. m_codeLines.pushBack(line);
  683. }
  684. return Error::NONE;
  685. }
  686. Error ShaderProgramParser::parseFile(CString fname, U32 depth)
  687. {
  688. // First check the depth
  689. if(depth > MAX_INCLUDE_DEPTH)
  690. {
  691. ANKI_SHADER_COMPILER_LOGE("The include depth is too high. Probably circular includance");
  692. }
  693. Bool foundPragmaOnce = false;
  694. // Load file in lines
  695. StringAuto txt(m_alloc);
  696. ANKI_CHECK(m_fsystem->readAllText(fname, txt));
  697. StringListAuto lines(m_alloc);
  698. lines.splitString(txt.toCString(), '\n');
  699. if(lines.getSize() < 1)
  700. {
  701. ANKI_SHADER_COMPILER_LOGE("Source is empty");
  702. }
  703. // Parse lines
  704. for(const String& line : lines)
  705. {
  706. if(line.find("pragma") != CString::NPOS || line.find("include") != CString::NPOS)
  707. {
  708. // Possibly a preprocessor directive we care
  709. ANKI_CHECK(parseLine(line.toCString(), fname, foundPragmaOnce, depth));
  710. }
  711. else
  712. {
  713. // Just append the line
  714. m_codeLines.pushBack(line.toCString());
  715. }
  716. }
  717. if(foundPragmaOnce)
  718. {
  719. // Append the guard
  720. m_codeLines.pushBack("#endif // Include guard");
  721. }
  722. return Error::NONE;
  723. }
  724. Error ShaderProgramParser::parse()
  725. {
  726. ANKI_ASSERT(!m_fname.isEmpty());
  727. ANKI_ASSERT(m_codeLines.isEmpty());
  728. const CString fname = m_fname;
  729. // Parse recursively
  730. ANKI_CHECK(parseFile(fname, 0));
  731. // Checks
  732. {
  733. if(!!(m_shaderTypes & ShaderTypeBit::COMPUTE))
  734. {
  735. if(m_shaderTypes != ShaderTypeBit::COMPUTE)
  736. {
  737. ANKI_SHADER_COMPILER_LOGE("Can't combine compute shader with other types of shaders");
  738. return Error::USER_DATA;
  739. }
  740. }
  741. else if(!!(m_shaderTypes & ShaderTypeBit::ALL_GRAPHICS))
  742. {
  743. if(!(m_shaderTypes & ShaderTypeBit::VERTEX))
  744. {
  745. ANKI_SHADER_COMPILER_LOGE("Missing vertex shader");
  746. return Error::USER_DATA;
  747. }
  748. if(!(m_shaderTypes & ShaderTypeBit::FRAGMENT))
  749. {
  750. ANKI_SHADER_COMPILER_LOGE("Missing fragment shader");
  751. return Error::USER_DATA;
  752. }
  753. }
  754. if(m_insideShader)
  755. {
  756. ANKI_SHADER_COMPILER_LOGE("Forgot a \"pragma anki end\"");
  757. return Error::USER_DATA;
  758. }
  759. }
  760. // Create the code lines
  761. if(m_codeLines.getSize())
  762. {
  763. m_codeLines.join("\n", m_codeSource);
  764. m_codeLines.destroy();
  765. }
  766. // Create the hash
  767. {
  768. if(m_codeSource.getLength())
  769. {
  770. m_codeSourceHash = appendHash(m_codeSource.getBegin(), m_codeSource.getLength(), SHADER_HEADER_HASH);
  771. }
  772. if(m_libName.getLength() > 0)
  773. {
  774. m_codeSourceHash = appendHash(m_libName.getBegin(), m_libName.getLength(), m_codeSourceHash);
  775. }
  776. m_codeSourceHash = appendHash(&m_rayType, sizeof(m_rayType), m_codeSourceHash);
  777. }
  778. return Error::NONE;
  779. }
  780. void ShaderProgramParser::generateAnkiShaderHeader(ShaderType shaderType, const ShaderCompilerOptions& compilerOptions,
  781. StringAuto& header)
  782. {
  783. header.sprintf(SHADER_HEADER, SHADER_STAGE_NAMES[shaderType].cstr(), ANKI_OS_ANDROID, ANKI_OS_WINDOWS,
  784. ANKI_OS_LINUX, compilerOptions.m_bindlessLimits.m_bindlessTextureCount,
  785. compilerOptions.m_bindlessLimits.m_bindlessImageCount);
  786. }
  787. Error ShaderProgramParser::generateVariant(ConstWeakArray<MutatorValue> mutation,
  788. ShaderProgramParserVariant& variant) const
  789. {
  790. // Sanity checks
  791. ANKI_ASSERT(m_codeSource.getLength() > 0);
  792. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  793. for(U32 i = 0; i < mutation.getSize(); ++i)
  794. {
  795. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]) && "Value not found");
  796. }
  797. // Init variant
  798. ::new(&variant) ShaderProgramParserVariant();
  799. variant.m_alloc = m_alloc;
  800. // Create the mutator defines
  801. StringAuto mutatorDefines(m_alloc);
  802. for(U32 i = 0; i < mutation.getSize(); ++i)
  803. {
  804. mutatorDefines.append(StringAuto(m_alloc).sprintf("#define %s %d\n", m_mutators[i].m_name.cstr(), mutation[i]));
  805. }
  806. // Generate souce per stage
  807. for(ShaderType shaderType : EnumIterable<ShaderType>())
  808. {
  809. if(!(ShaderTypeBit(1u << shaderType) & m_shaderTypes))
  810. {
  811. continue;
  812. }
  813. // Create the header
  814. StringAuto header(m_alloc);
  815. generateAnkiShaderHeader(shaderType, m_compilerOptions, header);
  816. // Create the final source without the bindings
  817. StringAuto finalSource(m_alloc);
  818. finalSource.append(header);
  819. finalSource.append(mutatorDefines);
  820. finalSource.append(m_codeSource);
  821. // Move the source
  822. variant.m_sources[shaderType] = std::move(finalSource);
  823. }
  824. return Error::NONE;
  825. }
  826. Bool ShaderProgramParser::rewriteMutation(WeakArray<MutatorValue> mutation) const
  827. {
  828. // Checks
  829. ANKI_ASSERT(mutation.getSize() == m_mutators.getSize());
  830. for(U32 i = 0; i < mutation.getSize(); ++i)
  831. {
  832. ANKI_ASSERT(mutatorHasValue(m_mutators[i], mutation[i]));
  833. }
  834. // Early exit
  835. if(mutation.getSize() == 0)
  836. {
  837. return false;
  838. }
  839. // Find if mutation exists
  840. for(const MutationRewrite& rewrite : m_mutationRewrites)
  841. {
  842. Bool found = true;
  843. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  844. {
  845. if(rewrite.m_records[i].m_valueFrom != mutation[rewrite.m_records[i].m_mutatorIndex])
  846. {
  847. found = false;
  848. break;
  849. }
  850. }
  851. if(found)
  852. {
  853. // Rewrite it
  854. for(U32 i = 0; i < rewrite.m_records.getSize(); ++i)
  855. {
  856. mutation[rewrite.m_records[i].m_mutatorIndex] = rewrite.m_records[i].m_valueTo;
  857. }
  858. return true;
  859. }
  860. }
  861. return false;
  862. }
  863. Bool ShaderProgramParser::mutatorHasValue(const ShaderProgramParserMutator& mutator, MutatorValue value)
  864. {
  865. for(MutatorValue v : mutator.m_values)
  866. {
  867. if(value == v)
  868. {
  869. return true;
  870. }
  871. }
  872. return false;
  873. }
  874. } // end namespace anki