shaderc_metal.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /*
  2. * Copyright 2011-2023 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  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. #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
  19. #include <spirv_msl.hpp>
  20. #include <spirv_reflect.hpp>
  21. #include <spirv-tools/optimizer.hpp>
  22. BX_PRAGMA_DIAGNOSTIC_POP()
  23. namespace bgfx
  24. {
  25. struct TinyStlAllocator
  26. {
  27. static void* static_allocate(size_t _bytes);
  28. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  29. };
  30. } // namespace bgfx
  31. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  32. #include <tinystl/allocator.h>
  33. #include <tinystl/string.h>
  34. #include <tinystl/unordered_map.h>
  35. #include <tinystl/vector.h>
  36. namespace stl = tinystl;
  37. #include "../../src/shader.h"
  38. namespace bgfx { namespace metal
  39. {
  40. const TBuiltInResource resourceLimits =
  41. {
  42. 32, // MaxLights
  43. 6, // MaxClipPlanes
  44. 32, // MaxTextureUnits
  45. 32, // MaxTextureCoords
  46. 64, // MaxVertexAttribs
  47. 4096, // MaxVertexUniformComponents
  48. 64, // MaxVaryingFloats
  49. 32, // MaxVertexTextureImageUnits
  50. 80, // MaxCombinedTextureImageUnits
  51. 32, // MaxTextureImageUnits
  52. 4096, // MaxFragmentUniformComponents
  53. 32, // MaxDrawBuffers
  54. 128, // MaxVertexUniformVectors
  55. 8, // MaxVaryingVectors
  56. 16, // MaxFragmentUniformVectors
  57. 16, // MaxVertexOutputVectors
  58. 15, // MaxFragmentInputVectors
  59. -8, // MinProgramTexelOffset
  60. 7, // MaxProgramTexelOffset
  61. 8, // MaxClipDistances
  62. 65535, // MaxComputeWorkGroupCountX
  63. 65535, // MaxComputeWorkGroupCountY
  64. 65535, // MaxComputeWorkGroupCountZ
  65. 1024, // MaxComputeWorkGroupSizeX
  66. 1024, // MaxComputeWorkGroupSizeY
  67. 64, // MaxComputeWorkGroupSizeZ
  68. 1024, // MaxComputeUniformComponents
  69. 16, // MaxComputeTextureImageUnits
  70. 8, // MaxComputeImageUniforms
  71. 8, // MaxComputeAtomicCounters
  72. 1, // MaxComputeAtomicCounterBuffers
  73. 60, // MaxVaryingComponents
  74. 64, // MaxVertexOutputComponents
  75. 64, // MaxGeometryInputComponents
  76. 128, // MaxGeometryOutputComponents
  77. 128, // MaxFragmentInputComponents
  78. 8, // MaxImageUnits
  79. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  80. 8, // MaxCombinedShaderOutputResources
  81. 0, // MaxImageSamples
  82. 0, // MaxVertexImageUniforms
  83. 0, // MaxTessControlImageUniforms
  84. 0, // MaxTessEvaluationImageUniforms
  85. 0, // MaxGeometryImageUniforms
  86. 8, // MaxFragmentImageUniforms
  87. 8, // MaxCombinedImageUniforms
  88. 16, // MaxGeometryTextureImageUnits
  89. 256, // MaxGeometryOutputVertices
  90. 1024, // MaxGeometryTotalOutputComponents
  91. 1024, // MaxGeometryUniformComponents
  92. 64, // MaxGeometryVaryingComponents
  93. 128, // MaxTessControlInputComponents
  94. 128, // MaxTessControlOutputComponents
  95. 16, // MaxTessControlTextureImageUnits
  96. 1024, // MaxTessControlUniformComponents
  97. 4096, // MaxTessControlTotalOutputComponents
  98. 128, // MaxTessEvaluationInputComponents
  99. 128, // MaxTessEvaluationOutputComponents
  100. 16, // MaxTessEvaluationTextureImageUnits
  101. 1024, // MaxTessEvaluationUniformComponents
  102. 120, // MaxTessPatchComponents
  103. 32, // MaxPatchVertices
  104. 64, // MaxTessGenLevel
  105. 16, // MaxViewports
  106. 0, // MaxVertexAtomicCounters
  107. 0, // MaxTessControlAtomicCounters
  108. 0, // MaxTessEvaluationAtomicCounters
  109. 0, // MaxGeometryAtomicCounters
  110. 8, // MaxFragmentAtomicCounters
  111. 8, // MaxCombinedAtomicCounters
  112. 1, // MaxAtomicCounterBindings
  113. 0, // MaxVertexAtomicCounterBuffers
  114. 0, // MaxTessControlAtomicCounterBuffers
  115. 0, // MaxTessEvaluationAtomicCounterBuffers
  116. 0, // MaxGeometryAtomicCounterBuffers
  117. 1, // MaxFragmentAtomicCounterBuffers
  118. 1, // MaxCombinedAtomicCounterBuffers
  119. 16384, // MaxAtomicCounterBufferSize
  120. 4, // MaxTransformFeedbackBuffers
  121. 64, // MaxTransformFeedbackInterleavedComponents
  122. 8, // MaxCullDistances
  123. 8, // MaxCombinedClipAndCullDistances
  124. 4, // MaxSamples
  125. 0, // maxMeshOutputVerticesNV
  126. 0, // maxMeshOutputPrimitivesNV
  127. 0, // maxMeshWorkGroupSizeX_NV
  128. 0, // maxMeshWorkGroupSizeY_NV
  129. 0, // maxMeshWorkGroupSizeZ_NV
  130. 0, // maxTaskWorkGroupSizeX_NV
  131. 0, // maxTaskWorkGroupSizeY_NV
  132. 0, // maxTaskWorkGroupSizeZ_NV
  133. 0, // maxMeshViewCountNV
  134. 0, // maxMeshOutputVerticesEXT
  135. 0, // maxMeshOutputPrimitivesEXT
  136. 0, // maxMeshWorkGroupSizeX_EXT
  137. 0, // maxMeshWorkGroupSizeY_EXT
  138. 0, // maxMeshWorkGroupSizeZ_EXT
  139. 0, // maxTaskWorkGroupSizeX_EXT
  140. 0, // maxTaskWorkGroupSizeY_EXT
  141. 0, // maxTaskWorkGroupSizeZ_EXT
  142. 0, // maxMeshViewCountEXT
  143. 0, // maxDualSourceDrawBuffersEXT
  144. { // limits
  145. true, // nonInductiveForLoops
  146. true, // whileLoops
  147. true, // doWhileLoops
  148. true, // generalUniformIndexing
  149. true, // generalAttributeMatrixVectorIndexing
  150. true, // generalVaryingIndexing
  151. true, // generalSamplerIndexing
  152. true, // generalVariableIndexing
  153. true, // generalConstantMatrixVectorIndexing
  154. },
  155. };
  156. static EShLanguage getLang(char _p)
  157. {
  158. switch (_p)
  159. {
  160. case 'c': return EShLangCompute;
  161. case 'f': return EShLangFragment;
  162. case 'v': return EShLangVertex;
  163. default: return EShLangCount;
  164. }
  165. }
  166. static const char* s_attribName[] =
  167. {
  168. "a_position",
  169. "a_normal",
  170. "a_tangent",
  171. "a_bitangent",
  172. "a_color0",
  173. "a_color1",
  174. "a_color2",
  175. "a_color3",
  176. "a_indices",
  177. "a_weight",
  178. "a_texcoord0",
  179. "a_texcoord1",
  180. "a_texcoord2",
  181. "a_texcoord3",
  182. "a_texcoord4",
  183. "a_texcoord5",
  184. "a_texcoord6",
  185. "a_texcoord7",
  186. };
  187. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  188. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  189. {
  190. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  191. {
  192. if (0 == bx::strCmp(s_attribName[ii], _name) )
  193. {
  194. return bgfx::Attrib::Enum(ii);
  195. }
  196. }
  197. return bgfx::Attrib::Count;
  198. }
  199. static const char* s_samplerTypes[] =
  200. {
  201. "BgfxSampler2D",
  202. "BgfxISampler2D",
  203. "BgfxUSampler2D",
  204. "BgfxSampler2DArray",
  205. "BgfxSampler2DShadow",
  206. "BgfxSampler2DArrayShadow",
  207. "BgfxSampler3D",
  208. "BgfxISampler3D",
  209. "BgfxUSampler3D",
  210. "BgfxSamplerCube",
  211. "BgfxSamplerCubeShadow",
  212. "BgfxSampler2DMS",
  213. };
  214. static uint16_t writeUniformArray(bx::WriterI* _writer, const UniformArray& uniforms, bool isFragmentShader)
  215. {
  216. uint16_t size = 0;
  217. bx::ErrorAssert err;
  218. uint16_t count = uint16_t(uniforms.size());
  219. bx::write(_writer, count, &err);
  220. uint32_t fragmentBit = isFragmentShader ? kUniformFragmentBit : 0;
  221. for (uint16_t ii = 0; ii < count; ++ii)
  222. {
  223. const Uniform& un = uniforms[ii];
  224. size += un.regCount*16;
  225. uint8_t nameSize = (uint8_t)un.name.size();
  226. bx::write(_writer, nameSize, &err);
  227. bx::write(_writer, un.name.c_str(), nameSize, &err);
  228. bx::write(_writer, uint8_t(un.type | fragmentBit), &err);
  229. bx::write(_writer, un.num, &err);
  230. bx::write(_writer, un.regIndex, &err);
  231. bx::write(_writer, un.regCount, &err);
  232. bx::write(_writer, un.texComponent, &err);
  233. bx::write(_writer, un.texDimension, &err);
  234. bx::write(_writer, un.texFormat, &err);
  235. BX_TRACE("%s, %s, %d, %d, %d"
  236. , un.name.c_str()
  237. , getUniformTypeName(un.type)
  238. , un.num
  239. , un.regIndex
  240. , un.regCount
  241. );
  242. }
  243. return size;
  244. }
  245. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  246. {
  247. BX_UNUSED(_version);
  248. glslang::InitializeProcess();
  249. EShLanguage stage = getLang(_options.shaderType);
  250. if (EShLangCount == stage)
  251. {
  252. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  253. return false;
  254. }
  255. glslang::TProgram* program = new glslang::TProgram;
  256. glslang::TShader* shader = new glslang::TShader(stage);
  257. EShMessages messages = EShMessages(0
  258. | EShMsgDefault
  259. | EShMsgReadHlsl
  260. | EShMsgVulkanRules
  261. | EShMsgSpvRules
  262. );
  263. shader->setEntryPoint("main");
  264. shader->setAutoMapBindings(true);
  265. const int textureBindingOffset = 16;
  266. shader->setShiftBinding(glslang::EResTexture, textureBindingOffset);
  267. shader->setShiftBinding(glslang::EResSampler, textureBindingOffset);
  268. shader->setShiftBinding(glslang::EResImage, textureBindingOffset);
  269. const char* shaderStrings[] = { _code.c_str() };
  270. shader->setStrings(
  271. shaderStrings
  272. , BX_COUNTOF(shaderStrings)
  273. );
  274. bool compiled = shader->parse(&resourceLimits
  275. , 110
  276. , false
  277. , messages
  278. );
  279. bool linked = false;
  280. bool validated = true;
  281. if (!compiled)
  282. {
  283. const char* log = shader->getInfoLog();
  284. if (NULL != log)
  285. {
  286. int32_t source = 0;
  287. int32_t line = 0;
  288. int32_t column = 0;
  289. int32_t start = 0;
  290. int32_t end = INT32_MAX;
  291. bx::StringView err = bx::strFind(log, "ERROR:");
  292. bool found = false;
  293. if (!err.isEmpty() )
  294. {
  295. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  296. if (found)
  297. {
  298. ++line;
  299. }
  300. }
  301. if (found)
  302. {
  303. start = bx::uint32_imax(1, line-10);
  304. end = start + 20;
  305. }
  306. printCode(_code.c_str(), line, start, end, column);
  307. bx::printf("%s\n", log);
  308. }
  309. }
  310. else
  311. {
  312. program->addShader(shader);
  313. linked = true
  314. && program->link(messages)
  315. && program->mapIO()
  316. ;
  317. if (!linked)
  318. {
  319. const char* log = program->getInfoLog();
  320. if (NULL != log)
  321. {
  322. bx::printf("%s\n", log);
  323. }
  324. }
  325. else
  326. {
  327. program->buildReflection();
  328. if (_firstPass)
  329. {
  330. // first time through, we just find unused uniforms and get rid of them
  331. std::string output;
  332. bx::Error err;
  333. bx::LineReader reader(_code.c_str() );
  334. while (!reader.isDone() )
  335. {
  336. bx::StringView strLine = reader.next();
  337. bx::StringView str = strFind(strLine, "uniform ");
  338. if (!str.isEmpty() )
  339. {
  340. // If the line declares a uniform, merge all next
  341. // lines until we encounter a semicolon.
  342. bx::StringView lineEnd = strFind(strLine, ";");
  343. while (lineEnd.isEmpty() && !reader.isDone()) {
  344. bx::StringView nextLine = reader.next();
  345. strLine.set(strLine.getPtr(), nextLine.getTerm());
  346. lineEnd = strFind(nextLine, ";");
  347. }
  348. bool found = false;
  349. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  350. {
  351. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  352. {
  353. found = true;
  354. break;
  355. }
  356. }
  357. if (!found)
  358. {
  359. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  360. {
  361. // matching lines like: uniform u_name;
  362. // we want to replace "uniform" with "static" so that it's no longer
  363. // included in the uniform blob that the application must upload
  364. // we can't just remove them, because unused functions might still reference
  365. // them and cause a compile error when they're gone
  366. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  367. {
  368. found = true;
  369. break;
  370. }
  371. }
  372. }
  373. if (!found)
  374. {
  375. output.append(strLine.getPtr(), str.getPtr() );
  376. output += "static ";
  377. output.append(str.getTerm(), strLine.getTerm() );
  378. output += "\n";
  379. }
  380. else
  381. {
  382. output.append(strLine.getPtr(), strLine.getTerm() );
  383. output += "\n";
  384. }
  385. }
  386. else
  387. {
  388. output.append(strLine.getPtr(), strLine.getTerm() );
  389. output += "\n";
  390. }
  391. }
  392. // recompile with the unused uniforms converted to statics
  393. delete program;
  394. delete shader;
  395. return compile(_options, _version, output.c_str(), _writer, false);
  396. }
  397. UniformArray uniforms;
  398. {
  399. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  400. for (uint16_t ii = 0; ii < count; ++ii)
  401. {
  402. Uniform un;
  403. un.name = program->getUniformName(ii);
  404. if (bx::hasSuffix(un.name.c_str(), ".@data") )
  405. {
  406. continue;
  407. }
  408. un.num = uint8_t(program->getUniformArraySize(ii) );
  409. const uint32_t offset = program->getUniformBufferOffset(ii);
  410. un.regIndex = uint16_t(offset);
  411. un.regCount = un.num;
  412. switch (program->getUniformType(ii) )
  413. {
  414. case 0x1404: // GL_INT:
  415. un.type = UniformType::Sampler;
  416. break;
  417. case 0x8B52: // GL_FLOAT_VEC4:
  418. un.type = UniformType::Vec4;
  419. break;
  420. case 0x8B5B: // GL_FLOAT_MAT3:
  421. un.type = UniformType::Mat3;
  422. un.regCount *= 3;
  423. break;
  424. case 0x8B5C: // GL_FLOAT_MAT4:
  425. un.type = UniformType::Mat4;
  426. un.regCount *= 4;
  427. break;
  428. default:
  429. un.type = UniformType::End;
  430. break;
  431. }
  432. uniforms.push_back(un);
  433. }
  434. }
  435. if (g_verbose)
  436. {
  437. program->dumpReflection();
  438. }
  439. BX_UNUSED(spv::MemorySemanticsAllMemory);
  440. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  441. std::vector<uint32_t> spirv;
  442. glslang::SpvOptions options;
  443. options.disableOptimizer = false;
  444. glslang::GlslangToSpv(*intermediate, spirv, &options);
  445. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  446. auto print_msg_to_stderr = [](
  447. spv_message_level_t
  448. , const char*
  449. , const spv_position_t&
  450. , const char* m
  451. )
  452. {
  453. bx::printf("Error: %s\n", m);
  454. };
  455. opt.SetMessageConsumer(print_msg_to_stderr);
  456. opt.RegisterLegalizationPasses();
  457. spvtools::ValidatorOptions validatorOptions;
  458. validatorOptions.SetBeforeHlslLegalization(true);
  459. if (!opt.Run(
  460. spirv.data()
  461. , spirv.size()
  462. , &spirv
  463. , validatorOptions
  464. , false
  465. ) )
  466. {
  467. compiled = false;
  468. }
  469. else
  470. {
  471. if (g_verbose)
  472. {
  473. glslang::SpirvToolsDisassemble(std::cout, spirv, SPV_ENV_VULKAN_1_0);
  474. }
  475. spirv_cross::CompilerReflection refl(spirv);
  476. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  477. // Loop through the separate_images, and extract the uniform names:
  478. for (auto &resource : resourcesrefl.separate_images)
  479. {
  480. std::string name = refl.get_name(resource.id);
  481. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture"))
  482. {
  483. name = name.substr(0, name.length() - 7);
  484. }
  485. Uniform un;
  486. un.name = name;
  487. un.type = UniformType::Sampler;
  488. un.num = 0; // needed?
  489. un.regIndex = 0; // needed?
  490. un.regCount = 0; // needed?
  491. uniforms.push_back(un);
  492. }
  493. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  494. bx::Error err;
  495. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  496. {
  497. spirv_cross::CompilerMSL msl(std::move(spirv) );
  498. auto executionModel = msl.get_execution_model();
  499. spirv_cross::MSLResourceBinding newBinding;
  500. newBinding.stage = executionModel;
  501. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  502. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  503. if (!entryPoints.empty() )
  504. msl.rename_entry_point(entryPoints[0].name, "xlatMtlMain", entryPoints[0].execution_model);
  505. for (auto &resource : resources.uniform_buffers)
  506. {
  507. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  508. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  509. newBinding.desc_set = set;
  510. newBinding.binding = binding;
  511. newBinding.msl_buffer = 0;
  512. msl.add_msl_resource_binding( newBinding );
  513. msl.set_name(resource.id, "_mtl_u");
  514. }
  515. for (auto &resource : resources.storage_buffers)
  516. {
  517. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  518. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  519. newBinding.desc_set = set;
  520. newBinding.binding = binding;
  521. newBinding.msl_buffer = binding + 1;
  522. msl.add_msl_resource_binding( newBinding );
  523. }
  524. for (auto &resource : resources.separate_samplers)
  525. {
  526. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  527. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  528. newBinding.desc_set = set;
  529. newBinding.binding = binding;
  530. newBinding.msl_texture = binding - textureBindingOffset;
  531. newBinding.msl_sampler = binding - textureBindingOffset;
  532. msl.add_msl_resource_binding( newBinding );
  533. }
  534. for (auto &resource : resources.separate_images)
  535. {
  536. std::string name = msl.get_name(resource.id);
  537. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  538. {
  539. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  540. }
  541. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  542. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  543. newBinding.desc_set = set;
  544. newBinding.binding = binding;
  545. newBinding.msl_texture = binding - textureBindingOffset;
  546. newBinding.msl_sampler = binding - textureBindingOffset;
  547. msl.add_msl_resource_binding( newBinding );
  548. }
  549. for (auto &resource : resources.storage_images)
  550. {
  551. std::string name = msl.get_name(resource.id);
  552. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  553. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  554. newBinding.desc_set = set;
  555. newBinding.binding = binding;
  556. newBinding.msl_texture = binding - textureBindingOffset;
  557. newBinding.msl_sampler = binding - textureBindingOffset;
  558. msl.add_msl_resource_binding( newBinding );
  559. }
  560. std::string source = msl.compile();
  561. if ('c' == _options.shaderType)
  562. {
  563. for (int i = 0; i < 3; ++i)
  564. {
  565. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  566. bx::write(_writer, dim, &err);
  567. }
  568. }
  569. uint32_t shaderSize = (uint32_t)source.size();
  570. bx::write(_writer, shaderSize, &err);
  571. bx::write(_writer, source.c_str(), shaderSize, &err);
  572. uint8_t nul = 0;
  573. bx::write(_writer, nul, &err);
  574. }
  575. else
  576. {
  577. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  578. bx::write(_writer, shaderSize, &err);
  579. bx::write(_writer, spirv.data(), shaderSize, &err);
  580. uint8_t nul = 0;
  581. bx::write(_writer, nul, &err);
  582. }
  583. //
  584. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  585. bx::write(_writer, numAttr, &err);
  586. for (uint8_t ii = 0; ii < numAttr; ++ii)
  587. {
  588. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  589. if (bgfx::Attrib::Count != attr)
  590. {
  591. bx::write(_writer, bgfx::attribToId(attr), &err);
  592. }
  593. else
  594. {
  595. bx::write(_writer, uint16_t(UINT16_MAX), &err);
  596. }
  597. }
  598. bx::write(_writer, size, &err);
  599. }
  600. }
  601. }
  602. delete program;
  603. delete shader;
  604. glslang::FinalizeProcess();
  605. return compiled && linked && validated;
  606. }
  607. } // namespace metal
  608. bool compileMetalShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  609. {
  610. return metal::compile(_options, _version, _code, _writer, true);
  611. }
  612. } // namespace bgfx