shaderc_spirv.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. /*
  2. * Copyright 2011-2018 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("-Wshadow") // warning: declaration of 'userData' shadows a member of 'glslang::TShader::Includer::IncludeResult'
  10. #define ENABLE_OPT 1
  11. #include <ShaderLang.h>
  12. #include <ResourceLimits.h>
  13. #include <SPIRV/SPVRemapper.h>
  14. #include <SPIRV/GlslangToSpv.h>
  15. BX_PRAGMA_DIAGNOSTIC_POP()
  16. namespace bgfx
  17. {
  18. static bx::DefaultAllocator s_allocator;
  19. bx::AllocatorI* g_allocator = &s_allocator;
  20. struct TinyStlAllocator
  21. {
  22. static void* static_allocate(size_t _bytes);
  23. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  24. };
  25. void* TinyStlAllocator::static_allocate(size_t _bytes)
  26. {
  27. return BX_ALLOC(g_allocator, _bytes);
  28. }
  29. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  30. {
  31. if (NULL != _ptr)
  32. {
  33. BX_FREE(g_allocator, _ptr);
  34. }
  35. }
  36. } // namespace bgfx
  37. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  38. #include <tinystl/allocator.h>
  39. #include <tinystl/string.h>
  40. #include <tinystl/unordered_map.h>
  41. #include <tinystl/vector.h>
  42. namespace stl = tinystl;
  43. #include "../../src/shader_spirv.h"
  44. namespace bgfx { namespace spirv
  45. {
  46. const TBuiltInResource resourceLimits =
  47. {
  48. 32, // MaxLights
  49. 6, // MaxClipPlanes
  50. 32, // MaxTextureUnits
  51. 32, // MaxTextureCoords
  52. 64, // MaxVertexAttribs
  53. 4096, // MaxVertexUniformComponents
  54. 64, // MaxVaryingFloats
  55. 32, // MaxVertexTextureImageUnits
  56. 80, // MaxCombinedTextureImageUnits
  57. 32, // MaxTextureImageUnits
  58. 4096, // MaxFragmentUniformComponents
  59. 32, // MaxDrawBuffers
  60. 128, // MaxVertexUniformVectors
  61. 8, // MaxVaryingVectors
  62. 16, // MaxFragmentUniformVectors
  63. 16, // MaxVertexOutputVectors
  64. 15, // MaxFragmentInputVectors
  65. -8, // MinProgramTexelOffset
  66. 7, // MaxProgramTexelOffset
  67. 8, // MaxClipDistances
  68. 65535, // MaxComputeWorkGroupCountX
  69. 65535, // MaxComputeWorkGroupCountY
  70. 65535, // MaxComputeWorkGroupCountZ
  71. 1024, // MaxComputeWorkGroupSizeX
  72. 1024, // MaxComputeWorkGroupSizeY
  73. 64, // MaxComputeWorkGroupSizeZ
  74. 1024, // MaxComputeUniformComponents
  75. 16, // MaxComputeTextureImageUnits
  76. 8, // MaxComputeImageUniforms
  77. 8, // MaxComputeAtomicCounters
  78. 1, // MaxComputeAtomicCounterBuffers
  79. 60, // MaxVaryingComponents
  80. 64, // MaxVertexOutputComponents
  81. 64, // MaxGeometryInputComponents
  82. 128, // MaxGeometryOutputComponents
  83. 128, // MaxFragmentInputComponents
  84. 8, // MaxImageUnits
  85. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  86. 8, // MaxCombinedShaderOutputResources
  87. 0, // MaxImageSamples
  88. 0, // MaxVertexImageUniforms
  89. 0, // MaxTessControlImageUniforms
  90. 0, // MaxTessEvaluationImageUniforms
  91. 0, // MaxGeometryImageUniforms
  92. 8, // MaxFragmentImageUniforms
  93. 8, // MaxCombinedImageUniforms
  94. 16, // MaxGeometryTextureImageUnits
  95. 256, // MaxGeometryOutputVertices
  96. 1024, // MaxGeometryTotalOutputComponents
  97. 1024, // MaxGeometryUniformComponents
  98. 64, // MaxGeometryVaryingComponents
  99. 128, // MaxTessControlInputComponents
  100. 128, // MaxTessControlOutputComponents
  101. 16, // MaxTessControlTextureImageUnits
  102. 1024, // MaxTessControlUniformComponents
  103. 4096, // MaxTessControlTotalOutputComponents
  104. 128, // MaxTessEvaluationInputComponents
  105. 128, // MaxTessEvaluationOutputComponents
  106. 16, // MaxTessEvaluationTextureImageUnits
  107. 1024, // MaxTessEvaluationUniformComponents
  108. 120, // MaxTessPatchComponents
  109. 32, // MaxPatchVertices
  110. 64, // MaxTessGenLevel
  111. 16, // MaxViewports
  112. 0, // MaxVertexAtomicCounters
  113. 0, // MaxTessControlAtomicCounters
  114. 0, // MaxTessEvaluationAtomicCounters
  115. 0, // MaxGeometryAtomicCounters
  116. 8, // MaxFragmentAtomicCounters
  117. 8, // MaxCombinedAtomicCounters
  118. 1, // MaxAtomicCounterBindings
  119. 0, // MaxVertexAtomicCounterBuffers
  120. 0, // MaxTessControlAtomicCounterBuffers
  121. 0, // MaxTessEvaluationAtomicCounterBuffers
  122. 0, // MaxGeometryAtomicCounterBuffers
  123. 1, // MaxFragmentAtomicCounterBuffers
  124. 1, // MaxCombinedAtomicCounterBuffers
  125. 16384, // MaxAtomicCounterBufferSize
  126. 4, // MaxTransformFeedbackBuffers
  127. 64, // MaxTransformFeedbackInterleavedComponents
  128. 8, // MaxCullDistances
  129. 8, // MaxCombinedClipAndCullDistances
  130. 4, // MaxSamples
  131. { // limits
  132. 1, // nonInductiveForLoops
  133. 1, // whileLoops
  134. 1, // doWhileLoops
  135. 1, // generalUniformIndexing
  136. 1, // generalAttributeMatrixVectorIndexing
  137. 1, // generalVaryingIndexing
  138. 1, // generalSamplerIndexing
  139. 1, // generalVariableIndexing
  140. 1, // generalConstantMatrixVectorIndexing
  141. },
  142. };
  143. bool printAsm(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  144. {
  145. BX_UNUSED(_userData);
  146. char temp[512];
  147. toString(temp, sizeof(temp), _instruction);
  148. BX_TRACE("%5d: %s", _offset, temp);
  149. return true;
  150. }
  151. struct SpvReflection
  152. {
  153. struct TypeId
  154. {
  155. enum Enum
  156. {
  157. Void,
  158. Bool,
  159. Int32,
  160. Int64,
  161. Uint32,
  162. Uint64,
  163. Float,
  164. Double,
  165. Vector,
  166. Matrix,
  167. Count
  168. };
  169. TypeId()
  170. : baseType(Enum::Count)
  171. , type(Enum::Count)
  172. , numComponents(0)
  173. {
  174. }
  175. Enum baseType;
  176. Enum type;
  177. uint32_t numComponents;
  178. stl::string toString()
  179. {
  180. stl::string result;
  181. switch (type)
  182. {
  183. case Float:
  184. result.append("float");
  185. break;
  186. case Vector:
  187. bx::stringPrintf(result, "vec%d"
  188. , numComponents
  189. );
  190. break;
  191. case Matrix:
  192. bx::stringPrintf(result, "mat%d"
  193. , numComponents
  194. );
  195. default:
  196. break;
  197. }
  198. return result;
  199. }
  200. };
  201. struct Id
  202. {
  203. struct Variable
  204. {
  205. Variable()
  206. : decoration(SpvDecoration::Count)
  207. , builtin(SpvBuiltin::Count)
  208. , storageClass(SpvStorageClass::Count)
  209. , location(UINT32_MAX)
  210. , offset(UINT32_MAX)
  211. , type(UINT32_MAX)
  212. {
  213. }
  214. stl::string name;
  215. SpvDecoration::Enum decoration;
  216. SpvBuiltin::Enum builtin;
  217. SpvStorageClass::Enum storageClass;
  218. uint32_t location;
  219. uint32_t offset;
  220. uint32_t type;
  221. };
  222. typedef stl::vector<Variable> MemberArray;
  223. Variable var;
  224. MemberArray members;
  225. };
  226. typedef stl::unordered_map<uint32_t, TypeId> TypeIdMap;
  227. typedef stl::unordered_map<uint32_t, Id> IdMap;
  228. TypeIdMap typeIdMap;
  229. IdMap idMap;
  230. stl::string getTypeName(uint32_t _typeId)
  231. {
  232. return getTypeId(_typeId).toString();
  233. }
  234. Id& getId(uint32_t _id)
  235. {
  236. IdMap::iterator it = idMap.find(_id);
  237. if (it == idMap.end() )
  238. {
  239. Id id;
  240. stl::pair<IdMap::iterator, bool> result = idMap.insert(stl::make_pair(_id, id) );
  241. it = result.first;
  242. }
  243. return it->second;
  244. }
  245. Id::Variable& get(uint32_t _id, uint32_t _idx)
  246. {
  247. Id& id = getId(_id);
  248. id.members.resize(bx::uint32_max(_idx+1, uint32_t(id.members.size() ) ) );
  249. return id.members[_idx];
  250. }
  251. TypeId& getTypeId(uint32_t _id)
  252. {
  253. TypeIdMap::iterator it = typeIdMap.find(_id);
  254. if (it == typeIdMap.end() )
  255. {
  256. TypeId id;
  257. stl::pair<TypeIdMap::iterator, bool> result = typeIdMap.insert(stl::make_pair(_id, id) );
  258. it = result.first;
  259. }
  260. return it->second;
  261. }
  262. void update(uint32_t _id, const stl::string& _name)
  263. {
  264. getId(_id).var.name = _name;
  265. }
  266. BX_NO_INLINE void update(Id::Variable& _variable, SpvDecoration::Enum _decoration, uint32_t _literal)
  267. {
  268. _variable.decoration = _decoration;
  269. switch (_decoration)
  270. {
  271. case SpvDecoration::Location:
  272. _variable.location = _literal;
  273. break;
  274. case SpvDecoration::Offset:
  275. _variable.offset = _literal;
  276. break;
  277. case SpvDecoration::BuiltIn:
  278. _variable.builtin = SpvBuiltin::Enum(_literal);
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. BX_NO_INLINE void update(Id::Variable& _variable, uint32_t _type, SpvStorageClass::Enum _storageClass)
  285. {
  286. _variable.type = _type;
  287. _variable.storageClass = _storageClass;
  288. }
  289. void update(uint32_t _id, SpvDecoration::Enum _decoration, uint32_t _literal)
  290. {
  291. update(getId(_id).var, _decoration, _literal);
  292. }
  293. void update(uint32_t _id, uint32_t _type, SpvStorageClass::Enum _storageClass)
  294. {
  295. update(getId(_id).var, _type, _storageClass);
  296. }
  297. void update(uint32_t _id, uint32_t _idx, const stl::string& _name)
  298. {
  299. Id::Variable& var = get(_id, _idx);
  300. var.name = _name;
  301. }
  302. BX_NO_INLINE void update(uint32_t _id, uint32_t _idx, SpvDecoration::Enum _decoration, uint32_t _literal)
  303. {
  304. update(get(_id, _idx), _decoration, _literal);
  305. }
  306. void update(uint32_t _id, TypeId::Enum _type)
  307. {
  308. TypeId& type = getTypeId(_id);
  309. type.type = _type;
  310. }
  311. void update(uint32_t _id, TypeId::Enum _type, uint32_t _baseTypeId, uint32_t _numComonents)
  312. {
  313. TypeId& type = getTypeId(_id);
  314. type.type = _type;
  315. type.baseType = getTypeId(_baseTypeId).type;
  316. type.numComponents = _numComonents;
  317. }
  318. };
  319. bool spvParse(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  320. {
  321. BX_UNUSED(_offset);
  322. SpvReflection* spv = (SpvReflection*)_userData;
  323. switch (_instruction.opcode)
  324. {
  325. case SpvOpcode::Name:
  326. spv->update(_instruction.result
  327. , _instruction.operand[0].literalString
  328. );
  329. break;
  330. case SpvOpcode::Decorate:
  331. spv->update(_instruction.operand[0].data
  332. , SpvDecoration::Enum(_instruction.operand[1].data)
  333. , _instruction.operand[2].data
  334. );
  335. break;
  336. case SpvOpcode::MemberName:
  337. spv->update(_instruction.result
  338. , _instruction.operand[0].data
  339. , _instruction.operand[1].literalString
  340. );
  341. break;
  342. case SpvOpcode::MemberDecorate:
  343. spv->update(_instruction.operand[0].data
  344. , _instruction.operand[1].data
  345. , SpvDecoration::Enum(_instruction.operand[2].data)
  346. , _instruction.operand[3].data
  347. );
  348. break;
  349. case SpvOpcode::Variable:
  350. spv->update(_instruction.result
  351. , _instruction.type
  352. , SpvStorageClass::Enum(_instruction.operand[0].data)
  353. );
  354. break;
  355. case SpvOpcode::TypeVoid:
  356. spv->update(_instruction.result, SpvReflection::TypeId::Void);
  357. break;
  358. case SpvOpcode::TypeBool:
  359. spv->update(_instruction.result, SpvReflection::TypeId::Bool);
  360. break;
  361. case SpvOpcode::TypeInt:
  362. spv->update(_instruction.result
  363. , 32 == _instruction.operand[0].data
  364. ? 0 == _instruction.operand[1].data
  365. ? SpvReflection::TypeId::Uint32
  366. : SpvReflection::TypeId::Int32
  367. : 0 == _instruction.operand[1].data
  368. ? SpvReflection::TypeId::Uint64
  369. : SpvReflection::TypeId::Int64
  370. );
  371. break;
  372. case SpvOpcode::TypeFloat:
  373. spv->update(_instruction.result
  374. , 32 == _instruction.operand[0].data
  375. ? SpvReflection::TypeId::Float
  376. : SpvReflection::TypeId::Double
  377. );
  378. break;
  379. case SpvOpcode::TypeVector:
  380. spv->update(_instruction.result
  381. , SpvReflection::TypeId::Vector
  382. , _instruction.operand[0].data
  383. , _instruction.operand[1].data
  384. );
  385. break;
  386. case SpvOpcode::TypeMatrix:
  387. spv->update(_instruction.result
  388. , SpvReflection::TypeId::Matrix
  389. , _instruction.operand[0].data
  390. , _instruction.operand[1].data
  391. );
  392. break;
  393. case SpvOpcode::TypeImage:
  394. case SpvOpcode::TypeSampler:
  395. case SpvOpcode::TypeSampledImage:
  396. break;
  397. case SpvOpcode::TypeStruct:
  398. for (uint32_t ii = 0, num = _instruction.numOperands; ii < num; ++ii)
  399. {
  400. SpvReflection::Id::Variable& var = spv->get(_instruction.result, ii);
  401. var.type = _instruction.operand[ii].data;
  402. }
  403. break;
  404. default:
  405. break;
  406. }
  407. return true;
  408. }
  409. #define DBG(...) // bx::debugPrintf(__VA_ARGS__)
  410. void disassemble(bx::WriterI* _writer, bx::ReaderSeekerI* _reader, bx::Error* _err)
  411. {
  412. BX_UNUSED(_writer);
  413. uint32_t magic;
  414. bx::peek(_reader, magic);
  415. SpvReflection spvx;
  416. if (magic == SPV_CHUNK_HEADER)
  417. {
  418. SpirV spirv;
  419. read(_reader, spirv, _err);
  420. parse(spirv.shader, spvParse, &spvx, _err);
  421. for (SpvReflection::IdMap::const_iterator it = spvx.idMap.begin(), itEnd = spvx.idMap.end(); it != itEnd; ++it)
  422. {
  423. const SpvReflection::Id& id = it->second;
  424. uint32_t num = uint32_t(id.members.size() );
  425. if (0 < num
  426. && 0 != bx::strCmp(id.var.name.c_str(), "gl_PerVertex") )
  427. {
  428. DBG("%3d: %s %d %s\n"
  429. , it->first
  430. , id.var.name.c_str()
  431. , id.var.location
  432. , getName(id.var.storageClass)
  433. );
  434. DBG("{\n");
  435. for (uint32_t ii = 0; ii < num; ++ii)
  436. {
  437. const SpvReflection::Id::Variable& var = id.members[ii];
  438. DBG("\t\t%s %s %d %s\n"
  439. , spvx.getTypeName(var.type).c_str()
  440. , var.name.c_str()
  441. , var.offset
  442. , getName(var.storageClass)
  443. );
  444. BX_UNUSED(var);
  445. }
  446. DBG("}\n");
  447. }
  448. }
  449. }
  450. }
  451. static EShLanguage getLang(char _p)
  452. {
  453. switch (_p)
  454. {
  455. case 'c': return EShLangCompute;
  456. case 'f': return EShLangFragment;
  457. case 'v': return EShLangVertex;
  458. default: return EShLangCount;
  459. }
  460. }
  461. // static void printError(spv_message_level_t, const char*, const spv_position_t&, const char* _message)
  462. // {
  463. // fprintf(stderr, "%s\n", _message);
  464. // }
  465. static const char* s_attribName[] =
  466. {
  467. "a_position",
  468. "a_normal",
  469. "a_tangent",
  470. "a_bitangent",
  471. "a_color0",
  472. "a_color1",
  473. "a_color2",
  474. "a_color3",
  475. "a_indices",
  476. "a_weight",
  477. "a_texcoord0",
  478. "a_texcoord1",
  479. "a_texcoord2",
  480. "a_texcoord3",
  481. "a_texcoord4",
  482. "a_texcoord5",
  483. "a_texcoord6",
  484. "a_texcoord7",
  485. };
  486. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  487. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  488. {
  489. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  490. {
  491. if (0 == bx::strCmp(s_attribName[ii], _name) )
  492. {
  493. return bgfx::Attrib::Enum(ii);
  494. }
  495. }
  496. return bgfx::Attrib::Count;
  497. }
  498. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  499. {
  500. BX_UNUSED(_version);
  501. glslang::InitializeProcess();
  502. glslang::TProgram* program = new glslang::TProgram;
  503. EShLanguage stage = getLang(_options.shaderType);
  504. if (EShLangCount == stage)
  505. {
  506. fprintf(stderr, "Error: Unknown shader type '%c'.\n", _options.shaderType);
  507. return false;
  508. }
  509. glslang::TShader* shader = new glslang::TShader(stage);
  510. EShMessages messages = EShMessages(0
  511. | EShMsgDefault
  512. | EShMsgReadHlsl
  513. | EShMsgVulkanRules
  514. | EShMsgSpvRules
  515. );
  516. shader->setEntryPoint("main");
  517. const char* shaderStrings[] = { _code.c_str() };
  518. shader->setStrings(
  519. shaderStrings
  520. , BX_COUNTOF(shaderStrings)
  521. );
  522. bool compiled = shader->parse(&resourceLimits
  523. , 110
  524. , false
  525. , messages
  526. );
  527. bool linked = false;
  528. bool validated = true;
  529. if (!compiled)
  530. {
  531. const char* log = shader->getInfoLog();
  532. if (NULL != log)
  533. {
  534. int32_t source = 0;
  535. int32_t line = 0;
  536. int32_t column = 0;
  537. int32_t start = 0;
  538. int32_t end = INT32_MAX;
  539. const char* err = bx::strFind(log, "ERROR:");
  540. bool found = false;
  541. if (NULL != err)
  542. {
  543. found = 2 == sscanf(err, "ERROR: %u:%u: '", &source, &line);
  544. if (found)
  545. {
  546. ++line;
  547. }
  548. }
  549. if (found)
  550. {
  551. start = bx::uint32_imax(1, line-10);
  552. end = start + 20;
  553. }
  554. printCode(_code.c_str(), line, start, end, column);
  555. fprintf(stderr, "%s\n", log);
  556. }
  557. }
  558. else
  559. {
  560. program->addShader(shader);
  561. linked = true
  562. && program->link(messages)
  563. && program->mapIO()
  564. ;
  565. if (!linked)
  566. {
  567. const char* log = program->getInfoLog();
  568. if (NULL != log)
  569. {
  570. fprintf(stderr, "%s\n", log);
  571. }
  572. }
  573. else
  574. {
  575. uint16_t size = 0;
  576. program->buildReflection();
  577. if (_firstPass)
  578. {
  579. const size_t strLength = bx::strLen("uniform");
  580. // first time through, we just find unused uniforms and get rid of them
  581. std::string output;
  582. bx::Error err;
  583. LineReader reader(_code.c_str() );
  584. while (err.isOk() )
  585. {
  586. char str[4096];
  587. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  588. if (err.isOk() )
  589. {
  590. std::string strLine(str, len);
  591. size_t index = strLine.find("uniform ");
  592. if (index != std::string::npos)
  593. {
  594. bool found = false;
  595. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  596. {
  597. // matching lines like: uniform u_name;
  598. // we want to replace "uniform" with "static" so that it's no longer
  599. // included in the uniform blob that the application must upload
  600. // we can't just remove them, because unused functions might still reference
  601. // them and cause a compile error when they're gone
  602. if (!!bx::findIdentifierMatch(strLine.c_str(), program->getUniformName(ii) ) )
  603. {
  604. found = true;
  605. break;
  606. }
  607. }
  608. if (!found)
  609. {
  610. strLine = strLine.replace(index, strLength, "static");
  611. }
  612. }
  613. output += strLine;
  614. }
  615. }
  616. // recompile with the unused uniforms converted to statics
  617. return compile(_options, _version, output.c_str(), _writer, false);
  618. }
  619. {
  620. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  621. bx::write(_writer, count);
  622. uint32_t fragmentBit = _options.shaderType == 'f' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  623. for (uint16_t ii = 0; ii < count; ++ii)
  624. {
  625. Uniform un;
  626. un.name = program->getUniformName(ii);
  627. un.num = uint8_t(program->getUniformArraySize(ii) );
  628. const uint32_t offset = program->getUniformBufferOffset(ii);
  629. un.regIndex = uint16_t(offset);
  630. un.regCount = un.num;
  631. switch (program->getUniformType(ii))
  632. {
  633. case 0x1404: // GL_INT:
  634. un.type = UniformType::Int1;
  635. break;
  636. case 0x8B52: // GL_FLOAT_VEC4:
  637. un.type = UniformType::Vec4;
  638. break;
  639. case 0x8B5B: // GL_FLOAT_MAT3:
  640. un.type = UniformType::Mat3;
  641. un.regCount *= 3;
  642. break;
  643. case 0x8B5C: // GL_FLOAT_MAT4:
  644. un.type = UniformType::Mat4;
  645. un.regCount *= 4;
  646. break;
  647. default:
  648. un.type = UniformType::End;
  649. break;
  650. }
  651. size += un.regCount*16;
  652. uint8_t nameSize = (uint8_t)un.name.size();
  653. bx::write(_writer, nameSize);
  654. bx::write(_writer, un.name.c_str(), nameSize);
  655. bx::write(_writer, uint8_t(un.type | fragmentBit));
  656. bx::write(_writer, un.num);
  657. bx::write(_writer, un.regIndex);
  658. bx::write(_writer, un.regCount);
  659. BX_TRACE("%s, %s, %d, %d, %d"
  660. , un.name.c_str()
  661. , getUniformTypeName(un.type)
  662. , un.num
  663. , un.regIndex
  664. , un.regCount
  665. );
  666. }
  667. }
  668. if (g_verbose)
  669. {
  670. program->dumpReflection();
  671. }
  672. BX_UNUSED(spv::MemorySemanticsAllMemory);
  673. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  674. std::vector<uint32_t> spirv;
  675. glslang::SpvOptions options;
  676. options.disableOptimizer = false;
  677. glslang::GlslangToSpv(*intermediate, spirv, &options);
  678. bx::Error err;
  679. bx::WriterI* writer = bx::getDebugOut();
  680. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  681. disassemble(writer, &reader, &err);
  682. uint32_t shaderSize = (uint32_t)spirv.size()*sizeof(uint32_t);
  683. bx::write(_writer, shaderSize);
  684. bx::write(_writer, spirv.data(), shaderSize);
  685. uint8_t nul = 0;
  686. bx::write(_writer, nul);
  687. //
  688. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  689. bx::write(_writer, numAttr);
  690. for (uint8_t ii = 0; ii < numAttr; ++ii)
  691. {
  692. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  693. if (bgfx::Attrib::Count != attr)
  694. {
  695. bx::write(_writer, bgfx::attribToId(attr) );
  696. }
  697. else
  698. {
  699. bx::write(_writer, uint16_t(UINT16_MAX) );
  700. }
  701. }
  702. bx::write(_writer, size);
  703. }
  704. }
  705. delete program;
  706. delete shader;
  707. glslang::FinalizeProcess();
  708. return compiled && linked && validated;
  709. }
  710. } // namespace spirv
  711. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  712. {
  713. return spirv::compile(_options, _version, _code, _writer, true);
  714. }
  715. } // namespace bgfx