shaderc_hlsl.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. /*
  2. * Copyright 2011-2017 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  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()
  70. {
  71. for (uint32_t ii = 0; ii < BX_COUNTOF(s_d3dcompiler); ++ii)
  72. {
  73. const D3DCompiler* compiler = &s_d3dcompiler[ii];
  74. s_d3dcompilerdll = bx::dlopen(compiler->fileName);
  75. if (NULL == s_d3dcompilerdll)
  76. {
  77. continue;
  78. }
  79. D3DCompile = (PFN_D3D_COMPILE )bx::dlsym(s_d3dcompilerdll, "D3DCompile");
  80. D3DDisassemble = (PFN_D3D_DISASSEMBLE )bx::dlsym(s_d3dcompilerdll, "D3DDisassemble");
  81. D3DReflect = (PFN_D3D_REFLECT )bx::dlsym(s_d3dcompilerdll, "D3DReflect");
  82. D3DStripShader = (PFN_D3D_STRIP_SHADER)bx::dlsym(s_d3dcompilerdll, "D3DStripShader");
  83. if (NULL == D3DCompile
  84. || NULL == D3DDisassemble
  85. || NULL == D3DReflect
  86. || NULL == D3DStripShader)
  87. {
  88. bx::dlclose(s_d3dcompilerdll);
  89. continue;
  90. }
  91. if (g_verbose)
  92. {
  93. char filePath[MAX_PATH];
  94. GetModuleFileNameA( (HMODULE)s_d3dcompilerdll, filePath, sizeof(filePath) );
  95. BX_TRACE("Loaded %s compiler (%s).", compiler->fileName, filePath);
  96. }
  97. return compiler;
  98. }
  99. fprintf(stderr, "Error: Unable to open D3DCompiler_*.dll shader compiler.\n");
  100. return NULL;
  101. }
  102. void unload()
  103. {
  104. bx::dlclose(s_d3dcompilerdll);
  105. }
  106. struct CTHeader
  107. {
  108. uint32_t Size;
  109. uint32_t Creator;
  110. uint32_t Version;
  111. uint32_t Constants;
  112. uint32_t ConstantInfo;
  113. uint32_t Flags;
  114. uint32_t Target;
  115. };
  116. struct CTInfo
  117. {
  118. uint32_t Name;
  119. uint16_t RegisterSet;
  120. uint16_t RegisterIndex;
  121. uint16_t RegisterCount;
  122. uint16_t Reserved;
  123. uint32_t TypeInfo;
  124. uint32_t DefaultValue;
  125. };
  126. struct CTType
  127. {
  128. uint16_t Class;
  129. uint16_t Type;
  130. uint16_t Rows;
  131. uint16_t Columns;
  132. uint16_t Elements;
  133. uint16_t StructMembers;
  134. uint32_t StructMemberInfo;
  135. };
  136. struct RemapInputSemantic
  137. {
  138. bgfx::Attrib::Enum m_attr;
  139. const char* m_name;
  140. uint8_t m_index;
  141. };
  142. static const RemapInputSemantic s_remapInputSemantic[bgfx::Attrib::Count + 1] =
  143. {
  144. { bgfx::Attrib::Position, "POSITION", 0 },
  145. { bgfx::Attrib::Normal, "NORMAL", 0 },
  146. { bgfx::Attrib::Tangent, "TANGENT", 0 },
  147. { bgfx::Attrib::Bitangent, "BITANGENT", 0 },
  148. { bgfx::Attrib::Color0, "COLOR", 0 },
  149. { bgfx::Attrib::Color1, "COLOR", 1 },
  150. { bgfx::Attrib::Indices, "BLENDINDICES", 0 },
  151. { bgfx::Attrib::Weight, "BLENDWEIGHT", 0 },
  152. { bgfx::Attrib::TexCoord0, "TEXCOORD", 0 },
  153. { bgfx::Attrib::TexCoord1, "TEXCOORD", 1 },
  154. { bgfx::Attrib::TexCoord2, "TEXCOORD", 2 },
  155. { bgfx::Attrib::TexCoord3, "TEXCOORD", 3 },
  156. { bgfx::Attrib::TexCoord4, "TEXCOORD", 4 },
  157. { bgfx::Attrib::TexCoord5, "TEXCOORD", 5 },
  158. { bgfx::Attrib::TexCoord6, "TEXCOORD", 6 },
  159. { bgfx::Attrib::TexCoord7, "TEXCOORD", 7 },
  160. { bgfx::Attrib::Count, "", 0 },
  161. };
  162. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  163. {
  164. for (uint32_t ii = 0; ii < bgfx::Attrib::Count; ++ii)
  165. {
  166. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  167. if (0 == strcmp(ris.m_name, _name)
  168. && ris.m_index == _index)
  169. {
  170. return ris;
  171. }
  172. }
  173. return s_remapInputSemantic[bgfx::Attrib::Count];
  174. }
  175. struct UniformRemap
  176. {
  177. UniformType::Enum id;
  178. D3D_SHADER_VARIABLE_CLASS paramClass;
  179. D3D_SHADER_VARIABLE_TYPE paramType;
  180. uint8_t columns;
  181. uint8_t rows;
  182. };
  183. static const UniformRemap s_uniformRemap[] =
  184. {
  185. { UniformType::Int1, D3D_SVC_SCALAR, D3D_SVT_INT, 0, 0 },
  186. { UniformType::Vec4, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  187. { UniformType::Mat3, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 3, 3 },
  188. { UniformType::Mat4, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 4, 4 },
  189. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER, 0, 0 },
  190. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER2D, 0, 0 },
  191. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER3D, 0, 0 },
  192. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLERCUBE, 0, 0 },
  193. };
  194. UniformType::Enum findUniformType(const D3D11_SHADER_TYPE_DESC& constDesc)
  195. {
  196. for (uint32_t ii = 0; ii < BX_COUNTOF(s_uniformRemap); ++ii)
  197. {
  198. const UniformRemap& remap = s_uniformRemap[ii];
  199. if (remap.paramClass == constDesc.Class
  200. && remap.paramType == constDesc.Type)
  201. {
  202. if (D3D_SVC_MATRIX_COLUMNS != constDesc.Class)
  203. {
  204. return remap.id;
  205. }
  206. if (remap.columns == constDesc.Columns
  207. && remap.rows == constDesc.Rows)
  208. {
  209. return remap.id;
  210. }
  211. }
  212. }
  213. return UniformType::Count;
  214. }
  215. static uint32_t s_optimizationLevelD3D11[4] =
  216. {
  217. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  218. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  219. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  220. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  221. };
  222. typedef std::vector<std::string> UniformNameList;
  223. static bool isSampler(D3D_SHADER_VARIABLE_TYPE _svt)
  224. {
  225. switch (_svt)
  226. {
  227. case D3D_SVT_SAMPLER:
  228. case D3D_SVT_SAMPLER1D:
  229. case D3D_SVT_SAMPLER2D:
  230. case D3D_SVT_SAMPLER3D:
  231. case D3D_SVT_SAMPLERCUBE:
  232. return true;
  233. default:
  234. break;
  235. }
  236. return false;
  237. }
  238. bool getReflectionDataD3D9(ID3DBlob* _code, UniformArray& _uniforms)
  239. {
  240. // see reference for magic values: https://msdn.microsoft.com/en-us/library/ff552891(VS.85).aspx
  241. const uint32_t D3DSIO_COMMENT = 0x0000FFFE;
  242. const uint32_t D3DSIO_END = 0x0000FFFF;
  243. const uint32_t D3DSI_OPCODE_MASK = 0x0000FFFF;
  244. const uint32_t D3DSI_COMMENTSIZE_MASK = 0x7FFF0000;
  245. const uint32_t CTAB_CONSTANT = MAKEFOURCC('C', 'T', 'A', 'B');
  246. // parse the shader blob for the constant table
  247. const size_t codeSize = _code->GetBufferSize();
  248. const uint32_t* ptr = (const uint32_t*)_code->GetBufferPointer();
  249. const uint32_t* end = (const uint32_t*)( (const uint8_t*)ptr + codeSize);
  250. const CTHeader* header = NULL;
  251. ptr++; // first byte is shader type / version; skip it since we already know
  252. while (ptr < end && *ptr != D3DSIO_END)
  253. {
  254. uint32_t cur = *ptr++;
  255. if ( (cur & D3DSI_OPCODE_MASK) != D3DSIO_COMMENT)
  256. {
  257. continue;
  258. }
  259. // try to find CTAB comment block
  260. uint32_t commentSize = (cur & D3DSI_COMMENTSIZE_MASK) >> 16;
  261. uint32_t fourcc = *ptr;
  262. if (fourcc == CTAB_CONSTANT)
  263. {
  264. // found the constant table data
  265. header = (const CTHeader*)(ptr + 1);
  266. uint32_t tableSize = (commentSize - 1) * 4;
  267. if (tableSize < sizeof(CTHeader) || header->Size != sizeof(CTHeader) )
  268. {
  269. fprintf(stderr, "Error: Invalid constant table data\n");
  270. return false;
  271. }
  272. break;
  273. }
  274. // this is a different kind of comment section, so skip over it
  275. ptr += commentSize - 1;
  276. }
  277. if (!header)
  278. {
  279. fprintf(stderr, "Error: Could not find constant table data\n");
  280. return false;
  281. }
  282. const uint8_t* headerBytePtr = (const uint8_t*)header;
  283. const char* creator = (const char*)(headerBytePtr + header->Creator);
  284. BX_TRACE("Creator: %s 0x%08x", creator, header->Version);
  285. BX_TRACE("Num constants: %d", header->Constants);
  286. BX_TRACE("# cl ty RxC S By Name");
  287. const CTInfo* ctInfoArray = (const CTInfo*)(headerBytePtr + header->ConstantInfo);
  288. for (uint32_t ii = 0; ii < header->Constants; ++ii)
  289. {
  290. const CTInfo& ctInfo = ctInfoArray[ii];
  291. const CTType& ctType = *(const CTType*)(headerBytePtr + ctInfo.TypeInfo);
  292. const char* name = (const char*)(headerBytePtr + ctInfo.Name);
  293. BX_TRACE("%3d %2d %2d [%dx%d] %d %s[%d] c%d (%d)"
  294. , ii
  295. , ctType.Class
  296. , ctType.Type
  297. , ctType.Rows
  298. , ctType.Columns
  299. , ctType.StructMembers
  300. , name
  301. , ctType.Elements
  302. , ctInfo.RegisterIndex
  303. , ctInfo.RegisterCount
  304. );
  305. D3D11_SHADER_TYPE_DESC desc;
  306. desc.Class = (D3D_SHADER_VARIABLE_CLASS)ctType.Class;
  307. desc.Type = (D3D_SHADER_VARIABLE_TYPE)ctType.Type;
  308. desc.Rows = ctType.Rows;
  309. desc.Columns = ctType.Columns;
  310. UniformType::Enum type = findUniformType(desc);
  311. if (UniformType::Count != type)
  312. {
  313. Uniform un;
  314. un.name = '$' == name[0] ? name + 1 : name;
  315. un.type = isSampler(desc.Type)
  316. ? UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | type)
  317. : type
  318. ;
  319. un.num = (uint8_t)ctType.Elements;
  320. un.regIndex = ctInfo.RegisterIndex;
  321. un.regCount = ctInfo.RegisterCount;
  322. _uniforms.push_back(un);
  323. }
  324. }
  325. return true;
  326. }
  327. bool getReflectionDataD3D11(ID3DBlob* _code, bool _vshader, UniformArray& _uniforms, uint8_t& _numAttrs, uint16_t* _attrs, uint16_t& _size, UniformNameList& unusedUniforms)
  328. {
  329. ID3D11ShaderReflection* reflect = NULL;
  330. HRESULT hr = D3DReflect(_code->GetBufferPointer()
  331. , _code->GetBufferSize()
  332. , s_compiler->IID_ID3D11ShaderReflection
  333. , (void**)&reflect
  334. );
  335. if (FAILED(hr) )
  336. {
  337. fprintf(stderr, "Error: D3DReflect failed 0x%08x\n", (uint32_t)hr);
  338. return false;
  339. }
  340. D3D11_SHADER_DESC desc;
  341. hr = reflect->GetDesc(&desc);
  342. if (FAILED(hr) )
  343. {
  344. fprintf(stderr, "Error: ID3D11ShaderReflection::GetDesc failed 0x%08x\n", (uint32_t)hr);
  345. return false;
  346. }
  347. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  348. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  349. BX_TRACE("Input:");
  350. if (_vshader) // Only care about input semantic on vertex shaders
  351. {
  352. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  353. {
  354. D3D11_SIGNATURE_PARAMETER_DESC spd;
  355. reflect->GetInputParameterDesc(ii, &spd);
  356. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  357. , ii
  358. , spd.SemanticName
  359. , spd.SemanticIndex
  360. , spd.SystemValueType
  361. , spd.ComponentType
  362. , spd.Mask
  363. , spd.Register
  364. );
  365. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
  366. if (ris.m_attr != bgfx::Attrib::Count)
  367. {
  368. _attrs[_numAttrs] = bgfx::attribToId(ris.m_attr);
  369. ++_numAttrs;
  370. }
  371. }
  372. }
  373. BX_TRACE("Output:");
  374. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  375. {
  376. D3D11_SIGNATURE_PARAMETER_DESC spd;
  377. reflect->GetOutputParameterDesc(ii, &spd);
  378. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  379. }
  380. for (uint32_t ii = 0, num = bx::uint32_min(1, desc.ConstantBuffers); ii < num; ++ii)
  381. {
  382. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  383. D3D11_SHADER_BUFFER_DESC bufferDesc;
  384. hr = cbuffer->GetDesc(&bufferDesc);
  385. _size = (uint16_t)bufferDesc.Size;
  386. if (SUCCEEDED(hr) )
  387. {
  388. BX_TRACE("%s, %d, vars %d, size %d"
  389. , bufferDesc.Name
  390. , bufferDesc.Type
  391. , bufferDesc.Variables
  392. , bufferDesc.Size
  393. );
  394. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  395. {
  396. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  397. ID3D11ShaderReflectionType* type = var->GetType();
  398. D3D11_SHADER_VARIABLE_DESC varDesc;
  399. hr = var->GetDesc(&varDesc);
  400. if (SUCCEEDED(hr) )
  401. {
  402. D3D11_SHADER_TYPE_DESC constDesc;
  403. hr = type->GetDesc(&constDesc);
  404. if (SUCCEEDED(hr) )
  405. {
  406. UniformType::Enum uniformType = findUniformType(constDesc);
  407. if (UniformType::Count != uniformType
  408. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  409. {
  410. Uniform un;
  411. un.name = varDesc.Name;
  412. un.type = uniformType;
  413. un.num = constDesc.Elements;
  414. un.regIndex = varDesc.StartOffset;
  415. un.regCount = BX_ALIGN_16(varDesc.Size) / 16;
  416. _uniforms.push_back(un);
  417. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d (used)"
  418. , varDesc.Name
  419. , varDesc.StartOffset
  420. , varDesc.Size
  421. , varDesc.uFlags
  422. , uniformType
  423. );
  424. }
  425. else
  426. {
  427. if (0 == (varDesc.uFlags & D3D_SVF_USED) )
  428. {
  429. unusedUniforms.push_back(varDesc.Name);
  430. }
  431. BX_TRACE("\t%s, unknown type", varDesc.Name);
  432. }
  433. }
  434. }
  435. }
  436. }
  437. }
  438. BX_TRACE("Bound:");
  439. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  440. {
  441. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  442. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  443. if (SUCCEEDED(hr) )
  444. {
  445. if (D3D_SIT_SAMPLER == bindDesc.Type)
  446. {
  447. BX_TRACE("\t%s, %d, %d, %d"
  448. , bindDesc.Name
  449. , bindDesc.Type
  450. , bindDesc.BindPoint
  451. , bindDesc.BindCount
  452. );
  453. const char * end = strstr(bindDesc.Name, "Sampler");
  454. if (NULL != end)
  455. {
  456. Uniform un;
  457. un.name.assign(bindDesc.Name, (end - bindDesc.Name) );
  458. un.type = UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | UniformType::Int1);
  459. un.num = 1;
  460. un.regIndex = bindDesc.BindPoint;
  461. un.regCount = bindDesc.BindCount;
  462. _uniforms.push_back(un);
  463. }
  464. }
  465. }
  466. }
  467. if (NULL != reflect)
  468. {
  469. reflect->Release();
  470. }
  471. return true;
  472. }
  473. static bool compile(bx::CommandLine& _cmdLine, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  474. {
  475. const char* profile = _cmdLine.findOption('p', "profile");
  476. if (NULL == profile)
  477. {
  478. fprintf(stderr, "Error: Shader profile must be specified.\n");
  479. return false;
  480. }
  481. s_compiler = load();
  482. bool result = false;
  483. bool debug = _cmdLine.hasArg('\0', "debug");
  484. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  485. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  486. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  487. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
  488. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  489. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  490. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  491. bool werror = _cmdLine.hasArg('\0', "Werror");
  492. if (werror)
  493. {
  494. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  495. }
  496. uint32_t optimization = 3;
  497. if (_cmdLine.hasArg(optimization, 'O') )
  498. {
  499. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelD3D11) - 1);
  500. flags |= s_optimizationLevelD3D11[optimization];
  501. }
  502. else
  503. {
  504. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  505. }
  506. BX_TRACE("Profile: %s", profile);
  507. BX_TRACE("Flags: 0x%08x", flags);
  508. ID3DBlob* code;
  509. ID3DBlob* errorMsg;
  510. // Output preprocessed shader so that HLSL can be debugged via GPA
  511. // or PIX. Compiling through memory won't embed preprocessed shader
  512. // file path.
  513. std::string hlslfp;
  514. if (debug)
  515. {
  516. hlslfp = _cmdLine.findOption('o');
  517. hlslfp += ".hlsl";
  518. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  519. }
  520. HRESULT hr = D3DCompile(_code.c_str()
  521. , _code.size()
  522. , hlslfp.c_str()
  523. , NULL
  524. , NULL
  525. , "main"
  526. , profile
  527. , flags
  528. , 0
  529. , &code
  530. , &errorMsg
  531. );
  532. if (FAILED(hr)
  533. || (werror && NULL != errorMsg) )
  534. {
  535. const char* log = (char*)errorMsg->GetBufferPointer();
  536. int32_t line = 0;
  537. int32_t column = 0;
  538. int32_t start = 0;
  539. int32_t end = INT32_MAX;
  540. bool found = false
  541. || 2 == sscanf(log, "(%u,%u):", &line, &column)
  542. || 2 == sscanf(log, " :%u:%u: ", &line, &column)
  543. ;
  544. if (found
  545. && 0 != line)
  546. {
  547. start = bx::uint32_imax(1, line - 10);
  548. end = start + 20;
  549. }
  550. printCode(_code.c_str(), line, start, end, column);
  551. fprintf(stderr, "Error: D3DCompile failed 0x%08x %s\n", (uint32_t)hr, log);
  552. errorMsg->Release();
  553. return false;
  554. }
  555. UniformArray uniforms;
  556. uint8_t numAttrs = 0;
  557. uint16_t attrs[bgfx::Attrib::Count];
  558. uint16_t size = 0;
  559. if (_version == 9)
  560. {
  561. if (!getReflectionDataD3D9(code, uniforms) )
  562. {
  563. fprintf(stderr, "Error: Unable to get D3D9 reflection data.\n");
  564. goto error;
  565. }
  566. }
  567. else
  568. {
  569. UniformNameList unusedUniforms;
  570. if (!getReflectionDataD3D11(code, profile[0] == 'v', uniforms, numAttrs, attrs, size, unusedUniforms) )
  571. {
  572. fprintf(stderr, "Error: Unable to get D3D11 reflection data.\n");
  573. goto error;
  574. }
  575. if (_firstPass
  576. && unusedUniforms.size() > 0)
  577. {
  578. const size_t strLength = strlen("uniform");
  579. // first time through, we just find unused uniforms and get rid of them
  580. std::string output;
  581. LineReader reader(_code.c_str() );
  582. while (!reader.isEof() )
  583. {
  584. std::string line = reader.getLine();
  585. for (UniformNameList::iterator it = unusedUniforms.begin(), itEnd = unusedUniforms.end(); it != itEnd; ++it)
  586. {
  587. size_t index = line.find("uniform ");
  588. if (index == std::string::npos)
  589. {
  590. continue;
  591. }
  592. // matching lines like: uniform u_name;
  593. // we want to replace "uniform" with "static" so that it's no longer
  594. // included in the uniform blob that the application must upload
  595. // we can't just remove them, because unused functions might still reference
  596. // them and cause a compile error when they're gone
  597. if (!!bx::findIdentifierMatch(line.c_str(), it->c_str() ) )
  598. {
  599. line = line.replace(index, strLength, "static");
  600. unusedUniforms.erase(it);
  601. break;
  602. }
  603. }
  604. output += line;
  605. }
  606. // recompile with the unused uniforms converted to statics
  607. return compile(_cmdLine, _version, output.c_str(), _writer, false);
  608. }
  609. }
  610. {
  611. uint16_t count = (uint16_t)uniforms.size();
  612. bx::write(_writer, count);
  613. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  614. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  615. {
  616. const Uniform& un = *it;
  617. uint8_t nameSize = (uint8_t)un.name.size();
  618. bx::write(_writer, nameSize);
  619. bx::write(_writer, un.name.c_str(), nameSize);
  620. uint8_t type = un.type | fragmentBit;
  621. bx::write(_writer, type);
  622. bx::write(_writer, un.num);
  623. bx::write(_writer, un.regIndex);
  624. bx::write(_writer, un.regCount);
  625. BX_TRACE("%s, %s, %d, %d, %d"
  626. , un.name.c_str()
  627. , getUniformTypeName(un.type)
  628. , un.num
  629. , un.regIndex
  630. , un.regCount
  631. );
  632. }
  633. }
  634. {
  635. ID3DBlob* stripped;
  636. hr = D3DStripShader(code->GetBufferPointer()
  637. , code->GetBufferSize()
  638. , D3DCOMPILER_STRIP_REFLECTION_DATA
  639. | D3DCOMPILER_STRIP_TEST_BLOBS
  640. , &stripped
  641. );
  642. if (SUCCEEDED(hr) )
  643. {
  644. code->Release();
  645. code = stripped;
  646. }
  647. }
  648. {
  649. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  650. bx::write(_writer, shaderSize);
  651. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  652. uint8_t nul = 0;
  653. bx::write(_writer, nul);
  654. }
  655. if (_version > 9)
  656. {
  657. bx::write(_writer, numAttrs);
  658. bx::write(_writer, attrs, numAttrs*sizeof(uint16_t) );
  659. bx::write(_writer, size);
  660. }
  661. if (_cmdLine.hasArg('\0', "disasm") )
  662. {
  663. ID3DBlob* disasm;
  664. D3DDisassemble(code->GetBufferPointer()
  665. , code->GetBufferSize()
  666. , 0
  667. , NULL
  668. , &disasm
  669. );
  670. if (NULL != disasm)
  671. {
  672. std::string disasmfp = _cmdLine.findOption('o');
  673. disasmfp += ".disasm";
  674. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  675. disasm->Release();
  676. }
  677. }
  678. if (NULL != errorMsg)
  679. {
  680. errorMsg->Release();
  681. }
  682. result = true;
  683. error:
  684. code->Release();
  685. unload();
  686. return result;
  687. }
  688. } // namespace hlsl
  689. bool compileHLSLShader(bx::CommandLine& _cmdLine, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  690. {
  691. return hlsl::compile(_cmdLine, _version, _code, _writer, true);
  692. }
  693. } // namespace bgfx
  694. #else
  695. namespace bgfx
  696. {
  697. bool compileHLSLShader(bx::CommandLine& _cmdLine, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  698. {
  699. BX_UNUSED(_cmdLine, _version, _code, _writer);
  700. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  701. return false;
  702. }
  703. } // namespace bgfx
  704. #endif // SHADERC_CONFIG_HLSL