ShaderCompiler.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Context.h"
  24. #include "File.h"
  25. #include "FileSystem.h"
  26. #include "GraphicsDefs.h"
  27. #include "List.h"
  28. #include "Mutex.h"
  29. #include "ProcessUtils.h"
  30. #include "ShaderParser.h"
  31. #include "StringUtils.h"
  32. #include "Thread.h"
  33. #include "XMLFile.h"
  34. #include <cstdio>
  35. #include <cstring>
  36. #include <windows.h>
  37. #include <d3d9.h>
  38. #include <d3dx9shader.h>
  39. #include "DebugNew.h"
  40. struct Parameter
  41. {
  42. Parameter()
  43. {
  44. }
  45. Parameter(const String& name, unsigned reg, unsigned regCount) :
  46. name_(name),
  47. register_(reg),
  48. regCount_(regCount)
  49. {
  50. }
  51. bool operator < (const Parameter& rhs) const
  52. {
  53. if (register_ != rhs.register_)
  54. return register_ < rhs.register_;
  55. else if (name_ != rhs.name_)
  56. return name_ < rhs.name_;
  57. else
  58. return regCount_ < rhs.regCount_;
  59. }
  60. bool operator > (const Parameter& rhs) const
  61. {
  62. if (register_ != rhs.register_)
  63. return register_ > rhs.register_;
  64. else if (name_ != rhs.name_)
  65. return name_ > rhs.name_;
  66. else
  67. return regCount_ > rhs.regCount_;
  68. }
  69. bool operator == (const Parameter& rhs) const { return register_ == rhs.register_ && name_ == rhs.name_ && regCount_ == rhs.regCount_; }
  70. bool operator != (const Parameter& rhs) const { return register_ != rhs.register_ || name_ != rhs.name_ || regCount_ != rhs.regCount_; }
  71. String name_;
  72. unsigned register_;
  73. unsigned regCount_;
  74. };
  75. struct CompiledVariation
  76. {
  77. ShaderType type_;
  78. String name_;
  79. String outFileName_;
  80. Vector<String> defines_;
  81. Vector<String> defineValues_;
  82. PODVector<unsigned char> byteCode_;
  83. Vector<Parameter> constants_;
  84. Vector<Parameter> textureUnits_;
  85. String errorMsg_;
  86. };
  87. SharedPtr<Context> context_(new Context());
  88. SharedPtr<FileSystem> fileSystem_(new FileSystem(context_));
  89. String inDir_;
  90. String outDir_;
  91. Vector<String> defines_;
  92. Vector<String> defineValues_;
  93. String variationName_;
  94. volatile bool compileFailed_ = false;
  95. bool useSM3_ = false;
  96. bool compileVariation_ = false;
  97. bool compileVS_ = true;
  98. bool compilePS_ = true;
  99. List<CompiledVariation> variations_;
  100. List<CompiledVariation*> workList_;
  101. Mutex workMutex_;
  102. String hlslCode_;
  103. int main(int argc, char** argv);
  104. void Run(const Vector<String>& arguments);
  105. void CompileShader(const String& fileName);
  106. void CompileVariation(CompiledVariation* variation);
  107. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize);
  108. class WorkerThread : public RefCounted, public Thread
  109. {
  110. public:
  111. void ThreadFunction()
  112. {
  113. for (;;)
  114. {
  115. CompiledVariation* workItem = 0;
  116. {
  117. MutexLock lock(workMutex_);
  118. if (!workList_.Empty())
  119. {
  120. workItem = workList_.Front();
  121. workList_.Erase(workList_.Begin());
  122. }
  123. }
  124. if (!workItem)
  125. return;
  126. // If compile(s) failed, just empty the list, but do not compile more
  127. if (!compileFailed_)
  128. CompileVariation(workItem);
  129. }
  130. }
  131. };
  132. class IncludeHandler : public ID3DXInclude
  133. {
  134. public:
  135. STDMETHOD(Open)(D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes)
  136. {
  137. String fileName = inDir_ + String((const char*)pFileName);
  138. File file(context_, fileName);
  139. if (!file.IsOpen())
  140. return E_FAIL;
  141. unsigned fileSize = file.GetSize();
  142. void* fileData = new unsigned char[fileSize];
  143. *pBytes = fileSize;
  144. *ppData = fileData;
  145. file.Read(fileData, fileSize);
  146. return S_OK;
  147. }
  148. STDMETHOD(Close)(LPCVOID pData)
  149. {
  150. delete[] (unsigned char*)pData;
  151. return S_OK;
  152. }
  153. };
  154. int main(int argc, char** argv)
  155. {
  156. Vector<String> arguments;
  157. #ifdef WIN32
  158. arguments = ParseArguments(GetCommandLineW());
  159. #else
  160. arguments = ParseArguments(argc, argv);
  161. #endif
  162. Run(arguments);
  163. return 0;
  164. }
  165. void Run(const Vector<String>& arguments)
  166. {
  167. if (arguments.Size() < 1)
  168. {
  169. ErrorExit(
  170. "ShaderCompiler <definitionfile> <outputpath> [options]\n\n"
  171. "Options:\n"
  172. "-tVS|PS Compile only vertex or pixel shaders, by default compile both\n"
  173. "-vX Compile only the shader variation X\n"
  174. "-dX Add a define. Add SM3 to compile for Shader Model 3\n\n"
  175. "Shader binaries will be output into the same directory as the definition file.\n"
  176. "Specify a wildcard to compile multiple shaders from the directory.\n"
  177. );
  178. }
  179. String path, file, extension;
  180. SplitPath(arguments[0], path, file, extension);
  181. inDir_ = AddTrailingSlash(path);
  182. outDir_ = AddTrailingSlash(arguments[1]);
  183. for (unsigned i = 1; i < arguments.Size(); ++i)
  184. {
  185. if (arguments[i][0] == '-' && arguments[i].Length() > 1)
  186. {
  187. char option = arguments[i][1];
  188. String arg = arguments[i].Substring(2);
  189. switch (option)
  190. {
  191. case 'd':
  192. {
  193. Vector<String> nameAndValue = arg.Split('=');
  194. if (nameAndValue.Size() == 2)
  195. {
  196. defines_.Push(nameAndValue[0]);
  197. defineValues_.Push(nameAndValue[1]);
  198. if (nameAndValue[0] == "SM3" && ToInt(nameAndValue[1]) > 0)
  199. useSM3_ = true;
  200. }
  201. else
  202. {
  203. defines_.Push(arg);
  204. defineValues_.Push("1");
  205. if (arg == "SM3")
  206. useSM3_ = true;
  207. }
  208. }
  209. break;
  210. case 't':
  211. if (arg.ToLower() == "vs")
  212. {
  213. compileVS_ = true;
  214. compilePS_ = false;
  215. }
  216. else if (arg.ToLower() == "ps")
  217. {
  218. compileVS_ = false;
  219. compilePS_ = true;
  220. }
  221. break;
  222. case 'v':
  223. compileVariation_ = true;
  224. variationName_ = arg;
  225. break;
  226. }
  227. }
  228. }
  229. if (!file.StartsWith("*"))
  230. CompileShader(arguments[0]);
  231. else
  232. {
  233. Vector<String> shaderFiles;
  234. fileSystem_->ScanDir(shaderFiles, inDir_, file + extension, SCAN_FILES, false);
  235. for (unsigned i = 0; i < shaderFiles.Size(); ++i)
  236. CompileShader(inDir_ + shaderFiles[i]);
  237. }
  238. }
  239. void CompileShader(const String& fileName)
  240. {
  241. String file = GetFileName(fileName);
  242. XMLFile doc(context_);
  243. File source(context_);
  244. source.Open(fileName);
  245. if (!doc.Load(source))
  246. ErrorExit("Could not open input file " + fileName);
  247. XMLElement shaders = doc.GetRoot("shaders");
  248. if (!shaders)
  249. ErrorExit("No shaders element in " + source.GetName());
  250. if (compileVS_)
  251. {
  252. ShaderParser vsParser;
  253. if (!vsParser.Parse(VS, shaders, defines_, defineValues_))
  254. ErrorExit("VS: " + vsParser.GetErrorMessage());
  255. const HashMap<String, unsigned>& combinations = vsParser.GetAllCombinations();
  256. for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
  257. {
  258. if (!compileVariation_ || i->first_ == variationName_)
  259. {
  260. ShaderCombination src;
  261. CompiledVariation compile;
  262. vsParser.GetCombination(src, i->first_);
  263. compile.type_ = VS;
  264. compile.name_ = file;
  265. compile.outFileName_ = outDir_ + file;
  266. if (!src.name_.Empty())
  267. {
  268. compile.name_ += "_" + src.name_;
  269. compile.outFileName_ += "_" + src.name_;
  270. }
  271. compile.outFileName_ += useSM3_ ? ".vs3" : ".vs2";
  272. compile.defines_ = src.defines_;
  273. compile.defineValues_ = src.defineValues_;
  274. variations_.Push(compile);
  275. workList_.Push(&variations_.Back());
  276. }
  277. }
  278. }
  279. if (compilePS_)
  280. {
  281. ShaderParser psParser;
  282. if (!psParser.Parse(PS, shaders, defines_, defineValues_))
  283. ErrorExit("PS: " + psParser.GetErrorMessage());
  284. const HashMap<String, unsigned>& combinations = psParser.GetAllCombinations();
  285. for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
  286. {
  287. if (!compileVariation_ || i->first_ == variationName_)
  288. {
  289. ShaderCombination src;
  290. CompiledVariation compile;
  291. psParser.GetCombination(src, i->first_);
  292. compile.type_ = PS;
  293. compile.name_ = file;
  294. compile.outFileName_ = outDir_ + file;
  295. if (!src.name_.Empty())
  296. {
  297. compile.name_ += "_" + src.name_;
  298. compile.outFileName_ += "_" + src.name_;
  299. }
  300. compile.outFileName_ += useSM3_ ? ".ps3" : ".ps2";
  301. compile.defines_ = src.defines_;
  302. compile.defineValues_ = src.defineValues_;
  303. variations_.Push(compile);
  304. workList_.Push(&variations_.Back());
  305. }
  306. }
  307. }
  308. if (variations_.Empty())
  309. {
  310. PrintLine("No variations to compile");
  311. return;
  312. }
  313. // Load the shader source code
  314. {
  315. String inputFileName = inDir_ + file + ".hlsl";
  316. File hlslFile(context_, inputFileName);
  317. if (!hlslFile.IsOpen())
  318. ErrorExit("Could not open input file " + inputFileName);
  319. hlslCode_.Clear();
  320. while (!hlslFile.IsEof())
  321. hlslCode_ += hlslFile.ReadLine() + "\n";
  322. }
  323. if (!compileVariation_)
  324. {
  325. // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely
  326. unsigned numWorkerThreads = GetNumLogicalCPUs() - 1;
  327. if (!numWorkerThreads)
  328. numWorkerThreads = 1;
  329. Vector<SharedPtr<WorkerThread> > workerThreads;
  330. workerThreads.Resize(numWorkerThreads);
  331. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  332. {
  333. workerThreads[i] = new WorkerThread();
  334. workerThreads[i]->Start();
  335. }
  336. // This will wait until the thread functions have stopped
  337. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  338. workerThreads[i]->Stop();
  339. }
  340. else
  341. {
  342. WorkerThread dummyThread;
  343. dummyThread.ThreadFunction();
  344. }
  345. // Check that all shaders compiled
  346. for (List<CompiledVariation>::Iterator i = variations_.Begin(); i != variations_.End(); ++i)
  347. {
  348. if (!i->errorMsg_.Empty())
  349. {
  350. if (i->type_ == VS)
  351. ErrorExit("Failed to compile vertex shader " + i->name_ + ": " + i->errorMsg_);
  352. else
  353. ErrorExit("Failed to compile pixel shader " + i->name_ + ": " + i->errorMsg_);
  354. }
  355. }
  356. }
  357. void CompileVariation(CompiledVariation* variation)
  358. {
  359. IncludeHandler includeHandler;
  360. PODVector<D3DXMACRO> macros;
  361. // Insert variation-specific and global defines
  362. for (unsigned i = 0; i < variation->defines_.Size(); ++i)
  363. {
  364. D3DXMACRO macro;
  365. macro.Name = variation->defines_[i].CString();
  366. macro.Definition = variation->defineValues_[i].CString();
  367. macros.Push(macro);
  368. }
  369. for (unsigned i = 0; i < defines_.Size(); ++i)
  370. {
  371. D3DXMACRO macro;
  372. macro.Name = defines_[i].CString();
  373. macro.Definition = defineValues_[i].CString();
  374. macros.Push(macro);
  375. }
  376. D3DXMACRO endMacro;
  377. endMacro.Name = 0;
  378. endMacro.Definition = 0;
  379. macros.Push(endMacro);
  380. LPD3DXBUFFER shaderCode = 0;
  381. LPD3DXBUFFER errorMsgs = 0;
  382. LPD3DXCONSTANTTABLE constantTable = 0;
  383. // Set the profile, entrypoint and flags according to the shader being compiled
  384. String profile;
  385. String entryPoint;
  386. unsigned flags = D3DXSHADER_OPTIMIZATION_LEVEL3;
  387. if (variation->type_ == VS)
  388. {
  389. entryPoint = "VS";
  390. if (!useSM3_)
  391. profile = "vs_2_0";
  392. else
  393. profile = "vs_3_0";
  394. }
  395. else
  396. {
  397. entryPoint = "PS";
  398. if (!useSM3_)
  399. profile = "ps_2_0";
  400. else
  401. {
  402. profile = "ps_3_0";
  403. flags |= D3DXSHADER_PREFER_FLOW_CONTROL;
  404. }
  405. }
  406. // Compile using D3DX
  407. HRESULT hr = D3DXCompileShader(hlslCode_.CString(), hlslCode_.Length(), &macros.Front(), &includeHandler,
  408. entryPoint.CString(), profile.CString(), flags, &shaderCode, &errorMsgs, &constantTable);
  409. if (FAILED(hr))
  410. {
  411. variation->errorMsg_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  412. compileFailed_ = true;
  413. }
  414. else
  415. {
  416. CopyStrippedCode(variation->byteCode_, shaderCode->GetBufferPointer(), shaderCode->GetBufferSize());
  417. if (!variation->name_.Empty())
  418. PrintLine("Compiled shader variation " + variation->name_ + ", code size " + String(variation->byteCode_.Size()));
  419. else
  420. PrintLine("Compiled base shader variation, code size " + String(variation->byteCode_.Size()));
  421. // Print warnings if any
  422. if (errorMsgs && errorMsgs->GetBufferSize())
  423. {
  424. String warning((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  425. PrintLine("WARNING: " + warning);
  426. }
  427. // Parse the constant table for constants and texture units
  428. D3DXCONSTANTTABLE_DESC desc;
  429. constantTable->GetDesc(&desc);
  430. for (unsigned i = 0; i < desc.Constants; ++i)
  431. {
  432. D3DXHANDLE handle = constantTable->GetConstant(NULL, i);
  433. D3DXCONSTANT_DESC constantDesc;
  434. unsigned numElements = 1;
  435. constantTable->GetConstantDesc(handle, &constantDesc, &numElements);
  436. String name(constantDesc.Name);
  437. unsigned reg = constantDesc.RegisterIndex;
  438. unsigned regCount = constantDesc.RegisterCount;
  439. // Check if the parameter is a constant or a texture sampler
  440. bool isSampler = (name[0] == 's');
  441. name = name.Substring(1);
  442. if (isSampler)
  443. {
  444. // Skip if it's a G-buffer sampler
  445. if (name.Find("Buffer") == String::NPOS)
  446. {
  447. Parameter newTextureUnit(name, reg, 1);
  448. variation->textureUnits_.Push(newTextureUnit);
  449. }
  450. }
  451. else
  452. {
  453. Parameter newParam(name, reg, regCount);
  454. variation->constants_.Push(newParam);
  455. }
  456. }
  457. File outFile(context_);
  458. if (!outFile.Open(variation->outFileName_, FILE_WRITE))
  459. {
  460. variation->errorMsg_ = "Could not open output file " + variation->outFileName_;
  461. compileFailed_ = true;
  462. }
  463. else
  464. {
  465. outFile.WriteFileID("USHD");
  466. outFile.WriteShort((unsigned short)variation->type_);
  467. outFile.WriteShort(useSM3_ ? 3 : 2);
  468. outFile.WriteUInt(variation->constants_.Size());
  469. for (unsigned i = 0; i < variation->constants_.Size(); ++i)
  470. {
  471. outFile.WriteString(variation->constants_[i].name_);
  472. outFile.WriteUByte(variation->constants_[i].register_);
  473. outFile.WriteUByte(variation->constants_[i].regCount_);
  474. }
  475. outFile.WriteUInt(variation->textureUnits_.Size());
  476. for (unsigned i = 0; i < variation->textureUnits_.Size(); ++i)
  477. {
  478. outFile.WriteString(variation->textureUnits_[i].name_);
  479. outFile.WriteUByte(variation->textureUnits_[i].register_);
  480. }
  481. unsigned dataSize = variation->byteCode_.Size();
  482. outFile.WriteUInt(dataSize);
  483. if (dataSize)
  484. outFile.Write(&variation->byteCode_[0], dataSize);
  485. }
  486. }
  487. if (shaderCode)
  488. shaderCode->Release();
  489. if (constantTable)
  490. constantTable->Release();
  491. if (errorMsgs)
  492. errorMsgs->Release();
  493. }
  494. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize)
  495. {
  496. unsigned* srcWords = (unsigned*)src;
  497. unsigned srcWordSize = srcSize >> 2;
  498. dest.Clear();
  499. for (unsigned i = 0; i < srcWordSize; ++i)
  500. {
  501. unsigned opcode = srcWords[i] & 0xffff;
  502. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  503. unsigned commentLength = srcWords[i] >> 16;
  504. // For now, skip comment only at fixed position to prevent false positives
  505. if (i == 1 && opcode == D3DSIO_COMMENT)
  506. {
  507. // Skip the comment
  508. i += commentLength;
  509. }
  510. else
  511. {
  512. // Not a comment, copy the data
  513. unsigned char* srcBytes = (unsigned char*)(srcWords + i);
  514. dest.Push(*srcBytes++);
  515. dest.Push(*srcBytes++);
  516. dest.Push(*srcBytes++);
  517. dest.Push(*srcBytes++);
  518. }
  519. }
  520. }