ShaderProgramParser.cpp 26 KB

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