ShaderProgramParser.cpp 26 KB

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