shaderc_hlsl.cpp 21 KB

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