2
0

shaderc_metal.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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* _shaderWriter, 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(_shaderWriter, 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(_shaderWriter, nameSize, &err);
  227. bx::write(_shaderWriter, un.name.c_str(), nameSize, &err);
  228. bx::write(_shaderWriter, uint8_t(un.type | fragmentBit), &err);
  229. bx::write(_shaderWriter, un.num, &err);
  230. bx::write(_shaderWriter, un.regIndex, &err);
  231. bx::write(_shaderWriter, un.regCount, &err);
  232. bx::write(_shaderWriter, un.texComponent, &err);
  233. bx::write(_shaderWriter, un.texDimension, &err);
  234. bx::write(_shaderWriter, 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* _shaderWriter, bx::WriterI* _messageWriter, bool _firstPass)
  246. {
  247. BX_UNUSED(_version);
  248. bx::ErrorAssert messageErr;
  249. glslang::InitializeProcess();
  250. EShLanguage stage = getLang(_options.shaderType);
  251. if (EShLangCount == stage)
  252. {
  253. bx::write(_messageWriter, &messageErr, "Error: Unknown shader type '%c'.\n", _options.shaderType);
  254. return false;
  255. }
  256. glslang::TProgram* program = new glslang::TProgram;
  257. glslang::TShader* shader = new glslang::TShader(stage);
  258. EShMessages messages = EShMessages(0
  259. | EShMsgDefault
  260. | EShMsgReadHlsl
  261. | EShMsgVulkanRules
  262. | EShMsgSpvRules
  263. );
  264. shader->setEntryPoint("main");
  265. shader->setAutoMapBindings(true);
  266. const int textureBindingOffset = 16;
  267. shader->setShiftBinding(glslang::EResTexture, textureBindingOffset);
  268. shader->setShiftBinding(glslang::EResSampler, textureBindingOffset);
  269. shader->setShiftBinding(glslang::EResImage, textureBindingOffset);
  270. const char* shaderStrings[] = { _code.c_str() };
  271. shader->setStrings(
  272. shaderStrings
  273. , BX_COUNTOF(shaderStrings)
  274. );
  275. bool compiled = shader->parse(&resourceLimits
  276. , 110
  277. , false
  278. , messages
  279. );
  280. bool linked = false;
  281. bool validated = true;
  282. if (!compiled)
  283. {
  284. const char* log = shader->getInfoLog();
  285. if (NULL != log)
  286. {
  287. int32_t source = 0;
  288. int32_t line = 0;
  289. int32_t column = 0;
  290. int32_t start = 0;
  291. int32_t end = INT32_MAX;
  292. bx::StringView err = bx::strFind(log, "ERROR:");
  293. bool found = false;
  294. if (!err.isEmpty() )
  295. {
  296. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  297. if (found)
  298. {
  299. ++line;
  300. }
  301. }
  302. if (found)
  303. {
  304. start = bx::uint32_imax(1, line-10);
  305. end = start + 20;
  306. }
  307. printCode(_code.c_str(), line, start, end, column);
  308. bx::write(_messageWriter, &messageErr, "%s\n", log);
  309. }
  310. }
  311. else
  312. {
  313. program->addShader(shader);
  314. linked = true
  315. && program->link(messages)
  316. && program->mapIO()
  317. ;
  318. if (!linked)
  319. {
  320. const char* log = program->getInfoLog();
  321. if (NULL != log)
  322. {
  323. bx::write(_messageWriter, &messageErr, "%s\n", log);
  324. }
  325. }
  326. else
  327. {
  328. program->buildReflection();
  329. if (_firstPass)
  330. {
  331. // first time through, we just find unused uniforms and get rid of them
  332. std::string output;
  333. bx::Error err;
  334. bx::LineReader reader(_code.c_str() );
  335. while (!reader.isDone() )
  336. {
  337. bx::StringView strLine = reader.next();
  338. bx::StringView str = strFind(strLine, "uniform ");
  339. if (!str.isEmpty() )
  340. {
  341. // If the line declares a uniform, merge all next
  342. // lines until we encounter a semicolon.
  343. bx::StringView lineEnd = strFind(strLine, ";");
  344. while (lineEnd.isEmpty() && !reader.isDone()) {
  345. bx::StringView nextLine = reader.next();
  346. strLine.set(strLine.getPtr(), nextLine.getTerm());
  347. lineEnd = strFind(nextLine, ";");
  348. }
  349. bool found = false;
  350. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  351. {
  352. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  353. {
  354. found = true;
  355. break;
  356. }
  357. }
  358. if (!found)
  359. {
  360. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  361. {
  362. // matching lines like: uniform u_name;
  363. // we want to replace "uniform" with "static" so that it's no longer
  364. // included in the uniform blob that the application must upload
  365. // we can't just remove them, because unused functions might still reference
  366. // them and cause a compile error when they're gone
  367. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  368. {
  369. found = true;
  370. break;
  371. }
  372. }
  373. }
  374. if (!found)
  375. {
  376. output.append(strLine.getPtr(), str.getPtr() );
  377. output += "static ";
  378. output.append(str.getTerm(), strLine.getTerm() );
  379. output += "\n";
  380. }
  381. else
  382. {
  383. output.append(strLine.getPtr(), strLine.getTerm() );
  384. output += "\n";
  385. }
  386. }
  387. else
  388. {
  389. output.append(strLine.getPtr(), strLine.getTerm() );
  390. output += "\n";
  391. }
  392. }
  393. // recompile with the unused uniforms converted to statics
  394. delete program;
  395. delete shader;
  396. return compile(_options, _version, output.c_str(), _shaderWriter, _messageWriter, false);
  397. }
  398. UniformArray uniforms;
  399. {
  400. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  401. for (uint16_t ii = 0; ii < count; ++ii)
  402. {
  403. Uniform un;
  404. un.name = program->getUniformName(ii);
  405. if (bx::hasSuffix(un.name.c_str(), ".@data") )
  406. {
  407. continue;
  408. }
  409. un.num = uint8_t(program->getUniformArraySize(ii) );
  410. const uint32_t offset = program->getUniformBufferOffset(ii);
  411. un.regIndex = uint16_t(offset);
  412. un.regCount = un.num;
  413. switch (program->getUniformType(ii) )
  414. {
  415. case 0x1404: // GL_INT:
  416. un.type = UniformType::Sampler;
  417. break;
  418. case 0x8B52: // GL_FLOAT_VEC4:
  419. un.type = UniformType::Vec4;
  420. break;
  421. case 0x8B5B: // GL_FLOAT_MAT3:
  422. un.type = UniformType::Mat3;
  423. un.regCount *= 3;
  424. break;
  425. case 0x8B5C: // GL_FLOAT_MAT4:
  426. un.type = UniformType::Mat4;
  427. un.regCount *= 4;
  428. break;
  429. default:
  430. un.type = UniformType::End;
  431. break;
  432. }
  433. uniforms.push_back(un);
  434. }
  435. }
  436. if (g_verbose)
  437. {
  438. program->dumpReflection();
  439. }
  440. BX_UNUSED(spv::MemorySemanticsAllMemory);
  441. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  442. std::vector<uint32_t> spirv;
  443. glslang::SpvOptions options;
  444. options.disableOptimizer = false;
  445. glslang::GlslangToSpv(*intermediate, spirv, &options);
  446. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  447. auto print_msg_to_stderr = [_messageWriter, &messageErr](
  448. spv_message_level_t
  449. , const char*
  450. , const spv_position_t&
  451. , const char* m
  452. )
  453. {
  454. bx::write(_messageWriter, &messageErr, "Error: %s\n", m);
  455. };
  456. opt.SetMessageConsumer(print_msg_to_stderr);
  457. opt.RegisterLegalizationPasses();
  458. spvtools::ValidatorOptions validatorOptions;
  459. validatorOptions.SetBeforeHlslLegalization(true);
  460. if (!opt.Run(
  461. spirv.data()
  462. , spirv.size()
  463. , &spirv
  464. , validatorOptions
  465. , false
  466. ) )
  467. {
  468. compiled = false;
  469. }
  470. else
  471. {
  472. if (g_verbose)
  473. {
  474. glslang::SpirvToolsDisassemble(std::cout, spirv, SPV_ENV_VULKAN_1_0);
  475. }
  476. spirv_cross::CompilerReflection refl(spirv);
  477. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  478. // Loop through the separate_images, and extract the uniform names:
  479. for (auto &resource : resourcesrefl.separate_images)
  480. {
  481. std::string name = refl.get_name(resource.id);
  482. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture"))
  483. {
  484. name = name.substr(0, name.length() - 7);
  485. }
  486. Uniform un;
  487. un.name = name;
  488. un.type = UniformType::Sampler;
  489. un.num = 0; // needed?
  490. un.regIndex = 0; // needed?
  491. un.regCount = 0; // needed?
  492. uniforms.push_back(un);
  493. }
  494. uint16_t size = writeUniformArray(_shaderWriter, uniforms, _options.shaderType == 'f');
  495. bx::Error err;
  496. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  497. {
  498. spirv_cross::CompilerMSL msl(std::move(spirv) );
  499. auto executionModel = msl.get_execution_model();
  500. spirv_cross::MSLResourceBinding newBinding;
  501. newBinding.stage = executionModel;
  502. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  503. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  504. if (!entryPoints.empty() )
  505. msl.rename_entry_point(entryPoints[0].name, "xlatMtlMain", entryPoints[0].execution_model);
  506. for (auto &resource : resources.uniform_buffers)
  507. {
  508. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  509. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  510. newBinding.desc_set = set;
  511. newBinding.binding = binding;
  512. newBinding.msl_buffer = 0;
  513. msl.add_msl_resource_binding( newBinding );
  514. msl.set_name(resource.id, "_mtl_u");
  515. }
  516. for (auto &resource : resources.storage_buffers)
  517. {
  518. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  519. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  520. newBinding.desc_set = set;
  521. newBinding.binding = binding;
  522. newBinding.msl_buffer = binding + 1;
  523. msl.add_msl_resource_binding( newBinding );
  524. }
  525. for (auto &resource : resources.separate_samplers)
  526. {
  527. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  528. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  529. newBinding.desc_set = set;
  530. newBinding.binding = binding;
  531. newBinding.msl_texture = binding - textureBindingOffset;
  532. newBinding.msl_sampler = binding - textureBindingOffset;
  533. msl.add_msl_resource_binding( newBinding );
  534. }
  535. for (auto &resource : resources.separate_images)
  536. {
  537. std::string name = msl.get_name(resource.id);
  538. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  539. {
  540. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  541. }
  542. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  543. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  544. newBinding.desc_set = set;
  545. newBinding.binding = binding;
  546. newBinding.msl_texture = binding - textureBindingOffset;
  547. newBinding.msl_sampler = binding - textureBindingOffset;
  548. msl.add_msl_resource_binding( newBinding );
  549. }
  550. for (auto &resource : resources.storage_images)
  551. {
  552. std::string name = msl.get_name(resource.id);
  553. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  554. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  555. newBinding.desc_set = set;
  556. newBinding.binding = binding;
  557. newBinding.msl_texture = binding - textureBindingOffset;
  558. newBinding.msl_sampler = binding - textureBindingOffset;
  559. msl.add_msl_resource_binding( newBinding );
  560. }
  561. std::string source = msl.compile();
  562. if ('c' == _options.shaderType)
  563. {
  564. for (int i = 0; i < 3; ++i)
  565. {
  566. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  567. bx::write(_shaderWriter, dim, &err);
  568. }
  569. }
  570. uint32_t shaderSize = (uint32_t)source.size();
  571. bx::write(_shaderWriter, shaderSize, &err);
  572. bx::write(_shaderWriter, source.c_str(), shaderSize, &err);
  573. uint8_t nul = 0;
  574. bx::write(_shaderWriter, nul, &err);
  575. }
  576. else
  577. {
  578. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  579. bx::write(_shaderWriter, shaderSize, &err);
  580. bx::write(_shaderWriter, spirv.data(), shaderSize, &err);
  581. uint8_t nul = 0;
  582. bx::write(_shaderWriter, nul, &err);
  583. }
  584. //
  585. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  586. bx::write(_shaderWriter, numAttr, &err);
  587. for (uint8_t ii = 0; ii < numAttr; ++ii)
  588. {
  589. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  590. if (bgfx::Attrib::Count != attr)
  591. {
  592. bx::write(_shaderWriter, bgfx::attribToId(attr), &err);
  593. }
  594. else
  595. {
  596. bx::write(_shaderWriter, uint16_t(UINT16_MAX), &err);
  597. }
  598. }
  599. bx::write(_shaderWriter, size, &err);
  600. }
  601. }
  602. }
  603. delete program;
  604. delete shader;
  605. glslang::FinalizeProcess();
  606. return compiled && linked && validated;
  607. }
  608. } // namespace metal
  609. bool compileMetalShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _shaderWriter, bx::WriterI* _messageWriter)
  610. {
  611. return metal::compile(_options, _version, _code, _shaderWriter, _messageWriter, true);
  612. }
  613. } // namespace bgfx