shaderc_hlsl.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. /*
  2. * Copyright 2011-2018 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::Color2, "COLOR", 2 },
  151. { bgfx::Attrib::Color3, "COLOR", 3 },
  152. { bgfx::Attrib::Indices, "BLENDINDICES", 0 },
  153. { bgfx::Attrib::Weight, "BLENDWEIGHT", 0 },
  154. { bgfx::Attrib::TexCoord0, "TEXCOORD", 0 },
  155. { bgfx::Attrib::TexCoord1, "TEXCOORD", 1 },
  156. { bgfx::Attrib::TexCoord2, "TEXCOORD", 2 },
  157. { bgfx::Attrib::TexCoord3, "TEXCOORD", 3 },
  158. { bgfx::Attrib::TexCoord4, "TEXCOORD", 4 },
  159. { bgfx::Attrib::TexCoord5, "TEXCOORD", 5 },
  160. { bgfx::Attrib::TexCoord6, "TEXCOORD", 6 },
  161. { bgfx::Attrib::TexCoord7, "TEXCOORD", 7 },
  162. { bgfx::Attrib::Count, "", 0 },
  163. };
  164. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  165. {
  166. for (uint32_t ii = 0; ii < bgfx::Attrib::Count; ++ii)
  167. {
  168. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  169. if (0 == bx::strCmp(ris.m_name, _name)
  170. && ris.m_index == _index)
  171. {
  172. return ris;
  173. }
  174. }
  175. return s_remapInputSemantic[bgfx::Attrib::Count];
  176. }
  177. struct UniformRemap
  178. {
  179. UniformType::Enum id;
  180. D3D_SHADER_VARIABLE_CLASS paramClass;
  181. D3D_SHADER_VARIABLE_TYPE paramType;
  182. uint8_t columns;
  183. uint8_t rows;
  184. };
  185. static const UniformRemap s_uniformRemap[] =
  186. {
  187. { UniformType::Int1, D3D_SVC_SCALAR, D3D_SVT_INT, 0, 0 },
  188. { UniformType::Vec4, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  189. { UniformType::Mat3, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 3, 3 },
  190. { UniformType::Mat4, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 4, 4 },
  191. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER, 0, 0 },
  192. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER2D, 0, 0 },
  193. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLER3D, 0, 0 },
  194. { UniformType::Int1, D3D_SVC_OBJECT, D3D_SVT_SAMPLERCUBE, 0, 0 },
  195. };
  196. UniformType::Enum findUniformType(const D3D11_SHADER_TYPE_DESC& constDesc)
  197. {
  198. for (uint32_t ii = 0; ii < BX_COUNTOF(s_uniformRemap); ++ii)
  199. {
  200. const UniformRemap& remap = s_uniformRemap[ii];
  201. if (remap.paramClass == constDesc.Class
  202. && remap.paramType == constDesc.Type)
  203. {
  204. if (D3D_SVC_MATRIX_COLUMNS != constDesc.Class)
  205. {
  206. return remap.id;
  207. }
  208. if (remap.columns == constDesc.Columns
  209. && remap.rows == constDesc.Rows)
  210. {
  211. return remap.id;
  212. }
  213. }
  214. }
  215. return UniformType::Count;
  216. }
  217. static uint32_t s_optimizationLevelD3D11[4] =
  218. {
  219. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  220. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  221. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  222. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  223. };
  224. typedef std::vector<std::string> UniformNameList;
  225. static bool isSampler(D3D_SHADER_VARIABLE_TYPE _svt)
  226. {
  227. switch (_svt)
  228. {
  229. case D3D_SVT_SAMPLER:
  230. case D3D_SVT_SAMPLER1D:
  231. case D3D_SVT_SAMPLER2D:
  232. case D3D_SVT_SAMPLER3D:
  233. case D3D_SVT_SAMPLERCUBE:
  234. return true;
  235. default:
  236. break;
  237. }
  238. return false;
  239. }
  240. bool getReflectionDataD3D9(ID3DBlob* _code, UniformArray& _uniforms)
  241. {
  242. // see reference for magic values: https://msdn.microsoft.com/en-us/library/ff552891(VS.85).aspx
  243. const uint32_t D3DSIO_COMMENT = 0x0000FFFE;
  244. const uint32_t D3DSIO_END = 0x0000FFFF;
  245. const uint32_t D3DSI_OPCODE_MASK = 0x0000FFFF;
  246. const uint32_t D3DSI_COMMENTSIZE_MASK = 0x7FFF0000;
  247. const uint32_t CTAB_CONSTANT = MAKEFOURCC('C', 'T', 'A', 'B');
  248. // parse the shader blob for the constant table
  249. const size_t codeSize = _code->GetBufferSize();
  250. const uint32_t* ptr = (const uint32_t*)_code->GetBufferPointer();
  251. const uint32_t* end = (const uint32_t*)( (const uint8_t*)ptr + codeSize);
  252. const CTHeader* header = NULL;
  253. ptr++; // first byte is shader type / version; skip it since we already know
  254. while (ptr < end && *ptr != D3DSIO_END)
  255. {
  256. uint32_t cur = *ptr++;
  257. if ( (cur & D3DSI_OPCODE_MASK) != D3DSIO_COMMENT)
  258. {
  259. continue;
  260. }
  261. // try to find CTAB comment block
  262. uint32_t commentSize = (cur & D3DSI_COMMENTSIZE_MASK) >> 16;
  263. uint32_t fourcc = *ptr;
  264. if (fourcc == CTAB_CONSTANT)
  265. {
  266. // found the constant table data
  267. header = (const CTHeader*)(ptr + 1);
  268. uint32_t tableSize = (commentSize - 1) * 4;
  269. if (tableSize < sizeof(CTHeader) || header->Size != sizeof(CTHeader) )
  270. {
  271. fprintf(stderr, "Error: Invalid constant table data\n");
  272. return false;
  273. }
  274. break;
  275. }
  276. // this is a different kind of comment section, so skip over it
  277. ptr += commentSize - 1;
  278. }
  279. if (!header)
  280. {
  281. fprintf(stderr, "Error: Could not find constant table data\n");
  282. return false;
  283. }
  284. const uint8_t* headerBytePtr = (const uint8_t*)header;
  285. const char* creator = (const char*)(headerBytePtr + header->Creator);
  286. BX_TRACE("Creator: %s 0x%08x", creator, header->Version);
  287. BX_TRACE("Num constants: %d", header->Constants);
  288. BX_TRACE("# cl ty RxC S By Name");
  289. const CTInfo* ctInfoArray = (const CTInfo*)(headerBytePtr + header->ConstantInfo);
  290. for (uint32_t ii = 0; ii < header->Constants; ++ii)
  291. {
  292. const CTInfo& ctInfo = ctInfoArray[ii];
  293. const CTType& ctType = *(const CTType*)(headerBytePtr + ctInfo.TypeInfo);
  294. const char* name = (const char*)(headerBytePtr + ctInfo.Name);
  295. BX_TRACE("%3d %2d %2d [%dx%d] %d %s[%d] c%d (%d)"
  296. , ii
  297. , ctType.Class
  298. , ctType.Type
  299. , ctType.Rows
  300. , ctType.Columns
  301. , ctType.StructMembers
  302. , name
  303. , ctType.Elements
  304. , ctInfo.RegisterIndex
  305. , ctInfo.RegisterCount
  306. );
  307. D3D11_SHADER_TYPE_DESC desc;
  308. desc.Class = (D3D_SHADER_VARIABLE_CLASS)ctType.Class;
  309. desc.Type = (D3D_SHADER_VARIABLE_TYPE)ctType.Type;
  310. desc.Rows = ctType.Rows;
  311. desc.Columns = ctType.Columns;
  312. UniformType::Enum type = findUniformType(desc);
  313. if (UniformType::Count != type)
  314. {
  315. Uniform un;
  316. un.name = '$' == name[0] ? name + 1 : name;
  317. un.type = isSampler(desc.Type)
  318. ? UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | type)
  319. : type
  320. ;
  321. un.num = (uint8_t)ctType.Elements;
  322. un.regIndex = ctInfo.RegisterIndex;
  323. un.regCount = ctInfo.RegisterCount;
  324. _uniforms.push_back(un);
  325. }
  326. }
  327. return true;
  328. }
  329. bool getReflectionDataD3D11(ID3DBlob* _code, bool _vshader, UniformArray& _uniforms, uint8_t& _numAttrs, uint16_t* _attrs, uint16_t& _size, UniformNameList& unusedUniforms)
  330. {
  331. ID3D11ShaderReflection* reflect = NULL;
  332. HRESULT hr = D3DReflect(_code->GetBufferPointer()
  333. , _code->GetBufferSize()
  334. , s_compiler->IID_ID3D11ShaderReflection
  335. , (void**)&reflect
  336. );
  337. if (FAILED(hr) )
  338. {
  339. fprintf(stderr, "Error: D3DReflect failed 0x%08x\n", (uint32_t)hr);
  340. return false;
  341. }
  342. D3D11_SHADER_DESC desc;
  343. hr = reflect->GetDesc(&desc);
  344. if (FAILED(hr) )
  345. {
  346. fprintf(stderr, "Error: ID3D11ShaderReflection::GetDesc failed 0x%08x\n", (uint32_t)hr);
  347. return false;
  348. }
  349. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  350. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  351. BX_TRACE("Input:");
  352. if (_vshader) // Only care about input semantic on vertex shaders
  353. {
  354. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  355. {
  356. D3D11_SIGNATURE_PARAMETER_DESC spd;
  357. reflect->GetInputParameterDesc(ii, &spd);
  358. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  359. , ii
  360. , spd.SemanticName
  361. , spd.SemanticIndex
  362. , spd.SystemValueType
  363. , spd.ComponentType
  364. , spd.Mask
  365. , spd.Register
  366. );
  367. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, uint8_t(spd.SemanticIndex) );
  368. if (ris.m_attr != bgfx::Attrib::Count)
  369. {
  370. _attrs[_numAttrs] = bgfx::attribToId(ris.m_attr);
  371. ++_numAttrs;
  372. }
  373. }
  374. }
  375. BX_TRACE("Output:");
  376. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  377. {
  378. D3D11_SIGNATURE_PARAMETER_DESC spd;
  379. reflect->GetOutputParameterDesc(ii, &spd);
  380. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  381. }
  382. for (uint32_t ii = 0, num = bx::uint32_min(1, desc.ConstantBuffers); ii < num; ++ii)
  383. {
  384. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  385. D3D11_SHADER_BUFFER_DESC bufferDesc;
  386. hr = cbuffer->GetDesc(&bufferDesc);
  387. _size = (uint16_t)bufferDesc.Size;
  388. if (SUCCEEDED(hr) )
  389. {
  390. BX_TRACE("%s, %d, vars %d, size %d"
  391. , bufferDesc.Name
  392. , bufferDesc.Type
  393. , bufferDesc.Variables
  394. , bufferDesc.Size
  395. );
  396. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  397. {
  398. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  399. ID3D11ShaderReflectionType* type = var->GetType();
  400. D3D11_SHADER_VARIABLE_DESC varDesc;
  401. hr = var->GetDesc(&varDesc);
  402. if (SUCCEEDED(hr) )
  403. {
  404. D3D11_SHADER_TYPE_DESC constDesc;
  405. hr = type->GetDesc(&constDesc);
  406. if (SUCCEEDED(hr) )
  407. {
  408. UniformType::Enum uniformType = findUniformType(constDesc);
  409. if (UniformType::Count != uniformType
  410. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  411. {
  412. Uniform un;
  413. un.name = varDesc.Name;
  414. un.type = uniformType;
  415. un.num = uint8_t(constDesc.Elements);
  416. un.regIndex = uint16_t(varDesc.StartOffset);
  417. un.regCount = BX_ALIGN_16(varDesc.Size) / 16;
  418. _uniforms.push_back(un);
  419. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d (used)"
  420. , varDesc.Name
  421. , varDesc.StartOffset
  422. , varDesc.Size
  423. , varDesc.uFlags
  424. , uniformType
  425. );
  426. }
  427. else
  428. {
  429. if (0 == (varDesc.uFlags & D3D_SVF_USED) )
  430. {
  431. unusedUniforms.push_back(varDesc.Name);
  432. }
  433. BX_TRACE("\t%s, unknown type", varDesc.Name);
  434. }
  435. }
  436. }
  437. }
  438. }
  439. }
  440. BX_TRACE("Bound:");
  441. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  442. {
  443. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  444. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  445. if (SUCCEEDED(hr) )
  446. {
  447. if (D3D_SIT_SAMPLER == bindDesc.Type)
  448. {
  449. BX_TRACE("\t%s, %d, %d, %d"
  450. , bindDesc.Name
  451. , bindDesc.Type
  452. , bindDesc.BindPoint
  453. , bindDesc.BindCount
  454. );
  455. const char * end = bx::strFind(bindDesc.Name, "Sampler");
  456. if (NULL != end)
  457. {
  458. Uniform un;
  459. un.name.assign(bindDesc.Name, (end - bindDesc.Name) );
  460. un.type = UniformType::Enum(BGFX_UNIFORM_SAMPLERBIT | UniformType::Int1);
  461. un.num = 1;
  462. un.regIndex = uint16_t(bindDesc.BindPoint);
  463. un.regCount = uint16_t(bindDesc.BindCount);
  464. _uniforms.push_back(un);
  465. }
  466. }
  467. }
  468. }
  469. if (NULL != reflect)
  470. {
  471. reflect->Release();
  472. }
  473. return true;
  474. }
  475. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  476. {
  477. const char* profile = _options.profile.c_str();
  478. if (profile[0] == '\0')
  479. {
  480. fprintf(stderr, "Error: Shader profile must be specified.\n");
  481. return false;
  482. }
  483. s_compiler = load();
  484. bool result = false;
  485. bool debug = _options.debugInformation;
  486. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  487. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  488. flags |= _options.avoidFlowControl ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  489. flags |= _options.noPreshader ? D3DCOMPILE_NO_PRESHADER : 0;
  490. flags |= _options.partialPrecision ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  491. flags |= _options.preferFlowControl ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  492. flags |= _options.backwardsCompatibility ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  493. bool werror = _options.warningsAreErrors;
  494. if (werror)
  495. {
  496. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  497. }
  498. if (_options.optimize )
  499. {
  500. uint32_t optimization = bx::uint32_min(_options.optimizationLevel, BX_COUNTOF(s_optimizationLevelD3D11) - 1);
  501. flags |= s_optimizationLevelD3D11[optimization];
  502. }
  503. else
  504. {
  505. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  506. }
  507. BX_TRACE("Profile: %s", profile);
  508. BX_TRACE("Flags: 0x%08x", flags);
  509. ID3DBlob* code;
  510. ID3DBlob* errorMsg;
  511. // Output preprocessed shader so that HLSL can be debugged via GPA
  512. // or PIX. Compiling through memory won't embed preprocessed shader
  513. // file path.
  514. std::string hlslfp;
  515. if (debug)
  516. {
  517. hlslfp = _options.outputFilePath + ".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 = bx::strLen("uniform");
  579. // first time through, we just find unused uniforms and get rid of them
  580. std::string output;
  581. bx::Error err;
  582. LineReader reader(_code.c_str() );
  583. while (err.isOk() )
  584. {
  585. char str[4096];
  586. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  587. if (err.isOk() )
  588. {
  589. std::string strLine(str, len);
  590. for (UniformNameList::iterator it = unusedUniforms.begin(), itEnd = unusedUniforms.end(); it != itEnd; ++it)
  591. {
  592. size_t index = strLine.find("uniform ");
  593. if (index == std::string::npos)
  594. {
  595. continue;
  596. }
  597. // matching lines like: uniform u_name;
  598. // we want to replace "uniform" with "static" so that it's no longer
  599. // included in the uniform blob that the application must upload
  600. // we can't just remove them, because unused functions might still reference
  601. // them and cause a compile error when they're gone
  602. if (!!bx::findIdentifierMatch(strLine.c_str(), it->c_str() ) )
  603. {
  604. strLine = strLine.replace(index, strLength, "static");
  605. unusedUniforms.erase(it);
  606. break;
  607. }
  608. }
  609. output += strLine;
  610. }
  611. }
  612. // recompile with the unused uniforms converted to statics
  613. return compile(_options, _version, output.c_str(), _writer, false);
  614. }
  615. }
  616. {
  617. uint16_t count = (uint16_t)uniforms.size();
  618. bx::write(_writer, count);
  619. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  620. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  621. {
  622. const Uniform& un = *it;
  623. uint8_t nameSize = (uint8_t)un.name.size();
  624. bx::write(_writer, nameSize);
  625. bx::write(_writer, un.name.c_str(), nameSize);
  626. uint8_t type = uint8_t(un.type | fragmentBit);
  627. bx::write(_writer, type);
  628. bx::write(_writer, un.num);
  629. bx::write(_writer, un.regIndex);
  630. bx::write(_writer, un.regCount);
  631. BX_TRACE("%s, %s, %d, %d, %d"
  632. , un.name.c_str()
  633. , getUniformTypeName(un.type)
  634. , un.num
  635. , un.regIndex
  636. , un.regCount
  637. );
  638. }
  639. }
  640. {
  641. ID3DBlob* stripped;
  642. hr = D3DStripShader(code->GetBufferPointer()
  643. , code->GetBufferSize()
  644. , D3DCOMPILER_STRIP_REFLECTION_DATA
  645. | D3DCOMPILER_STRIP_TEST_BLOBS
  646. , &stripped
  647. );
  648. if (SUCCEEDED(hr) )
  649. {
  650. code->Release();
  651. code = stripped;
  652. }
  653. }
  654. {
  655. uint32_t shaderSize = uint32_t(code->GetBufferSize() );
  656. bx::write(_writer, shaderSize);
  657. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  658. uint8_t nul = 0;
  659. bx::write(_writer, nul);
  660. }
  661. if (_version > 9)
  662. {
  663. bx::write(_writer, numAttrs);
  664. bx::write(_writer, attrs, numAttrs*sizeof(uint16_t) );
  665. bx::write(_writer, size);
  666. }
  667. if (_options.disasm )
  668. {
  669. ID3DBlob* disasm;
  670. D3DDisassemble(code->GetBufferPointer()
  671. , code->GetBufferSize()
  672. , 0
  673. , NULL
  674. , &disasm
  675. );
  676. if (NULL != disasm)
  677. {
  678. std::string disasmfp = _options.outputFilePath + ".disasm";
  679. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  680. disasm->Release();
  681. }
  682. }
  683. if (NULL != errorMsg)
  684. {
  685. errorMsg->Release();
  686. }
  687. result = true;
  688. error:
  689. code->Release();
  690. unload();
  691. return result;
  692. }
  693. } // namespace hlsl
  694. bool compileHLSLShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  695. {
  696. return hlsl::compile(_options, _version, _code, _writer, true);
  697. }
  698. } // namespace bgfx
  699. #else
  700. namespace bgfx
  701. {
  702. bool compileHLSLShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  703. {
  704. BX_UNUSED(_options, _version, _code, _writer);
  705. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  706. return false;
  707. }
  708. } // namespace bgfx
  709. #endif // SHADERC_CONFIG_HLSL