ShaderCompiler.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Context.h"
  23. #include "File.h"
  24. #include "FileSystem.h"
  25. #include "GraphicsDefs.h"
  26. #include "List.h"
  27. #include "Mutex.h"
  28. #include "ProcessUtils.h"
  29. #include "ShaderParser.h"
  30. #include "StringUtils.h"
  31. #include "Thread.h"
  32. #include "XMLFile.h"
  33. #include <cstdio>
  34. #include <cstring>
  35. #include <windows.h>
  36. #include <d3dcompiler.h>
  37. #include <mojoshader.h>
  38. #include "DebugNew.h"
  39. using namespace Urho3D;
  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 ID3DInclude
  133. {
  134. public:
  135. STDMETHOD(Open)(D3D_INCLUDE_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. "Usage: 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 = vsParser.GetCombination(i->first_);
  261. CompiledVariation compile;
  262. compile.type_ = VS;
  263. compile.name_ = file;
  264. compile.outFileName_ = outDir_ + file;
  265. if (!src.name_.Empty())
  266. {
  267. compile.name_ += "_" + src.name_;
  268. compile.outFileName_ += "_" + src.name_;
  269. }
  270. compile.outFileName_ += useSM3_ ? ".vs3" : ".vs2";
  271. compile.defines_ = src.defines_;
  272. compile.defineValues_ = src.defineValues_;
  273. variations_.Push(compile);
  274. workList_.Push(&variations_.Back());
  275. }
  276. }
  277. }
  278. if (compilePS_)
  279. {
  280. ShaderParser psParser;
  281. if (!psParser.Parse(PS, shaders, defines_, defineValues_))
  282. ErrorExit("PS: " + psParser.GetErrorMessage());
  283. const HashMap<String, unsigned>& combinations = psParser.GetAllCombinations();
  284. for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
  285. {
  286. if (!compileVariation_ || i->first_ == variationName_)
  287. {
  288. ShaderCombination src = psParser.GetCombination(i->first_);
  289. CompiledVariation compile;
  290. compile.type_ = PS;
  291. compile.name_ = file;
  292. compile.outFileName_ = outDir_ + file;
  293. if (!src.name_.Empty())
  294. {
  295. compile.name_ += "_" + src.name_;
  296. compile.outFileName_ += "_" + src.name_;
  297. }
  298. compile.outFileName_ += useSM3_ ? ".ps3" : ".ps2";
  299. compile.defines_ = src.defines_;
  300. compile.defineValues_ = src.defineValues_;
  301. variations_.Push(compile);
  302. workList_.Push(&variations_.Back());
  303. }
  304. }
  305. }
  306. if (variations_.Empty())
  307. {
  308. PrintLine("No variations to compile");
  309. return;
  310. }
  311. // Load the shader source code
  312. {
  313. String inputFileName = inDir_ + file + ".hlsl";
  314. File hlslFile(context_, inputFileName);
  315. if (!hlslFile.IsOpen())
  316. ErrorExit("Could not open input file " + inputFileName);
  317. hlslCode_.Clear();
  318. while (!hlslFile.IsEof())
  319. hlslCode_ += hlslFile.ReadLine() + "\n";
  320. }
  321. if (!compileVariation_)
  322. {
  323. // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely
  324. unsigned numWorkerThreads = GetNumLogicalCPUs() - 1;
  325. if (!numWorkerThreads)
  326. numWorkerThreads = 1;
  327. Vector<SharedPtr<WorkerThread> > workerThreads;
  328. workerThreads.Resize(numWorkerThreads);
  329. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  330. {
  331. workerThreads[i] = new WorkerThread();
  332. workerThreads[i]->Start();
  333. }
  334. // This will wait until the thread functions have stopped
  335. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  336. workerThreads[i]->Stop();
  337. }
  338. else
  339. {
  340. WorkerThread dummyThread;
  341. dummyThread.ThreadFunction();
  342. }
  343. // Check that all shaders compiled
  344. for (List<CompiledVariation>::Iterator i = variations_.Begin(); i != variations_.End(); ++i)
  345. {
  346. if (!i->errorMsg_.Empty())
  347. {
  348. if (i->type_ == VS)
  349. ErrorExit("Failed to compile vertex shader " + i->name_ + ": " + i->errorMsg_);
  350. else
  351. ErrorExit("Failed to compile pixel shader " + i->name_ + ": " + i->errorMsg_);
  352. }
  353. }
  354. }
  355. void CompileVariation(CompiledVariation* variation)
  356. {
  357. IncludeHandler includeHandler;
  358. PODVector<D3D_SHADER_MACRO> macros;
  359. // Insert variation-specific and global defines
  360. for (unsigned i = 0; i < variation->defines_.Size(); ++i)
  361. {
  362. D3D_SHADER_MACRO macro;
  363. macro.Name = variation->defines_[i].CString();
  364. macro.Definition = variation->defineValues_[i].CString();
  365. macros.Push(macro);
  366. }
  367. for (unsigned i = 0; i < defines_.Size(); ++i)
  368. {
  369. D3D_SHADER_MACRO macro;
  370. macro.Name = defines_[i].CString();
  371. macro.Definition = defineValues_[i].CString();
  372. macros.Push(macro);
  373. }
  374. D3D_SHADER_MACRO endMacro;
  375. endMacro.Name = 0;
  376. endMacro.Definition = 0;
  377. macros.Push(endMacro);
  378. LPD3DBLOB shaderCode = NULL;
  379. LPD3DBLOB errorMsgs = NULL;
  380. // Set the profile, entrypoint and flags according to the shader being compiled
  381. String profile;
  382. String entryPoint;
  383. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  384. if (variation->type_ == VS)
  385. {
  386. entryPoint = "VS";
  387. if (!useSM3_)
  388. profile = "vs_2_0";
  389. else
  390. profile = "vs_3_0";
  391. }
  392. else
  393. {
  394. entryPoint = "PS";
  395. if (!useSM3_)
  396. profile = "ps_2_0";
  397. else
  398. {
  399. profile = "ps_3_0";
  400. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  401. }
  402. }
  403. // Compile using D3DCompiler
  404. HRESULT hr = D3DCompile(hlslCode_.CString(), hlslCode_.Length(), NULL, &macros.Front(), &includeHandler,
  405. entryPoint.CString(), profile.CString(), flags, 0, &shaderCode, &errorMsgs);
  406. if (FAILED(hr))
  407. {
  408. variation->errorMsg_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  409. compileFailed_ = true;
  410. }
  411. else
  412. {
  413. BYTE const *const bufData = static_cast<BYTE *>(shaderCode->GetBufferPointer());
  414. SIZE_T const bufSize = shaderCode->GetBufferSize();
  415. MOJOSHADER_parseData const *parseData = MOJOSHADER_parse("bytecode", bufData, bufSize, NULL, 0, NULL, 0, NULL, NULL, NULL);
  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. for(int i = 0; i < parseData->symbol_count; i++)
  428. {
  429. MOJOSHADER_symbol const& symbol = parseData->symbols[i];
  430. String name(symbol.name);
  431. unsigned const reg = symbol.register_index;
  432. unsigned const regCount = symbol.register_count;
  433. // Check if the parameter is a constant or a texture sampler
  434. bool const isSampler = (name[0] == 's');
  435. name = name.Substring(1);
  436. if (isSampler)
  437. {
  438. // Skip if it's a G-buffer sampler
  439. if (!name.Contains("Buffer"))
  440. {
  441. Parameter newTextureUnit(name, reg, 1);
  442. variation->textureUnits_.Push(newTextureUnit);
  443. }
  444. }
  445. else
  446. {
  447. Parameter newParam(name, reg, regCount);
  448. variation->constants_.Push(newParam);
  449. }
  450. }
  451. MOJOSHADER_freeParseData(parseData);
  452. File outFile(context_);
  453. if (!outFile.Open(variation->outFileName_, FILE_WRITE))
  454. {
  455. variation->errorMsg_ = "Could not open output file " + variation->outFileName_;
  456. compileFailed_ = true;
  457. }
  458. else
  459. {
  460. outFile.WriteFileID("USHD");
  461. outFile.WriteShort((unsigned short)variation->type_);
  462. outFile.WriteShort(useSM3_ ? 3 : 2);
  463. outFile.WriteUInt(variation->constants_.Size());
  464. for (unsigned i = 0; i < variation->constants_.Size(); ++i)
  465. {
  466. outFile.WriteString(variation->constants_[i].name_);
  467. outFile.WriteUByte(variation->constants_[i].register_);
  468. outFile.WriteUByte(variation->constants_[i].regCount_);
  469. }
  470. outFile.WriteUInt(variation->textureUnits_.Size());
  471. for (unsigned i = 0; i < variation->textureUnits_.Size(); ++i)
  472. {
  473. outFile.WriteString(variation->textureUnits_[i].name_);
  474. outFile.WriteUByte(variation->textureUnits_[i].register_);
  475. }
  476. unsigned dataSize = variation->byteCode_.Size();
  477. outFile.WriteUInt(dataSize);
  478. if (dataSize)
  479. outFile.Write(&variation->byteCode_[0], dataSize);
  480. }
  481. }
  482. if (shaderCode)
  483. shaderCode->Release();
  484. if (errorMsgs)
  485. errorMsgs->Release();
  486. }
  487. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize)
  488. {
  489. unsigned const D3DSIO_COMMENT = 0xFFFE;
  490. unsigned* srcWords = (unsigned*)src;
  491. unsigned srcWordSize = srcSize >> 2;
  492. dest.Clear();
  493. for (unsigned i = 0; i < srcWordSize; ++i)
  494. {
  495. unsigned opcode = srcWords[i] & 0xffff;
  496. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  497. unsigned commentLength = srcWords[i] >> 16;
  498. // For now, skip comment only at fixed position to prevent false positives
  499. if (i == 1 && opcode == D3DSIO_COMMENT)
  500. {
  501. // Skip the comment
  502. i += commentLength;
  503. }
  504. else
  505. {
  506. // Not a comment, copy the data
  507. unsigned char* srcBytes = (unsigned char*)(srcWords + i);
  508. dest.Push(*srcBytes++);
  509. dest.Push(*srcBytes++);
  510. dest.Push(*srcBytes++);
  511. dest.Push(*srcBytes++);
  512. }
  513. }
  514. }