ShaderProgramParser.cpp 27 KB

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