shaderc_spirv.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. /*
  2. * Copyright 2011-2021 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "shaderc.h"
  6. BX_PRAGMA_DIAGNOSTIC_PUSH()
  7. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4100) // error C4100: 'inclusionDepth' : unreferenced formal parameter
  8. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4265) // error C4265: 'spv::spirvbin_t': class has virtual functions, but destructor is not virtual
  9. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wattributes") // warning: attribute ignored
  10. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wdeprecated-declarations") // warning: ‘MSLVertexAttr’ is deprecated
  11. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits") // warning: comparison of unsigned expression in ‘< 0’ is always false
  12. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow") // warning: declaration of 'userData' shadows a member of 'glslang::TShader::Includer::IncludeResult'
  13. #define ENABLE_OPT 1
  14. #include <ShaderLang.h>
  15. #include <ResourceLimits.h>
  16. #include <SPIRV/SPVRemapper.h>
  17. #include <SPIRV/GlslangToSpv.h>
  18. #include <webgpu/webgpu_cpp.h>
  19. #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
  20. #include <spirv_msl.hpp>
  21. #include <spirv_reflect.hpp>
  22. #include <spirv-tools/optimizer.hpp>
  23. BX_PRAGMA_DIAGNOSTIC_POP()
  24. namespace bgfx
  25. {
  26. static bx::DefaultAllocator s_allocator;
  27. bx::AllocatorI* g_allocator = &s_allocator;
  28. struct TinyStlAllocator
  29. {
  30. static void* static_allocate(size_t _bytes);
  31. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  32. };
  33. void* TinyStlAllocator::static_allocate(size_t _bytes)
  34. {
  35. return BX_ALLOC(g_allocator, _bytes);
  36. }
  37. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  38. {
  39. if (NULL != _ptr)
  40. {
  41. BX_FREE(g_allocator, _ptr);
  42. }
  43. }
  44. } // namespace bgfx
  45. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  46. #include <tinystl/allocator.h>
  47. #include <tinystl/string.h>
  48. #include <tinystl/unordered_map.h>
  49. #include <tinystl/vector.h>
  50. namespace stl = tinystl;
  51. #include "../../src/shader.h"
  52. #include "../../src/shader_spirv.h"
  53. #include "../../3rdparty/khronos/vulkan-local/vulkan.h"
  54. namespace bgfx { namespace spirv
  55. {
  56. const TBuiltInResource resourceLimits =
  57. {
  58. 32, // MaxLights
  59. 6, // MaxClipPlanes
  60. 32, // MaxTextureUnits
  61. 32, // MaxTextureCoords
  62. 64, // MaxVertexAttribs
  63. 4096, // MaxVertexUniformComponents
  64. 64, // MaxVaryingFloats
  65. 32, // MaxVertexTextureImageUnits
  66. 80, // MaxCombinedTextureImageUnits
  67. 32, // MaxTextureImageUnits
  68. 4096, // MaxFragmentUniformComponents
  69. 32, // MaxDrawBuffers
  70. 128, // MaxVertexUniformVectors
  71. 8, // MaxVaryingVectors
  72. 16, // MaxFragmentUniformVectors
  73. 16, // MaxVertexOutputVectors
  74. 15, // MaxFragmentInputVectors
  75. -8, // MinProgramTexelOffset
  76. 7, // MaxProgramTexelOffset
  77. 8, // MaxClipDistances
  78. 65535, // MaxComputeWorkGroupCountX
  79. 65535, // MaxComputeWorkGroupCountY
  80. 65535, // MaxComputeWorkGroupCountZ
  81. 1024, // MaxComputeWorkGroupSizeX
  82. 1024, // MaxComputeWorkGroupSizeY
  83. 64, // MaxComputeWorkGroupSizeZ
  84. 1024, // MaxComputeUniformComponents
  85. 16, // MaxComputeTextureImageUnits
  86. 8, // MaxComputeImageUniforms
  87. 8, // MaxComputeAtomicCounters
  88. 1, // MaxComputeAtomicCounterBuffers
  89. 60, // MaxVaryingComponents
  90. 64, // MaxVertexOutputComponents
  91. 64, // MaxGeometryInputComponents
  92. 128, // MaxGeometryOutputComponents
  93. 128, // MaxFragmentInputComponents
  94. 8, // MaxImageUnits
  95. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  96. 8, // MaxCombinedShaderOutputResources
  97. 0, // MaxImageSamples
  98. 0, // MaxVertexImageUniforms
  99. 0, // MaxTessControlImageUniforms
  100. 0, // MaxTessEvaluationImageUniforms
  101. 0, // MaxGeometryImageUniforms
  102. 8, // MaxFragmentImageUniforms
  103. 8, // MaxCombinedImageUniforms
  104. 16, // MaxGeometryTextureImageUnits
  105. 256, // MaxGeometryOutputVertices
  106. 1024, // MaxGeometryTotalOutputComponents
  107. 1024, // MaxGeometryUniformComponents
  108. 64, // MaxGeometryVaryingComponents
  109. 128, // MaxTessControlInputComponents
  110. 128, // MaxTessControlOutputComponents
  111. 16, // MaxTessControlTextureImageUnits
  112. 1024, // MaxTessControlUniformComponents
  113. 4096, // MaxTessControlTotalOutputComponents
  114. 128, // MaxTessEvaluationInputComponents
  115. 128, // MaxTessEvaluationOutputComponents
  116. 16, // MaxTessEvaluationTextureImageUnits
  117. 1024, // MaxTessEvaluationUniformComponents
  118. 120, // MaxTessPatchComponents
  119. 32, // MaxPatchVertices
  120. 64, // MaxTessGenLevel
  121. 16, // MaxViewports
  122. 0, // MaxVertexAtomicCounters
  123. 0, // MaxTessControlAtomicCounters
  124. 0, // MaxTessEvaluationAtomicCounters
  125. 0, // MaxGeometryAtomicCounters
  126. 8, // MaxFragmentAtomicCounters
  127. 8, // MaxCombinedAtomicCounters
  128. 1, // MaxAtomicCounterBindings
  129. 0, // MaxVertexAtomicCounterBuffers
  130. 0, // MaxTessControlAtomicCounterBuffers
  131. 0, // MaxTessEvaluationAtomicCounterBuffers
  132. 0, // MaxGeometryAtomicCounterBuffers
  133. 1, // MaxFragmentAtomicCounterBuffers
  134. 1, // MaxCombinedAtomicCounterBuffers
  135. 16384, // MaxAtomicCounterBufferSize
  136. 4, // MaxTransformFeedbackBuffers
  137. 64, // MaxTransformFeedbackInterleavedComponents
  138. 8, // MaxCullDistances
  139. 8, // MaxCombinedClipAndCullDistances
  140. 4, // MaxSamples
  141. 0, // maxMeshOutputVerticesNV
  142. 0, // maxMeshOutputPrimitivesNV
  143. 0, // maxMeshWorkGroupSizeX_NV
  144. 0, // maxMeshWorkGroupSizeY_NV
  145. 0, // maxMeshWorkGroupSizeZ_NV
  146. 0, // maxTaskWorkGroupSizeX_NV
  147. 0, // maxTaskWorkGroupSizeY_NV
  148. 0, // maxTaskWorkGroupSizeZ_NV
  149. 0, // maxMeshViewCountNV
  150. 0, // maxDualSourceDrawBuffersEXT
  151. { // limits
  152. true, // nonInductiveForLoops
  153. true, // whileLoops
  154. true, // doWhileLoops
  155. true, // generalUniformIndexing
  156. true, // generalAttributeMatrixVectorIndexing
  157. true, // generalVaryingIndexing
  158. true, // generalSamplerIndexing
  159. true, // generalVariableIndexing
  160. true, // generalConstantMatrixVectorIndexing
  161. },
  162. };
  163. bool printAsm(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  164. {
  165. BX_UNUSED(_userData);
  166. char temp[512];
  167. toString(temp, sizeof(temp), _instruction);
  168. BX_TRACE("%5d: %s", _offset, temp);
  169. return true;
  170. }
  171. bgfx::TextureComponentType::Enum SpirvCrossBaseTypeToFormatType(spirv_cross::SPIRType::BaseType _type)
  172. {
  173. switch (_type)
  174. {
  175. case spirv_cross::SPIRType::Float:
  176. return bgfx::TextureComponentType::Float;
  177. case spirv_cross::SPIRType::Int:
  178. return bgfx::TextureComponentType::Int;
  179. case spirv_cross::SPIRType::UInt:
  180. return bgfx::TextureComponentType::Uint;
  181. default:
  182. return bgfx::TextureComponentType::Float;
  183. }
  184. }
  185. bgfx::TextureDimension::Enum SpirvDimToTextureViewDimension(spv::Dim _dim, bool _arrayed)
  186. {
  187. switch (_dim)
  188. {
  189. case spv::Dim::Dim1D:
  190. return bgfx::TextureDimension::Dimension1D;
  191. case spv::Dim::Dim2D:
  192. return _arrayed
  193. ? bgfx::TextureDimension::Dimension2DArray
  194. : bgfx::TextureDimension::Dimension2D
  195. ;
  196. case spv::Dim::Dim3D:
  197. return bgfx::TextureDimension::Dimension3D;
  198. case spv::Dim::DimCube:
  199. return _arrayed
  200. ? bgfx::TextureDimension::DimensionCubeArray
  201. : bgfx::TextureDimension::DimensionCube
  202. ;
  203. default:
  204. BX_ASSERT(false, "Unknown texture dimension %d", _dim);
  205. return bgfx::TextureDimension::Dimension2D;
  206. }
  207. }
  208. struct SpvReflection
  209. {
  210. struct TypeId
  211. {
  212. enum Enum
  213. {
  214. Void,
  215. Bool,
  216. Int32,
  217. Int64,
  218. Uint32,
  219. Uint64,
  220. Float,
  221. Double,
  222. Vector,
  223. Matrix,
  224. Count
  225. };
  226. TypeId()
  227. : baseType(Enum::Count)
  228. , type(Enum::Count)
  229. , numComponents(0)
  230. {
  231. }
  232. Enum baseType;
  233. Enum type;
  234. uint32_t numComponents;
  235. stl::string toString()
  236. {
  237. stl::string result;
  238. switch (type)
  239. {
  240. case Float:
  241. result.append("float");
  242. break;
  243. case Vector:
  244. bx::stringPrintf(result, "vec%d"
  245. , numComponents
  246. );
  247. break;
  248. case Matrix:
  249. bx::stringPrintf(result, "mat%d"
  250. , numComponents
  251. );
  252. default:
  253. break;
  254. }
  255. return result;
  256. }
  257. };
  258. struct Id
  259. {
  260. struct Variable
  261. {
  262. Variable()
  263. : decoration(SpvDecoration::Count)
  264. , builtin(SpvBuiltin::Count)
  265. , storageClass(SpvStorageClass::Count)
  266. , location(UINT32_MAX)
  267. , offset(UINT32_MAX)
  268. , type(UINT32_MAX)
  269. {
  270. }
  271. stl::string name;
  272. SpvDecoration::Enum decoration;
  273. SpvBuiltin::Enum builtin;
  274. SpvStorageClass::Enum storageClass;
  275. uint32_t location;
  276. uint32_t offset;
  277. uint32_t type;
  278. };
  279. typedef stl::vector<Variable> MemberArray;
  280. Variable var;
  281. MemberArray members;
  282. };
  283. typedef stl::unordered_map<uint32_t, TypeId> TypeIdMap;
  284. typedef stl::unordered_map<uint32_t, Id> IdMap;
  285. TypeIdMap typeIdMap;
  286. IdMap idMap;
  287. stl::string getTypeName(uint32_t _typeId)
  288. {
  289. return getTypeId(_typeId).toString();
  290. }
  291. Id& getId(uint32_t _id)
  292. {
  293. IdMap::iterator it = idMap.find(_id);
  294. if (it == idMap.end() )
  295. {
  296. Id id;
  297. stl::pair<IdMap::iterator, bool> result = idMap.insert(stl::make_pair(_id, id) );
  298. it = result.first;
  299. }
  300. return it->second;
  301. }
  302. Id::Variable& get(uint32_t _id, uint32_t _idx)
  303. {
  304. Id& id = getId(_id);
  305. id.members.resize(bx::uint32_max(_idx+1, uint32_t(id.members.size() ) ) );
  306. return id.members[_idx];
  307. }
  308. TypeId& getTypeId(uint32_t _id)
  309. {
  310. TypeIdMap::iterator it = typeIdMap.find(_id);
  311. if (it == typeIdMap.end() )
  312. {
  313. TypeId id;
  314. stl::pair<TypeIdMap::iterator, bool> result = typeIdMap.insert(stl::make_pair(_id, id) );
  315. it = result.first;
  316. }
  317. return it->second;
  318. }
  319. void update(uint32_t _id, const stl::string& _name)
  320. {
  321. getId(_id).var.name = _name;
  322. }
  323. BX_NO_INLINE void update(Id::Variable& _variable, SpvDecoration::Enum _decoration, uint32_t _literal)
  324. {
  325. _variable.decoration = _decoration;
  326. switch (_decoration)
  327. {
  328. case SpvDecoration::Location:
  329. _variable.location = _literal;
  330. break;
  331. case SpvDecoration::Offset:
  332. _variable.offset = _literal;
  333. break;
  334. case SpvDecoration::BuiltIn:
  335. _variable.builtin = SpvBuiltin::Enum(_literal);
  336. break;
  337. default:
  338. break;
  339. }
  340. }
  341. BX_NO_INLINE void update(Id::Variable& _variable, uint32_t _type, SpvStorageClass::Enum _storageClass)
  342. {
  343. _variable.type = _type;
  344. _variable.storageClass = _storageClass;
  345. }
  346. void update(uint32_t _id, SpvDecoration::Enum _decoration, uint32_t _literal)
  347. {
  348. update(getId(_id).var, _decoration, _literal);
  349. }
  350. void update(uint32_t _id, uint32_t _type, SpvStorageClass::Enum _storageClass)
  351. {
  352. update(getId(_id).var, _type, _storageClass);
  353. }
  354. void update(uint32_t _id, uint32_t _idx, const stl::string& _name)
  355. {
  356. Id::Variable& var = get(_id, _idx);
  357. var.name = _name;
  358. }
  359. BX_NO_INLINE void update(uint32_t _id, uint32_t _idx, SpvDecoration::Enum _decoration, uint32_t _literal)
  360. {
  361. update(get(_id, _idx), _decoration, _literal);
  362. }
  363. void update(uint32_t _id, TypeId::Enum _type)
  364. {
  365. TypeId& type = getTypeId(_id);
  366. type.type = _type;
  367. }
  368. void update(uint32_t _id, TypeId::Enum _type, uint32_t _baseTypeId, uint32_t _numComonents)
  369. {
  370. TypeId& type = getTypeId(_id);
  371. type.type = _type;
  372. type.baseType = getTypeId(_baseTypeId).type;
  373. type.numComponents = _numComonents;
  374. }
  375. };
  376. bool spvParse(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  377. {
  378. BX_UNUSED(_offset);
  379. SpvReflection* spv = (SpvReflection*)_userData;
  380. switch (_instruction.opcode)
  381. {
  382. case SpvOpcode::Name:
  383. spv->update(_instruction.result
  384. , _instruction.operand[0].literalString
  385. );
  386. break;
  387. case SpvOpcode::Decorate:
  388. spv->update(_instruction.operand[0].data
  389. , SpvDecoration::Enum(_instruction.operand[1].data)
  390. , _instruction.operand[2].data
  391. );
  392. break;
  393. case SpvOpcode::MemberName:
  394. spv->update(_instruction.result
  395. , _instruction.operand[0].data
  396. , _instruction.operand[1].literalString
  397. );
  398. break;
  399. case SpvOpcode::MemberDecorate:
  400. spv->update(_instruction.operand[0].data
  401. , _instruction.operand[1].data
  402. , SpvDecoration::Enum(_instruction.operand[2].data)
  403. , _instruction.operand[3].data
  404. );
  405. break;
  406. case SpvOpcode::Variable:
  407. spv->update(_instruction.result
  408. , _instruction.type
  409. , SpvStorageClass::Enum(_instruction.operand[0].data)
  410. );
  411. break;
  412. case SpvOpcode::TypeVoid:
  413. spv->update(_instruction.result, SpvReflection::TypeId::Void);
  414. break;
  415. case SpvOpcode::TypeBool:
  416. spv->update(_instruction.result, SpvReflection::TypeId::Bool);
  417. break;
  418. case SpvOpcode::TypeInt:
  419. spv->update(_instruction.result
  420. , 32 == _instruction.operand[0].data
  421. ? 0 == _instruction.operand[1].data
  422. ? SpvReflection::TypeId::Uint32
  423. : SpvReflection::TypeId::Int32
  424. : 0 == _instruction.operand[1].data
  425. ? SpvReflection::TypeId::Uint64
  426. : SpvReflection::TypeId::Int64
  427. );
  428. break;
  429. case SpvOpcode::TypeFloat:
  430. spv->update(_instruction.result
  431. , 32 == _instruction.operand[0].data
  432. ? SpvReflection::TypeId::Float
  433. : SpvReflection::TypeId::Double
  434. );
  435. break;
  436. case SpvOpcode::TypeVector:
  437. spv->update(_instruction.result
  438. , SpvReflection::TypeId::Vector
  439. , _instruction.operand[0].data
  440. , _instruction.operand[1].data
  441. );
  442. break;
  443. case SpvOpcode::TypeMatrix:
  444. spv->update(_instruction.result
  445. , SpvReflection::TypeId::Matrix
  446. , _instruction.operand[0].data
  447. , _instruction.operand[1].data
  448. );
  449. break;
  450. case SpvOpcode::TypeImage:
  451. case SpvOpcode::TypeSampler:
  452. case SpvOpcode::TypeSampledImage:
  453. break;
  454. case SpvOpcode::TypeStruct:
  455. for (uint32_t ii = 0, num = _instruction.numOperands; ii < num; ++ii)
  456. {
  457. SpvReflection::Id::Variable& var = spv->get(_instruction.result, ii);
  458. var.type = _instruction.operand[ii].data;
  459. }
  460. break;
  461. default:
  462. break;
  463. }
  464. return true;
  465. }
  466. #define DBG(...) // bx::debugPrintf(__VA_ARGS__)
  467. void disassemble(bx::WriterI* _writer, bx::ReaderSeekerI* _reader, bx::Error* _err)
  468. {
  469. BX_UNUSED(_writer);
  470. uint32_t magic;
  471. bx::peek(_reader, magic);
  472. SpvReflection spvx;
  473. if (magic == SPV_CHUNK_HEADER)
  474. {
  475. SpirV spirv;
  476. read(_reader, spirv, _err);
  477. parse(spirv.shader, spvParse, &spvx, _err);
  478. for (SpvReflection::IdMap::const_iterator it = spvx.idMap.begin(), itEnd = spvx.idMap.end(); it != itEnd; ++it)
  479. {
  480. const SpvReflection::Id& id = it->second;
  481. uint32_t num = uint32_t(id.members.size() );
  482. if (0 < num
  483. && 0 != bx::strCmp(id.var.name.c_str(), "gl_PerVertex") )
  484. {
  485. DBG("%3d: %s %d %s\n"
  486. , it->first
  487. , id.var.name.c_str()
  488. , id.var.location
  489. , getName(id.var.storageClass)
  490. );
  491. DBG("{\n");
  492. for (uint32_t ii = 0; ii < num; ++ii)
  493. {
  494. const SpvReflection::Id::Variable& var = id.members[ii];
  495. DBG("\t\t%s %s %d %s\n"
  496. , spvx.getTypeName(var.type).c_str()
  497. , var.name.c_str()
  498. , var.offset
  499. , getName(var.storageClass)
  500. );
  501. BX_UNUSED(var);
  502. }
  503. DBG("}\n");
  504. }
  505. }
  506. }
  507. }
  508. static EShLanguage getLang(char _p)
  509. {
  510. switch (_p)
  511. {
  512. case 'c': return EShLangCompute;
  513. case 'f': return EShLangFragment;
  514. case 'v': return EShLangVertex;
  515. default: return EShLangCount;
  516. }
  517. }
  518. static const char* s_attribName[] =
  519. {
  520. "a_position",
  521. "a_normal",
  522. "a_tangent",
  523. "a_bitangent",
  524. "a_color0",
  525. "a_color1",
  526. "a_color2",
  527. "a_color3",
  528. "a_indices",
  529. "a_weight",
  530. "a_texcoord0",
  531. "a_texcoord1",
  532. "a_texcoord2",
  533. "a_texcoord3",
  534. "a_texcoord4",
  535. "a_texcoord5",
  536. "a_texcoord6",
  537. "a_texcoord7",
  538. };
  539. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  540. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  541. {
  542. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  543. {
  544. if (0 == bx::strCmp(s_attribName[ii], _name) )
  545. {
  546. return bgfx::Attrib::Enum(ii);
  547. }
  548. }
  549. return bgfx::Attrib::Count;
  550. }
  551. static const char* s_samplerTypes[] =
  552. {
  553. "BgfxSampler2D",
  554. "BgfxISampler2D",
  555. "BgfxUSampler2D",
  556. "BgfxSampler2DArray",
  557. "BgfxSampler2DShadow",
  558. "BgfxSampler2DArrayShadow",
  559. "BgfxSampler3D",
  560. "BgfxISampler3D",
  561. "BgfxUSampler3D",
  562. "BgfxSamplerCube",
  563. "BgfxSamplerCubeShadow",
  564. "BgfxSampler2DMS",
  565. };
  566. static uint16_t writeUniformArray(bx::WriterI* _writer, const UniformArray& uniforms, bool isFragmentShader)
  567. {
  568. uint16_t size = 0;
  569. uint16_t count = static_cast<uint16_t>(uniforms.size() );
  570. bx::write(_writer, count);
  571. uint32_t fragmentBit = isFragmentShader ? kUniformFragmentBit : 0;
  572. for (uint16_t ii = 0; ii < count; ++ii)
  573. {
  574. const Uniform& un = uniforms[ii];
  575. if ( (un.type & ~kUniformMask) > UniformType::End)
  576. {
  577. size = bx::max(size, (uint16_t)(un.regIndex + un.regCount*16) );
  578. }
  579. uint8_t nameSize = (uint8_t)un.name.size();
  580. bx::write(_writer, nameSize);
  581. bx::write(_writer, un.name.c_str(), nameSize);
  582. bx::write(_writer, uint8_t(un.type | fragmentBit) );
  583. bx::write(_writer, un.num);
  584. bx::write(_writer, un.regIndex);
  585. bx::write(_writer, un.regCount);
  586. bx::write(_writer, un.texComponent);
  587. bx::write(_writer, un.texDimension);
  588. BX_TRACE("%s, %s, %d, %d, %d"
  589. , un.name.c_str()
  590. , getUniformTypeName(un.type)
  591. , un.num
  592. , un.regIndex
  593. , un.regCount
  594. );
  595. }
  596. return size;
  597. }
  598. static spv_target_env getSpirvTargetVersion(uint32_t version)
  599. {
  600. switch (version)
  601. {
  602. case 1010:
  603. return SPV_ENV_VULKAN_1_0;
  604. case 1311:
  605. return SPV_ENV_VULKAN_1_1;
  606. case 1411:
  607. return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
  608. case 1512:
  609. return SPV_ENV_VULKAN_1_2;
  610. default:
  611. BX_ASSERT(0, "Unknown SPIR-V version requested. Returning SPV_ENV_VULKAN_1_0 as default.");
  612. return SPV_ENV_VULKAN_1_0;
  613. }
  614. }
  615. static glslang::EShTargetClientVersion getGlslangTargetVulkanVersion(uint32_t version)
  616. {
  617. switch (version)
  618. {
  619. case 1010:
  620. return glslang::EShTargetVulkan_1_0;
  621. case 1311:
  622. case 1411:
  623. return glslang::EShTargetVulkan_1_1;
  624. case 1512:
  625. return glslang::EShTargetVulkan_1_2;
  626. default:
  627. BX_ASSERT(0, "Unknown SPIR-V version requested. Returning EShTargetVulkan_1_0 as default.");
  628. return glslang::EShTargetVulkan_1_0;
  629. }
  630. }
  631. static glslang::EShTargetLanguageVersion getGlslangTargetSpirvVersion(uint32_t version)
  632. {
  633. switch (version)
  634. {
  635. case 1010:
  636. return glslang::EShTargetSpv_1_0;
  637. case 1311:
  638. return glslang::EShTargetSpv_1_3;
  639. case 1411:
  640. return glslang::EShTargetSpv_1_4;
  641. case 1512:
  642. return glslang::EShTargetSpv_1_5;
  643. default:
  644. BX_ASSERT(0, "Unknown SPIR-V version requested. Returning EShTargetSpv_1_0 as default.");
  645. return glslang::EShTargetSpv_1_0;
  646. }
  647. }
  648. /// This is the value used to fill out GLSLANG's SpvVersion object.
  649. /// The required value is that which is defined by GL_KHR_vulkan_glsl, which is defined here:
  650. /// https://github.com/KhronosGroup/GLSL/blob/master/extensions/khr/GL_KHR_vulkan_glsl.txt
  651. /// The value is 100.
  652. constexpr int s_GLSL_VULKAN_CLIENT_VERSION = 100;
  653. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  654. {
  655. BX_UNUSED(_version);
  656. glslang::InitializeProcess();
  657. EShLanguage stage = getLang(_options.shaderType);
  658. if (EShLangCount == stage)
  659. {
  660. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  661. return false;
  662. }
  663. glslang::TProgram* program = new glslang::TProgram;
  664. glslang::TShader* shader = new glslang::TShader(stage);
  665. EShMessages messages = EShMessages(0
  666. | EShMsgDefault
  667. | EShMsgReadHlsl
  668. | EShMsgVulkanRules
  669. | EShMsgSpvRules
  670. );
  671. shader->setEntryPoint("main");
  672. shader->setAutoMapBindings(true);
  673. shader->setEnvInput(glslang::EShSourceHlsl, stage, glslang::EShClientVulkan, s_GLSL_VULKAN_CLIENT_VERSION);
  674. shader->setEnvClient(glslang::EShClientVulkan, getGlslangTargetVulkanVersion(_version));
  675. shader->setEnvTarget(glslang::EShTargetSpv, getGlslangTargetSpirvVersion(_version));
  676. uint32_t bindingOffset = (stage == EShLanguage::EShLangFragment ? 48 : 0);
  677. shader->setShiftBinding(glslang::EResUbo, bindingOffset);
  678. shader->setShiftBinding(glslang::EResTexture, bindingOffset + 16);
  679. shader->setShiftBinding(glslang::EResSampler, bindingOffset + 32);
  680. shader->setShiftBinding(glslang::EResSsbo, bindingOffset + 16);
  681. shader->setShiftBinding(glslang::EResImage, bindingOffset + 32);
  682. const char* shaderStrings[] = { _code.c_str() };
  683. shader->setStrings(
  684. shaderStrings
  685. , BX_COUNTOF(shaderStrings)
  686. );
  687. bool compiled = shader->parse(&resourceLimits
  688. , 110
  689. , false
  690. , messages
  691. );
  692. bool linked = false;
  693. bool validated = true;
  694. if (!compiled)
  695. {
  696. const char* log = shader->getInfoLog();
  697. if (NULL != log)
  698. {
  699. int32_t source = 0;
  700. int32_t line = 0;
  701. int32_t column = 0;
  702. int32_t start = 0;
  703. int32_t end = INT32_MAX;
  704. bx::StringView err = bx::strFind(log, "ERROR:");
  705. bool found = false;
  706. if (!err.isEmpty() )
  707. {
  708. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  709. if (found)
  710. {
  711. ++line;
  712. }
  713. }
  714. if (found)
  715. {
  716. start = bx::uint32_imax(1, line-10);
  717. end = start + 20;
  718. }
  719. printCode(_code.c_str(), line, start, end, column);
  720. bx::printf("%s\n", log);
  721. }
  722. }
  723. else
  724. {
  725. program->addShader(shader);
  726. linked = true
  727. && program->link(messages)
  728. && program->mapIO()
  729. ;
  730. if (!linked)
  731. {
  732. const char* log = program->getInfoLog();
  733. if (NULL != log)
  734. {
  735. bx::printf("%s\n", log);
  736. }
  737. }
  738. else
  739. {
  740. program->buildReflection();
  741. if (_firstPass)
  742. {
  743. // first time through, we just find unused uniforms and get rid of them
  744. std::string output;
  745. struct Uniform
  746. {
  747. std::string name;
  748. std::string decl;
  749. };
  750. std::vector<Uniform> uniforms;
  751. bx::LineReader reader(_code.c_str() );
  752. while (!reader.isDone() )
  753. {
  754. bx::StringView strLine = reader.next();
  755. bool moved = false;
  756. bx::StringView str = strFind(strLine, "uniform ");
  757. if (!str.isEmpty() )
  758. {
  759. bool found = false;
  760. bool sampler = false;
  761. std::string name = "";
  762. // add to samplers
  763. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  764. {
  765. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  766. {
  767. found = true;
  768. sampler = true;
  769. break;
  770. }
  771. }
  772. if (!found)
  773. {
  774. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  775. {
  776. // matching lines like: uniform u_name;
  777. // we want to replace "uniform" with "static" so that it's no longer
  778. // included in the uniform blob that the application must upload
  779. // we can't just remove them, because unused functions might still reference
  780. // them and cause a compile error when they're gone
  781. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  782. {
  783. found = true;
  784. name = program->getUniformName(ii);
  785. break;
  786. }
  787. }
  788. }
  789. if (!found)
  790. {
  791. output.append(strLine.getPtr(), str.getPtr() );
  792. output += "static ";
  793. output.append(str.getTerm(), strLine.getTerm() );
  794. output += "\n";
  795. moved = true;
  796. }
  797. else if (!sampler)
  798. {
  799. Uniform uniform;
  800. uniform.name = name;
  801. uniform.decl = std::string(strLine.getPtr(), strLine.getTerm() );
  802. uniforms.push_back(uniform);
  803. moved = true;
  804. }
  805. }
  806. if (!moved)
  807. {
  808. output.append(strLine.getPtr(), strLine.getTerm() );
  809. output += "\n";
  810. }
  811. }
  812. std::string uniformBlock;
  813. uniformBlock += "cbuffer UniformBlock\n";
  814. uniformBlock += "{\n";
  815. for (const Uniform& uniform : uniforms)
  816. {
  817. uniformBlock += uniform.decl.substr(7 /* uniform */);
  818. uniformBlock += "\n";
  819. }
  820. uniformBlock += "};\n";
  821. output = uniformBlock + output;
  822. // recompile with the unused uniforms converted to statics
  823. delete program;
  824. delete shader;
  825. return compile(_options, _version, output.c_str(), _writer, false);
  826. }
  827. else
  828. {
  829. // second time, do nothing (todo remove)
  830. }
  831. UniformArray uniforms;
  832. {
  833. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  834. for (uint16_t ii = 0; ii < count; ++ii)
  835. {
  836. Uniform un;
  837. un.name = program->getUniformName(ii);
  838. un.num = 0;
  839. const uint32_t offset = program->getUniformBufferOffset(ii);
  840. un.regIndex = uint16_t(offset);
  841. un.regCount = uint16_t(program->getUniformArraySize(ii));
  842. switch (program->getUniformType(ii) )
  843. {
  844. case 0x1404: // GL_INT:
  845. un.type = UniformType::Sampler;
  846. break;
  847. case 0x8B52: // GL_FLOAT_VEC4:
  848. un.type = UniformType::Vec4;
  849. break;
  850. case 0x8B5B: // GL_FLOAT_MAT3:
  851. un.type = UniformType::Mat3;
  852. un.regCount *= 3;
  853. break;
  854. case 0x8B5C: // GL_FLOAT_MAT4:
  855. un.type = UniformType::Mat4;
  856. un.regCount *= 4;
  857. break;
  858. default:
  859. un.type = UniformType::End;
  860. break;
  861. }
  862. uniforms.push_back(un);
  863. }
  864. }
  865. if (g_verbose)
  866. {
  867. program->dumpReflection();
  868. }
  869. BX_UNUSED(spv::MemorySemanticsAllMemory);
  870. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  871. std::vector<uint32_t> spirv;
  872. glslang::SpvOptions options;
  873. options.disableOptimizer = false;
  874. glslang::GlslangToSpv(*intermediate, spirv, &options);
  875. spvtools::Optimizer opt(getSpirvTargetVersion(_version));
  876. auto print_msg_to_stderr = [](
  877. spv_message_level_t
  878. , const char*
  879. , const spv_position_t&
  880. , const char* m
  881. )
  882. {
  883. bx::printf("Error: %s\n", m);
  884. };
  885. opt.SetMessageConsumer(print_msg_to_stderr);
  886. opt.RegisterLegalizationPasses();
  887. spvtools::ValidatorOptions validatorOptions;
  888. validatorOptions.SetBeforeHlslLegalization(true);
  889. if (!opt.Run(
  890. spirv.data()
  891. , spirv.size()
  892. , &spirv
  893. , validatorOptions
  894. , false
  895. ) )
  896. {
  897. compiled = false;
  898. }
  899. else
  900. {
  901. bx::Error err;
  902. bx::WriterI* writer = bx::getDebugOut();
  903. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  904. disassemble(writer, &reader, &err);
  905. spirv_cross::CompilerReflection refl(spirv);
  906. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  907. if (g_verbose)
  908. {
  909. glslang::SpirvToolsDisassemble(std::cout, spirv, getSpirvTargetVersion(_version) );
  910. }
  911. // Loop through the separate_images, and extract the uniform names:
  912. for (auto &resource : resourcesrefl.separate_images)
  913. {
  914. std::string name = refl.get_name(resource.id);
  915. if (name.size() > 7
  916. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  917. {
  918. std::string uniform_name = name.substr(0, name.length() - 7);
  919. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  920. auto imageType = refl.get_type(resource.base_type_id).image;
  921. auto componentType = refl.get_type(imageType.type).basetype;
  922. bool isCompareSampler = false;
  923. for (auto& sampler : resourcesrefl.separate_samplers)
  924. {
  925. if (binding_index + 16 == refl.get_decoration(sampler.id, spv::Decoration::DecorationBinding) )
  926. {
  927. std::string samplerName = refl.get_name(sampler.id);
  928. isCompareSampler = refl.variable_is_depth_or_compare(sampler.id) || samplerName.find("Comparison") != std::string::npos;
  929. break;
  930. }
  931. }
  932. Uniform un;
  933. un.name = uniform_name;
  934. un.type = UniformType::Enum(UniformType::Sampler
  935. | kUniformSamplerBit
  936. | (isCompareSampler ? kUniformCompareBit : 0)
  937. );
  938. un.texComponent = textureComponentTypeToId(SpirvCrossBaseTypeToFormatType(componentType) );
  939. un.texDimension = textureDimensionToId(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  940. un.regIndex = binding_index;
  941. un.regCount = 0; // unused
  942. uniforms.push_back(un);
  943. }
  944. }
  945. // Loop through the storage_images, and extract the uniform names:
  946. for (auto &resource : resourcesrefl.storage_images)
  947. {
  948. std::string name = refl.get_name(resource.id);
  949. if (name.size() > 7
  950. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  951. {
  952. std::string uniform_name = name.substr(0, name.length() - 7);
  953. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  954. auto imageType = refl.get_type(resource.base_type_id).image;
  955. auto componentType = refl.get_type(imageType.type).basetype;
  956. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  957. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  958. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  959. : UniformType::End;
  960. Uniform un;
  961. un.name = uniform_name;
  962. un.type = type;
  963. un.texComponent = textureComponentTypeToId(SpirvCrossBaseTypeToFormatType(componentType) );
  964. un.texDimension = textureDimensionToId(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  965. un.regIndex = binding_index;
  966. un.regCount = descriptorTypeToId(DescriptorType::StorageImage);
  967. uniforms.push_back(un);
  968. }
  969. }
  970. // Loop through the storage buffer, and extract the uniform names:
  971. for (auto& resource : resourcesrefl.storage_buffers)
  972. {
  973. std::string name = refl.get_name(resource.id);
  974. for (auto& uniform : uniforms)
  975. {
  976. if (!bx::strFind(uniform.name.c_str(), name.c_str() ).isEmpty() )
  977. {
  978. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  979. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  980. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  981. : UniformType::End;
  982. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  983. uniform.name = name;
  984. uniform.type = type;
  985. uniform.regIndex = binding_index;
  986. uniform.regCount = descriptorTypeToId(DescriptorType::StorageBuffer);
  987. break;
  988. }
  989. }
  990. }
  991. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  992. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  993. {
  994. spirv_cross::CompilerMSL msl(std::move(spirv) );
  995. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  996. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  997. if (!entryPoints.empty() )
  998. {
  999. msl.rename_entry_point(
  1000. entryPoints[0].name
  1001. , "xlatMtlMain"
  1002. , entryPoints[0].execution_model
  1003. );
  1004. }
  1005. for (auto &resource : resources.uniform_buffers)
  1006. {
  1007. msl.set_name(resource.id, "_mtl_u");
  1008. }
  1009. for (auto &resource : resources.storage_buffers)
  1010. {
  1011. unsigned binding = msl.get_decoration(resource.id, spv::DecorationBinding);
  1012. msl.set_decoration(resource.id, spv::DecorationBinding, binding + 1);
  1013. }
  1014. for (auto &resource : resources.separate_images)
  1015. {
  1016. std::string name = msl.get_name(resource.id);
  1017. if (name.size() > 7
  1018. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  1019. {
  1020. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  1021. }
  1022. }
  1023. std::string source = msl.compile();
  1024. if ('c' == _options.shaderType)
  1025. {
  1026. for (int i = 0; i < 3; ++i)
  1027. {
  1028. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  1029. bx::write(_writer, dim);
  1030. }
  1031. }
  1032. uint32_t shaderSize = (uint32_t)source.size();
  1033. bx::write(_writer, shaderSize);
  1034. bx::write(_writer, source.c_str(), shaderSize);
  1035. uint8_t nul = 0;
  1036. bx::write(_writer, nul);
  1037. }
  1038. else
  1039. {
  1040. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  1041. bx::write(_writer, shaderSize);
  1042. bx::write(_writer, spirv.data(), shaderSize);
  1043. uint8_t nul = 0;
  1044. bx::write(_writer, nul);
  1045. }
  1046. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  1047. bx::write(_writer, numAttr);
  1048. for (uint8_t ii = 0; ii < numAttr; ++ii)
  1049. {
  1050. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  1051. if (bgfx::Attrib::Count != attr)
  1052. {
  1053. bx::write(_writer, bgfx::attribToId(attr) );
  1054. }
  1055. else
  1056. {
  1057. bx::write(_writer, uint16_t(UINT16_MAX) );
  1058. }
  1059. }
  1060. bx::write(_writer, size);
  1061. }
  1062. }
  1063. }
  1064. delete program;
  1065. delete shader;
  1066. glslang::FinalizeProcess();
  1067. return compiled && linked && validated;
  1068. }
  1069. } // namespace spirv
  1070. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  1071. {
  1072. return spirv::compile(_options, _version, _code, _writer, true);
  1073. }
  1074. } // namespace bgfx