shaderc_hlsl.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. #if SHADERC_CONFIG_HLSL
  7. #if defined(__MINGW32__)
  8. # define __REQUIRED_RPCNDR_H_VERSION__ 475
  9. # define __in
  10. # define __out
  11. #endif // defined(__MINGW32__)
  12. #define COM_NO_WINDOWS_H
  13. #include <d3dcompiler.h>
  14. #include <d3d11shader.h>
  15. #include <bx/os.h>
  16. #ifndef D3D_SVF_USED
  17. # define D3D_SVF_USED 2
  18. #endif // D3D_SVF_USED
  19. namespace bgfx { namespace hlsl
  20. {
  21. typedef HRESULT(WINAPI* PFN_D3D_COMPILE)(_In_reads_bytes_(SrcDataSize) LPCVOID pSrcData
  22. , _In_ SIZE_T SrcDataSize
  23. , _In_opt_ LPCSTR pSourceName
  24. , _In_reads_opt_(_Inexpressible_(pDefines->Name != NULL) ) CONST D3D_SHADER_MACRO* pDefines
  25. , _In_opt_ ID3DInclude* pInclude
  26. , _In_opt_ LPCSTR pEntrypoint
  27. , _In_ LPCSTR pTarget
  28. , _In_ UINT Flags1
  29. , _In_ UINT Flags2
  30. , _Out_ ID3DBlob** ppCode
  31. , _Always_(_Outptr_opt_result_maybenull_) ID3DBlob** ppErrorMsgs
  32. );
  33. typedef HRESULT(WINAPI* PFN_D3D_DISASSEMBLE)(_In_reads_bytes_(SrcDataSize) LPCVOID pSrcData
  34. , _In_ SIZE_T SrcDataSize
  35. , _In_ UINT Flags
  36. , _In_opt_ LPCSTR szComments
  37. , _Out_ ID3DBlob** ppDisassembly
  38. );
  39. typedef HRESULT(WINAPI* PFN_D3D_REFLECT)(_In_reads_bytes_(SrcDataSize) LPCVOID pSrcData
  40. , _In_ SIZE_T SrcDataSize
  41. , _In_ REFIID pInterface
  42. , _Out_ void** ppReflector
  43. );
  44. typedef HRESULT(WINAPI* PFN_D3D_STRIP_SHADER)(_In_reads_bytes_(BytecodeLength) LPCVOID pShaderBytecode
  45. , _In_ SIZE_T BytecodeLength
  46. , _In_ UINT uStripFlags
  47. , _Out_ ID3DBlob** ppStrippedBlob
  48. );
  49. PFN_D3D_COMPILE D3DCompile;
  50. PFN_D3D_DISASSEMBLE D3DDisassemble;
  51. PFN_D3D_REFLECT D3DReflect;
  52. PFN_D3D_STRIP_SHADER D3DStripShader;
  53. struct D3DCompiler
  54. {
  55. const char* fileName;
  56. const GUID IID_ID3D11ShaderReflection;
  57. };
  58. static const D3DCompiler s_d3dcompiler[] =
  59. { // BK - the only different method in interface is GetRequiresFlags at the end
  60. // of IID_ID3D11ShaderReflection47 (which is not used anyway).
  61. { "D3DCompiler_47.dll", { 0x8d536ca1, 0x0cca, 0x4956, { 0xa8, 0x37, 0x78, 0x69, 0x63, 0x75, 0x55, 0x84 } } },
  62. { "D3DCompiler_46.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  63. { "D3DCompiler_45.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  64. { "D3DCompiler_44.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  65. { "D3DCompiler_43.dll", { 0x0a233719, 0x3960, 0x4578, { 0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1 } } },
  66. };
  67. static const D3DCompiler* s_compiler;
  68. static void* s_d3dcompilerdll;
  69. const D3DCompiler* load(bx::WriterI* _messageWriter)
  70. {
  71. bx::Error messageErr;
  72. for (uint32_t ii = 0; ii < BX_COUNTOF(s_d3dcompiler); ++ii)
  73. {
  74. const D3DCompiler* compiler = &s_d3dcompiler[ii];
  75. s_d3dcompilerdll = bx::dlopen(compiler->fileName);
  76. if (NULL == s_d3dcompilerdll)
  77. {
  78. continue;
  79. }
  80. D3DCompile = (PFN_D3D_COMPILE )bx::dlsym(s_d3dcompilerdll, "D3DCompile");
  81. D3DDisassemble = (PFN_D3D_DISASSEMBLE )bx::dlsym(s_d3dcompilerdll, "D3DDisassemble");
  82. D3DReflect = (PFN_D3D_REFLECT )bx::dlsym(s_d3dcompilerdll, "D3DReflect");
  83. D3DStripShader = (PFN_D3D_STRIP_SHADER)bx::dlsym(s_d3dcompilerdll, "D3DStripShader");
  84. if (NULL == D3DCompile
  85. || NULL == D3DDisassemble
  86. || NULL == D3DReflect
  87. || NULL == D3DStripShader)
  88. {
  89. bx::dlclose(s_d3dcompilerdll);
  90. continue;
  91. }
  92. if (g_verbose)
  93. {
  94. char filePath[bx::kMaxFilePath];
  95. GetModuleFileNameA( (HMODULE)s_d3dcompilerdll, filePath, sizeof(filePath) );
  96. BX_TRACE("Loaded %s compiler (%s).", compiler->fileName, filePath);
  97. }
  98. return compiler;
  99. }
  100. bx::write(_messageWriter, &messageErr, "Error: Unable to open D3DCompiler_*.dll shader compiler.\n");
  101. return NULL;
  102. }
  103. void unload()
  104. {
  105. bx::dlclose(s_d3dcompilerdll);
  106. }
  107. struct CTHeader
  108. {
  109. uint32_t Size;
  110. uint32_t Creator;
  111. uint32_t Version;
  112. uint32_t Constants;
  113. uint32_t ConstantInfo;
  114. uint32_t Flags;
  115. uint32_t Target;
  116. };
  117. struct CTInfo
  118. {
  119. uint32_t Name;
  120. uint16_t RegisterSet;
  121. uint16_t RegisterIndex;
  122. uint16_t RegisterCount;
  123. uint16_t Reserved;
  124. uint32_t TypeInfo;
  125. uint32_t DefaultValue;
  126. };
  127. struct CTType
  128. {
  129. uint16_t Class;
  130. uint16_t Type;
  131. uint16_t Rows;
  132. uint16_t Columns;
  133. uint16_t Elements;
  134. uint16_t StructMembers;
  135. uint32_t StructMemberInfo;
  136. };
  137. struct RemapInputSemantic
  138. {
  139. bgfx::Attrib::Enum m_attr;
  140. const char* m_name;
  141. uint8_t m_index;
  142. };
  143. static const RemapInputSemantic s_remapInputSemantic[bgfx::Attrib::Count + 1] =
  144. {
  145. { bgfx::Attrib::Position, "POSITION", 0 },
  146. { bgfx::Attrib::Normal, "NORMAL", 0 },
  147. { bgfx::Attrib::Tangent, "TANGENT", 0 },
  148. { bgfx::Attrib::Bitangent, "BITANGENT", 0 },
  149. { bgfx::Attrib::Color0, "COLOR", 0 },
  150. { bgfx::Attrib::Color1, "COLOR", 1 },
  151. { bgfx::Attrib::Color2, "COLOR", 2 },
  152. { bgfx::Attrib::Color3, "COLOR", 3 },
  153. { bgfx::Attrib::Indices, "BLENDINDICES", 0 },
  154. { bgfx::Attrib::Weight, "BLENDWEIGHT", 0 },
  155. { bgfx::Attrib::TexCoord0, "TEXCOORD", 0 },
  156. { bgfx::Attrib::TexCoord1, "TEXCOORD", 1 },
  157. { bgfx::Attrib::TexCoord2, "TEXCOORD", 2 },
  158. { bgfx::Attrib::TexCoord3, "TEXCOORD", 3 },
  159. { bgfx::Attrib::TexCoord4, "TEXCOORD", 4 },
  160. { bgfx::Attrib::TexCoord5, "TEXCOORD", 5 },
  161. { bgfx::Attrib::TexCoord6, "TEXCOORD", 6 },
  162. { bgfx::Attrib::TexCoord7, "TEXCOORD", 7 },
  163. { bgfx::Attrib::Count, "", 0 },
  164. };
  165. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  166. {
  167. for (uint32_t ii = 0; ii < bgfx::Attrib::Count; ++ii)
  168. {
  169. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  170. if (0 == bx::strCmp(ris.m_name, _name)
  171. && ris.m_index == _index)
  172. {
  173. return ris;
  174. }
  175. }
  176. return s_remapInputSemantic[bgfx::Attrib::Count];
  177. }
  178. struct UniformRemap
  179. {
  180. UniformType::Enum id;
  181. D3D_SHADER_VARIABLE_CLASS paramClass;
  182. D3D_SHADER_VARIABLE_TYPE paramType;
  183. uint8_t columns;
  184. uint8_t rows;
  185. };
  186. static const UniformRemap s_uniformRemap[] =
  187. {
  188. { UniformType::Sampler, D3D_SVC_SCALAR, D3D_SVT_INT, 0, 0 },
  189. { UniformType::Vec4, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  190. { UniformType::Mat3, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 3, 3 },
  191. { UniformType::Mat4, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 4, 4 },
  192. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLER, 0, 0 },
  193. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLER2D, 0, 0 },
  194. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLER3D, 0, 0 },
  195. { UniformType::Sampler, D3D_SVC_OBJECT, D3D_SVT_SAMPLERCUBE, 0, 0 },
  196. };
  197. UniformType::Enum findUniformType(const D3D11_SHADER_TYPE_DESC& constDesc)
  198. {
  199. for (uint32_t ii = 0; ii < BX_COUNTOF(s_uniformRemap); ++ii)
  200. {
  201. const UniformRemap& remap = s_uniformRemap[ii];
  202. if (remap.paramClass == constDesc.Class
  203. && remap.paramType == constDesc.Type)
  204. {
  205. if (D3D_SVC_MATRIX_COLUMNS != constDesc.Class)
  206. {
  207. return remap.id;
  208. }
  209. if (remap.columns == constDesc.Columns
  210. && remap.rows == constDesc.Rows)
  211. {
  212. return remap.id;
  213. }
  214. }
  215. }
  216. return UniformType::Count;
  217. }
  218. static uint32_t s_optimizationLevelD3D11[4] =
  219. {
  220. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  221. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  222. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  223. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  224. };
  225. typedef std::vector<std::string> UniformNameList;
  226. static bool isSampler(D3D_SHADER_VARIABLE_TYPE _svt)
  227. {
  228. switch (_svt)
  229. {
  230. case D3D_SVT_SAMPLER:
  231. case D3D_SVT_SAMPLER1D:
  232. case D3D_SVT_SAMPLER2D:
  233. case D3D_SVT_SAMPLER3D:
  234. case D3D_SVT_SAMPLERCUBE:
  235. return true;
  236. default:
  237. break;
  238. }
  239. return false;
  240. }
  241. bool getReflectionDataD3D9(ID3DBlob* _code, UniformArray& _uniforms, bx::WriterI* _messageWriter)
  242. {
  243. bx::ErrorAssert messageErr;
  244. // see reference for magic values: https://msdn.microsoft.com/en-us/library/ff552891(VS.85).aspx
  245. const uint32_t D3DSIO_COMMENT = 0x0000FFFE;
  246. const uint32_t D3DSIO_END = 0x0000FFFF;
  247. const uint32_t D3DSI_OPCODE_MASK = 0x0000FFFF;
  248. const uint32_t D3DSI_COMMENTSIZE_MASK = 0x7FFF0000;
  249. const uint32_t CTAB_CONSTANT = MAKEFOURCC('C', 'T', 'A', 'B');
  250. // parse the shader blob for the constant table
  251. const size_t codeSize = _code->GetBufferSize();
  252. const uint32_t* ptr = (const uint32_t*)_code->GetBufferPointer();
  253. const uint32_t* end = (const uint32_t*)( (const uint8_t*)ptr + codeSize);
  254. const CTHeader* header = NULL;
  255. ptr++; // first byte is shader type / version; skip it since we already know
  256. while (ptr < end && *ptr != D3DSIO_END)
  257. {
  258. uint32_t cur = *ptr++;
  259. if ( (cur & D3DSI_OPCODE_MASK) != D3DSIO_COMMENT)
  260. {
  261. continue;
  262. }
  263. // try to find CTAB comment block
  264. uint32_t commentSize = (cur & D3DSI_COMMENTSIZE_MASK) >> 16;
  265. uint32_t fourcc = *ptr;
  266. if (fourcc == CTAB_CONSTANT)
  267. {
  268. // found the constant table data
  269. header = (const CTHeader*)(ptr + 1);
  270. uint32_t tableSize = (commentSize - 1) * 4;
  271. if (tableSize < sizeof(CTHeader) || header->Size != sizeof(CTHeader) )
  272. {
  273. bx::write(_messageWriter, &messageErr, "Error: Invalid constant table data\n");
  274. return false;
  275. }
  276. break;
  277. }
  278. // this is a different kind of comment section, so skip over it
  279. ptr += commentSize - 1;
  280. }
  281. if (!header)
  282. {
  283. bx::write(_messageWriter, &messageErr, "Error: Could not find constant table data\n");
  284. return false;
  285. }
  286. const uint8_t* headerBytePtr = (const uint8_t*)header;
  287. const char* creator = (const char*)(headerBytePtr + header->Creator);
  288. BX_UNUSED(creator);
  289. BX_TRACE("Creator: %s 0x%08x", creator, header->Version);
  290. BX_TRACE("Num constants: %d", header->Constants);
  291. BX_TRACE("# cl ty RxC S By Name");
  292. const CTInfo* ctInfoArray = (const CTInfo*)(headerBytePtr + header->ConstantInfo);
  293. for (uint32_t ii = 0; ii < header->Constants; ++ii)
  294. {
  295. const CTInfo& ctInfo = ctInfoArray[ii];
  296. const CTType& ctType = *(const CTType*)(headerBytePtr + ctInfo.TypeInfo);
  297. const char* name = (const char*)(headerBytePtr + ctInfo.Name);
  298. BX_TRACE("%3d %2d %2d [%dx%d] %d %s[%d] c%d (%d)"
  299. , ii
  300. , ctType.Class
  301. , ctType.Type
  302. , ctType.Rows
  303. , ctType.Columns
  304. , ctType.StructMembers
  305. , name
  306. , ctType.Elements
  307. , ctInfo.RegisterIndex
  308. , ctInfo.RegisterCount
  309. );
  310. D3D11_SHADER_TYPE_DESC desc;
  311. desc.Class = (D3D_SHADER_VARIABLE_CLASS)ctType.Class;
  312. desc.Type = (D3D_SHADER_VARIABLE_TYPE)ctType.Type;
  313. desc.Rows = ctType.Rows;
  314. desc.Columns = ctType.Columns;
  315. UniformType::Enum type = findUniformType(desc);
  316. if (UniformType::Count != type)
  317. {
  318. Uniform un;
  319. un.name = '$' == name[0] ? name + 1 : name;
  320. un.type = isSampler(desc.Type)
  321. ? UniformType::Enum(kUniformSamplerBit | type)
  322. : type
  323. ;
  324. un.num = (uint8_t)ctType.Elements;
  325. un.regIndex = ctInfo.RegisterIndex;
  326. un.regCount = ctInfo.RegisterCount;
  327. _uniforms.push_back(un);
  328. }
  329. }
  330. return true;
  331. }
  332. bool getReflectionDataD3D11(ID3DBlob* _code, bool _vshader, UniformArray& _uniforms, uint8_t& _numAttrs, uint16_t* _attrs, uint16_t& _size, UniformNameList& unusedUniforms, bx::WriterI* _messageWriter)
  333. {
  334. bx::Error messageErr;
  335. ID3D11ShaderReflection* reflect = NULL;
  336. HRESULT hr = D3DReflect(_code->GetBufferPointer()
  337. , _code->GetBufferSize()
  338. , s_compiler->IID_ID3D11ShaderReflection
  339. , (void**)&reflect
  340. );
  341. if (FAILED(hr) )
  342. {
  343. bx::write(_messageWriter, &messageErr, "Error: D3DReflect failed 0x%08x\n", (uint32_t)hr);
  344. return false;
  345. }
  346. D3D11_SHADER_DESC desc;
  347. hr = reflect->GetDesc(&desc);
  348. if (FAILED(hr) )
  349. {
  350. bx::write(_messageWriter, &messageErr, "Error: ID3D11ShaderReflection::GetDesc failed 0x%08x\n", (uint32_t)hr);
  351. return false;
  352. }
  353. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  354. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  355. BX_TRACE("Input:");
  356. if (_vshader) // Only care about input semantic on vertex shaders
  357. {
  358. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  359. {
  360. D3D11_SIGNATURE_PARAMETER_DESC spd;
  361. reflect->GetInputParameterDesc(ii, &spd);
  362. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  363. , ii
  364. , spd.SemanticName
  365. , spd.SemanticIndex
  366. , spd.SystemValueType
  367. , spd.ComponentType
  368. , spd.Mask
  369. , spd.Register
  370. );
  371. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, uint8_t(spd.SemanticIndex) );
  372. if (ris.m_attr != bgfx::Attrib::Count)
  373. {
  374. _attrs[_numAttrs] = bgfx::attribToId(ris.m_attr);
  375. ++_numAttrs;
  376. }
  377. }
  378. }
  379. BX_TRACE("Output:");
  380. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  381. {
  382. D3D11_SIGNATURE_PARAMETER_DESC spd;
  383. reflect->GetOutputParameterDesc(ii, &spd);
  384. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  385. }
  386. for (uint32_t ii = 0, num = bx::uint32_min(1, desc.ConstantBuffers); ii < num; ++ii)
  387. {
  388. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  389. D3D11_SHADER_BUFFER_DESC bufferDesc;
  390. hr = cbuffer->GetDesc(&bufferDesc);
  391. _size = (uint16_t)bufferDesc.Size;
  392. if (SUCCEEDED(hr) )
  393. {
  394. BX_TRACE("%s, %d, vars %d, size %d"
  395. , bufferDesc.Name
  396. , bufferDesc.Type
  397. , bufferDesc.Variables
  398. , bufferDesc.Size
  399. );
  400. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  401. {
  402. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  403. ID3D11ShaderReflectionType* type = var->GetType();
  404. D3D11_SHADER_VARIABLE_DESC varDesc;
  405. hr = var->GetDesc(&varDesc);
  406. if (SUCCEEDED(hr) )
  407. {
  408. D3D11_SHADER_TYPE_DESC constDesc;
  409. hr = type->GetDesc(&constDesc);
  410. if (SUCCEEDED(hr) )
  411. {
  412. UniformType::Enum uniformType = findUniformType(constDesc);
  413. if (UniformType::Count != uniformType
  414. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  415. {
  416. Uniform un;
  417. un.name = varDesc.Name;
  418. un.type = uniformType;
  419. un.num = uint8_t(constDesc.Elements);
  420. un.regIndex = uint16_t(varDesc.StartOffset);
  421. un.regCount = uint16_t(bx::alignUp(varDesc.Size, 16) / 16);
  422. _uniforms.push_back(un);
  423. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d (used)"
  424. , varDesc.Name
  425. , varDesc.StartOffset
  426. , varDesc.Size
  427. , varDesc.uFlags
  428. , uniformType
  429. );
  430. }
  431. else
  432. {
  433. if (0 == (varDesc.uFlags & D3D_SVF_USED) )
  434. {
  435. unusedUniforms.push_back(varDesc.Name);
  436. }
  437. BX_TRACE("\t%s, unknown type", varDesc.Name);
  438. }
  439. }
  440. }
  441. }
  442. }
  443. }
  444. BX_TRACE("Bound:");
  445. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  446. {
  447. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  448. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  449. if (SUCCEEDED(hr) )
  450. {
  451. if (D3D_SIT_SAMPLER == bindDesc.Type || D3D_SIT_TEXTURE == bindDesc.Type)
  452. {
  453. BX_TRACE("\t%s, %d, %d, %d"
  454. , bindDesc.Name
  455. , bindDesc.Type
  456. , bindDesc.BindPoint
  457. , bindDesc.BindCount
  458. );
  459. bx::StringView end = bx::strFind(bindDesc.Name, "Sampler");
  460. if (end.isEmpty())
  461. end = bx::strFind(bindDesc.Name, "Texture");
  462. if (!end.isEmpty())
  463. {
  464. Uniform un;
  465. un.name.assign(bindDesc.Name, (end.getPtr() - bindDesc.Name) );
  466. un.type = UniformType::Enum(kUniformSamplerBit | UniformType::Sampler);
  467. un.num = 1;
  468. un.regIndex = uint16_t(bindDesc.BindPoint);
  469. un.regCount = uint16_t(bindDesc.BindCount);
  470. _uniforms.push_back(un);
  471. }
  472. }
  473. else
  474. {
  475. BX_TRACE("\t%s, unknown bind data", bindDesc.Name);
  476. }
  477. }
  478. }
  479. if (NULL != reflect)
  480. {
  481. reflect->Release();
  482. }
  483. return true;
  484. }
  485. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _shaderWriter, bx::WriterI* _messageWriter, bool _firstPass)
  486. {
  487. bx::Error messageErr;
  488. const char* profile = _options.profile.c_str();
  489. if (profile[0] == '\0')
  490. {
  491. bx::write(_messageWriter, &messageErr, "Error: Shader profile must be specified.\n");
  492. return false;
  493. }
  494. char profileAndType[8] = {};
  495. profileAndType[0] = (_options.shaderType == 'f') ? 'p' : _options.shaderType;
  496. bx::strCat(profileAndType, BX_COUNTOF(profileAndType), profile);
  497. s_compiler = load(_messageWriter);
  498. bool result = false;
  499. bool debug = _options.debugInformation;
  500. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  501. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  502. flags |= _options.avoidFlowControl ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  503. flags |= _options.noPreshader ? D3DCOMPILE_NO_PRESHADER : 0;
  504. flags |= _options.partialPrecision ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  505. flags |= _options.preferFlowControl ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  506. flags |= _options.backwardsCompatibility ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  507. bool werror = _options.warningsAreErrors;
  508. if (werror)
  509. {
  510. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  511. }
  512. if (_options.optimize )
  513. {
  514. uint32_t optimization = bx::uint32_min(_options.optimizationLevel, BX_COUNTOF(s_optimizationLevelD3D11) - 1);
  515. flags |= s_optimizationLevelD3D11[optimization];
  516. }
  517. else
  518. {
  519. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  520. }
  521. BX_TRACE("Profile: %s", profile);
  522. BX_TRACE("Flags: 0x%08x", flags);
  523. ID3DBlob* code;
  524. ID3DBlob* errorMsg;
  525. // Output preprocessed shader so that HLSL can be debugged via GPA
  526. // or PIX. Compiling through memory won't embed preprocessed shader
  527. // file path.
  528. std::string hlslfp;
  529. if (debug)
  530. {
  531. hlslfp = _options.outputFilePath + ".hlsl";
  532. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  533. }
  534. bx::ErrorAssert err;
  535. HRESULT hr = D3DCompile(_code.c_str()
  536. , _code.size()
  537. , hlslfp.c_str()
  538. , NULL
  539. , NULL
  540. , "main"
  541. , profileAndType
  542. , flags
  543. , 0
  544. , &code
  545. , &errorMsg
  546. );
  547. if (FAILED(hr)
  548. || (werror && NULL != errorMsg) )
  549. {
  550. const char* log = (char*)errorMsg->GetBufferPointer();
  551. int32_t line = 0;
  552. int32_t column = 0;
  553. int32_t start = 0;
  554. int32_t end = INT32_MAX;
  555. if (!hlslfp.empty())
  556. {
  557. bx::StringView logfp = bx::strFind(log, hlslfp.c_str() );
  558. if (!logfp.isEmpty() )
  559. {
  560. log = logfp.getPtr() + hlslfp.length();
  561. }
  562. }
  563. bool found = false
  564. || 2 == sscanf(log, "(%u,%u", &line, &column)
  565. || 2 == sscanf(log, " :%u:%u: ", &line, &column)
  566. ;
  567. if (found
  568. && 0 != line)
  569. {
  570. start = bx::uint32_imax(1, line - 10);
  571. end = start + 20;
  572. }
  573. printCode(_code.c_str(), line, start, end, column);
  574. bx::write(_messageWriter, &messageErr, "Error: D3DCompile failed 0x%08x %s\n", (uint32_t)hr, log);
  575. errorMsg->Release();
  576. return false;
  577. }
  578. UniformArray uniforms;
  579. uint8_t numAttrs = 0;
  580. uint16_t attrs[bgfx::Attrib::Count];
  581. uint16_t size = 0;
  582. if (_version < 400)
  583. {
  584. if (!getReflectionDataD3D9(code, uniforms, _messageWriter) )
  585. {
  586. bx::write(_messageWriter, &messageErr, "Error: Unable to get D3D9 reflection data.\n");
  587. goto error;
  588. }
  589. }
  590. else
  591. {
  592. UniformNameList unusedUniforms;
  593. if (!getReflectionDataD3D11(code, profileAndType[0] == 'v', uniforms, numAttrs, attrs, size, unusedUniforms, _messageWriter) )
  594. {
  595. bx::write(_messageWriter, &messageErr, "Error: Unable to get D3D11 reflection data.\n");
  596. goto error;
  597. }
  598. if (_firstPass
  599. && unusedUniforms.size() > 0)
  600. {
  601. // first time through, we just find unused uniforms and get rid of them
  602. std::string output;
  603. bx::LineReader reader(_code.c_str() );
  604. while (!reader.isDone() )
  605. {
  606. bx::StringView strLine = reader.next();
  607. std::string replaceOutput;
  608. bx::StringView str = strFind(strLine, "uniform ");
  609. if (!str.isEmpty())
  610. {
  611. std::string lineToReplace(strLine.getPtr(), 0, strLine.getLength());
  612. for (UniformNameList::iterator it = unusedUniforms.begin(); it != unusedUniforms.end();)
  613. {
  614. // matching lines like: uniform u_name;
  615. // we want to replace "uniform" with "static" so that it's no longer
  616. // included in the uniform blob that the application must upload
  617. // we can't just remove them, because unused functions might still reference
  618. // them and cause a compile error when they're gone
  619. auto identifier = bx::findIdentifierMatch(strLine, it->c_str());
  620. if (!identifier.isEmpty())
  621. {
  622. bx::StringView definePrefix = bx::StringView(strLine.getPtr(), identifier.getPtr());
  623. bx::StringView semicolon = strRFind(definePrefix, ';');
  624. if (!semicolon.isEmpty())
  625. {
  626. bx::StringView uniformDefine = bx::StringView(semicolon.getPtr(), strLine.getTerm());
  627. str = strFind(uniformDefine, "uniform ");
  628. }
  629. replaceOutput.clear();
  630. replaceOutput.append(strLine.getPtr(), str.getPtr());
  631. replaceOutput += "static ";
  632. replaceOutput.append(str.getTerm(), strLine.getTerm());
  633. lineToReplace = replaceOutput;
  634. strLine = bx::StringView(lineToReplace.c_str());
  635. it = unusedUniforms.erase(it);
  636. }
  637. else
  638. {
  639. ++it;
  640. }
  641. }
  642. }
  643. if (!replaceOutput.empty())
  644. {
  645. output.append(replaceOutput);
  646. }
  647. else
  648. {
  649. output.append(strLine.getPtr(), strLine.getTerm() );
  650. }
  651. output += "\n";
  652. }
  653. // recompile with the unused uniforms converted to statics
  654. return compile(_options, _version, output.c_str(), _shaderWriter, _messageWriter, false);
  655. }
  656. }
  657. {
  658. uint16_t count = (uint16_t)uniforms.size();
  659. bx::write(_shaderWriter, count, &err);
  660. uint32_t fragmentBit = profileAndType[0] == 'p' ? kUniformFragmentBit : 0;
  661. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  662. {
  663. const Uniform& un = *it;
  664. uint8_t nameSize = (uint8_t)un.name.size();
  665. bx::write(_shaderWriter, nameSize, &err);
  666. bx::write(_shaderWriter, un.name.c_str(), nameSize, &err);
  667. uint8_t type = uint8_t(un.type | fragmentBit);
  668. bx::write(_shaderWriter, type, &err);
  669. bx::write(_shaderWriter, un.num, &err);
  670. bx::write(_shaderWriter, un.regIndex, &err);
  671. bx::write(_shaderWriter, un.regCount, &err);
  672. bx::write(_shaderWriter, un.texComponent, &err);
  673. bx::write(_shaderWriter, un.texDimension, &err);
  674. bx::write(_shaderWriter, un.texFormat, &err);
  675. BX_TRACE("%s, %s, %d, %d, %d"
  676. , un.name.c_str()
  677. , getUniformTypeName(UniformType::Enum(un.type & ~kUniformMask))
  678. , un.num
  679. , un.regIndex
  680. , un.regCount
  681. );
  682. }
  683. }
  684. {
  685. ID3DBlob* stripped;
  686. hr = D3DStripShader(code->GetBufferPointer()
  687. , code->GetBufferSize()
  688. , D3DCOMPILER_STRIP_REFLECTION_DATA
  689. | D3DCOMPILER_STRIP_TEST_BLOBS
  690. , &stripped
  691. );
  692. if (SUCCEEDED(hr) )
  693. {
  694. code->Release();
  695. code = stripped;
  696. }
  697. }
  698. {
  699. uint32_t shaderSize = uint32_t(code->GetBufferSize() );
  700. bx::write(_shaderWriter, shaderSize, &err);
  701. bx::write(_shaderWriter, code->GetBufferPointer(), shaderSize, &err);
  702. uint8_t nul = 0;
  703. bx::write(_shaderWriter, nul, &err);
  704. }
  705. if (_version >= 400)
  706. {
  707. bx::write(_shaderWriter, numAttrs, &err);
  708. bx::write(_shaderWriter, attrs, numAttrs*sizeof(uint16_t), &err);
  709. bx::write(_shaderWriter, size, &err);
  710. }
  711. if (_options.disasm )
  712. {
  713. ID3DBlob* disasm;
  714. D3DDisassemble(code->GetBufferPointer()
  715. , code->GetBufferSize()
  716. , 0
  717. , NULL
  718. , &disasm
  719. );
  720. if (NULL != disasm)
  721. {
  722. std::string disasmfp = _options.outputFilePath + ".disasm";
  723. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  724. disasm->Release();
  725. }
  726. }
  727. if (NULL != errorMsg)
  728. {
  729. errorMsg->Release();
  730. }
  731. result = true;
  732. error:
  733. code->Release();
  734. unload();
  735. return result;
  736. }
  737. } // namespace hlsl
  738. bool compileHLSLShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _shaderWriter, bx::WriterI* _messageWriter)
  739. {
  740. return hlsl::compile(_options, _version, _code, _shaderWriter, _messageWriter, true);
  741. }
  742. } // namespace bgfx
  743. #else
  744. namespace bgfx
  745. {
  746. bool compileHLSLShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _shaderWriter, bx::WriterI* _messageWriter)
  747. {
  748. BX_UNUSED(_options, _version, _code, _shaderWriter);
  749. bx::Error messageErr;
  750. bx::write(_messageWriter, &messageErr, "HLSL compiler is not supported on this platform.\n");
  751. return false;
  752. }
  753. } // namespace bgfx
  754. #endif // SHADERC_CONFIG_HLSL