ShaderCompiler.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. "-t <VS|PS> Compile only vertex or pixel shaders, by default compile both\n"
  173. "-v <name> Compile only the shader variation with name\n"
  174. "-d <define> Add a define. Add SM3 to compile for Shader Model 3\n\n"
  175. "If output path is not specified, shader binaries will be output into the same\n"
  176. "directory as the definition file. Specify a wildcard to compile multiple\n"
  177. "shaders."
  178. );
  179. }
  180. String path, file, extension;
  181. SplitPath(arguments[0], path, file, extension);
  182. inDir_ = AddTrailingSlash(path);
  183. if (arguments.Size() > 1 && arguments[1][0] != '-')
  184. outDir_ = AddTrailingSlash(arguments[1]);
  185. else
  186. outDir_ = inDir_;
  187. for (unsigned i = 1; i < arguments.Size(); ++i)
  188. {
  189. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  190. {
  191. String argument = arguments[i].Substring(1).ToLower();
  192. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  193. if (argument == "d" && !value.Empty())
  194. {
  195. Vector<String> nameAndValue = value.Split('=');
  196. if (nameAndValue.Size() == 2)
  197. {
  198. defines_.Push(nameAndValue[0]);
  199. defineValues_.Push(nameAndValue[1]);
  200. if (nameAndValue[0] == "SM3" && ToInt(nameAndValue[1]) > 0)
  201. useSM3_ = true;
  202. }
  203. else
  204. {
  205. defines_.Push(value);
  206. defineValues_.Push("1");
  207. if (value == "SM3")
  208. useSM3_ = true;
  209. }
  210. ++i;
  211. }
  212. else if (argument == "t" && !value.Empty())
  213. {
  214. if (value.ToLower() == "vs")
  215. {
  216. compileVS_ = true;
  217. compilePS_ = false;
  218. }
  219. else if (value.ToLower() == "ps")
  220. {
  221. compileVS_ = false;
  222. compilePS_ = true;
  223. }
  224. ++i;
  225. }
  226. // Note: variation name must be allowed to be empty
  227. else if (argument == "v")
  228. {
  229. compileVariation_ = true;
  230. variationName_ = value;
  231. ++i;
  232. }
  233. }
  234. }
  235. if (!file.StartsWith("*"))
  236. CompileShader(arguments[0]);
  237. else
  238. {
  239. Vector<String> shaderFiles;
  240. fileSystem_->ScanDir(shaderFiles, inDir_, file + extension, SCAN_FILES, false);
  241. for (unsigned i = 0; i < shaderFiles.Size(); ++i)
  242. CompileShader(inDir_ + shaderFiles[i]);
  243. }
  244. }
  245. void CompileShader(const String& fileName)
  246. {
  247. String file = GetFileName(fileName);
  248. XMLFile doc(context_);
  249. File source(context_);
  250. source.Open(fileName);
  251. if (!doc.Load(source))
  252. ErrorExit("Could not open input file " + fileName);
  253. XMLElement shaders = doc.GetRoot("shaders");
  254. if (!shaders)
  255. ErrorExit("No shaders element in " + source.GetName());
  256. if (compileVS_)
  257. {
  258. ShaderParser vsParser;
  259. if (!vsParser.Parse(VS, shaders, !compileVariation_, defines_, defineValues_))
  260. ErrorExit("VS: " + vsParser.GetErrorMessage());
  261. // If compiling a specific variation only, request it beforehand
  262. if (compileVariation_)
  263. vsParser.GetCombination(variationName_);
  264. const HashMap<String, unsigned>& combinations = vsParser.GetAllCombinations();
  265. for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
  266. {
  267. if (!compileVariation_ || i->first_ == variationName_)
  268. {
  269. ShaderCombination src = vsParser.GetCombination(i->first_);
  270. CompiledVariation compile;
  271. compile.type_ = VS;
  272. compile.name_ = file;
  273. compile.outFileName_ = outDir_ + file;
  274. if (!src.name_.Empty())
  275. {
  276. compile.name_ += "_" + src.name_;
  277. compile.outFileName_ += "_" + src.name_;
  278. }
  279. compile.outFileName_ += useSM3_ ? ".vs3" : ".vs2";
  280. compile.defines_ = src.defines_;
  281. compile.defineValues_ = src.defineValues_;
  282. variations_.Push(compile);
  283. workList_.Push(&variations_.Back());
  284. }
  285. }
  286. }
  287. if (compilePS_)
  288. {
  289. ShaderParser psParser;
  290. if (!psParser.Parse(PS, shaders, !compileVariation_, defines_, defineValues_))
  291. ErrorExit("PS: " + psParser.GetErrorMessage());
  292. // If compiling a specific variation only, request it beforehand
  293. if (compileVariation_)
  294. psParser.GetCombination(variationName_);
  295. const HashMap<String, unsigned>& combinations = psParser.GetAllCombinations();
  296. for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
  297. {
  298. if (!compileVariation_ || i->first_ == variationName_)
  299. {
  300. ShaderCombination src = psParser.GetCombination(i->first_);
  301. CompiledVariation compile;
  302. compile.type_ = PS;
  303. compile.name_ = file;
  304. compile.outFileName_ = outDir_ + file;
  305. if (!src.name_.Empty())
  306. {
  307. compile.name_ += "_" + src.name_;
  308. compile.outFileName_ += "_" + src.name_;
  309. }
  310. compile.outFileName_ += useSM3_ ? ".ps3" : ".ps2";
  311. compile.defines_ = src.defines_;
  312. compile.defineValues_ = src.defineValues_;
  313. variations_.Push(compile);
  314. workList_.Push(&variations_.Back());
  315. }
  316. }
  317. }
  318. if (variations_.Empty())
  319. {
  320. PrintLine("No variations to compile");
  321. return;
  322. }
  323. // Load the shader source code
  324. {
  325. String inputFileName = inDir_ + file + ".hlsl";
  326. File hlslFile(context_, inputFileName);
  327. if (!hlslFile.IsOpen())
  328. ErrorExit("Could not open input file " + inputFileName);
  329. hlslCode_.Clear();
  330. while (!hlslFile.IsEof())
  331. hlslCode_ += hlslFile.ReadLine() + "\n";
  332. }
  333. if (!compileVariation_)
  334. {
  335. // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely
  336. unsigned numWorkerThreads = GetNumLogicalCPUs() - 1;
  337. if (!numWorkerThreads)
  338. numWorkerThreads = 1;
  339. Vector<SharedPtr<WorkerThread> > workerThreads;
  340. workerThreads.Resize(numWorkerThreads);
  341. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  342. {
  343. workerThreads[i] = new WorkerThread();
  344. workerThreads[i]->Run();
  345. }
  346. // This will wait until the thread functions have stopped
  347. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  348. workerThreads[i]->Stop();
  349. }
  350. else
  351. {
  352. WorkerThread dummyThread;
  353. dummyThread.ThreadFunction();
  354. }
  355. // Check that all shaders compiled
  356. for (List<CompiledVariation>::Iterator i = variations_.Begin(); i != variations_.End(); ++i)
  357. {
  358. if (!i->errorMsg_.Empty())
  359. {
  360. if (i->type_ == VS)
  361. ErrorExit("Failed to compile vertex shader " + i->name_ + ": " + i->errorMsg_);
  362. else
  363. ErrorExit("Failed to compile pixel shader " + i->name_ + ": " + i->errorMsg_);
  364. }
  365. }
  366. }
  367. void CompileVariation(CompiledVariation* variation)
  368. {
  369. IncludeHandler includeHandler;
  370. PODVector<D3D_SHADER_MACRO> macros;
  371. // Insert variation-specific and global defines
  372. for (unsigned i = 0; i < variation->defines_.Size(); ++i)
  373. {
  374. D3D_SHADER_MACRO macro;
  375. macro.Name = variation->defines_[i].CString();
  376. macro.Definition = variation->defineValues_[i].CString();
  377. macros.Push(macro);
  378. }
  379. for (unsigned i = 0; i < defines_.Size(); ++i)
  380. {
  381. D3D_SHADER_MACRO macro;
  382. macro.Name = defines_[i].CString();
  383. macro.Definition = defineValues_[i].CString();
  384. macros.Push(macro);
  385. }
  386. D3D_SHADER_MACRO endMacro;
  387. endMacro.Name = 0;
  388. endMacro.Definition = 0;
  389. macros.Push(endMacro);
  390. LPD3DBLOB shaderCode = NULL;
  391. LPD3DBLOB errorMsgs = NULL;
  392. // Set the profile, entrypoint and flags according to the shader being compiled
  393. String profile;
  394. String entryPoint;
  395. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  396. if (variation->type_ == VS)
  397. {
  398. entryPoint = "VS";
  399. if (!useSM3_)
  400. profile = "vs_2_0";
  401. else
  402. profile = "vs_3_0";
  403. }
  404. else
  405. {
  406. entryPoint = "PS";
  407. if (!useSM3_)
  408. profile = "ps_2_0";
  409. else
  410. {
  411. profile = "ps_3_0";
  412. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  413. }
  414. }
  415. // Compile using D3DCompiler
  416. HRESULT hr = D3DCompile(hlslCode_.CString(), hlslCode_.Length(), NULL, &macros.Front(), &includeHandler,
  417. entryPoint.CString(), profile.CString(), flags, 0, &shaderCode, &errorMsgs);
  418. if (FAILED(hr))
  419. {
  420. variation->errorMsg_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  421. compileFailed_ = true;
  422. }
  423. else
  424. {
  425. BYTE const *const bufData = static_cast<BYTE *>(shaderCode->GetBufferPointer());
  426. SIZE_T const bufSize = shaderCode->GetBufferSize();
  427. MOJOSHADER_parseData const *parseData = MOJOSHADER_parse("bytecode", bufData, bufSize, NULL, 0, NULL, 0, NULL, NULL, NULL);
  428. CopyStrippedCode(variation->byteCode_, shaderCode->GetBufferPointer(), shaderCode->GetBufferSize());
  429. if (!variation->name_.Empty())
  430. PrintLine("Compiled shader variation " + variation->name_ + ", code size " + String(variation->byteCode_.Size()));
  431. else
  432. PrintLine("Compiled base shader variation, code size " + String(variation->byteCode_.Size()));
  433. // Print warnings if any
  434. if (errorMsgs && errorMsgs->GetBufferSize())
  435. {
  436. String warning((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  437. PrintLine("WARNING: " + warning);
  438. }
  439. for(int i = 0; i < parseData->symbol_count; i++)
  440. {
  441. MOJOSHADER_symbol const& symbol = parseData->symbols[i];
  442. String name(symbol.name);
  443. unsigned const reg = symbol.register_index;
  444. unsigned const regCount = symbol.register_count;
  445. // Check if the parameter is a constant or a texture sampler
  446. bool const isSampler = (name[0] == 's');
  447. name = name.Substring(1);
  448. if (isSampler)
  449. {
  450. // Skip if it's a G-buffer sampler, which are aliases for the standard texture units
  451. if (name != "AlbedoBuffer" && name != "NormalBuffer" && name != "DepthBuffer" && name != "LightBuffer")
  452. {
  453. Parameter newTextureUnit(name, reg, 1);
  454. variation->textureUnits_.Push(newTextureUnit);
  455. }
  456. }
  457. else
  458. {
  459. Parameter newParam(name, reg, regCount);
  460. variation->constants_.Push(newParam);
  461. }
  462. }
  463. MOJOSHADER_freeParseData(parseData);
  464. // Create the last part of the output path (SM2/SM3) if it does not exist
  465. String outPath = GetPath(variation->outFileName_);
  466. if (!fileSystem_->DirExists(outPath))
  467. fileSystem_->CreateDir(outPath);
  468. File outFile(context_);
  469. if (!outFile.Open(variation->outFileName_, FILE_WRITE))
  470. {
  471. variation->errorMsg_ = "Could not open output file " + variation->outFileName_;
  472. compileFailed_ = true;
  473. }
  474. else
  475. {
  476. outFile.WriteFileID("USHD");
  477. outFile.WriteShort((unsigned short)variation->type_);
  478. outFile.WriteShort(useSM3_ ? 3 : 2);
  479. outFile.WriteUInt(variation->constants_.Size());
  480. for (unsigned i = 0; i < variation->constants_.Size(); ++i)
  481. {
  482. outFile.WriteString(variation->constants_[i].name_);
  483. outFile.WriteUByte(variation->constants_[i].register_);
  484. outFile.WriteUByte(variation->constants_[i].regCount_);
  485. }
  486. outFile.WriteUInt(variation->textureUnits_.Size());
  487. for (unsigned i = 0; i < variation->textureUnits_.Size(); ++i)
  488. {
  489. outFile.WriteString(variation->textureUnits_[i].name_);
  490. outFile.WriteUByte(variation->textureUnits_[i].register_);
  491. }
  492. unsigned dataSize = variation->byteCode_.Size();
  493. outFile.WriteUInt(dataSize);
  494. if (dataSize)
  495. outFile.Write(&variation->byteCode_[0], dataSize);
  496. }
  497. }
  498. if (shaderCode)
  499. shaderCode->Release();
  500. if (errorMsgs)
  501. errorMsgs->Release();
  502. }
  503. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize)
  504. {
  505. unsigned const D3DSIO_COMMENT = 0xFFFE;
  506. unsigned* srcWords = (unsigned*)src;
  507. unsigned srcWordSize = srcSize >> 2;
  508. dest.Clear();
  509. for (unsigned i = 0; i < srcWordSize; ++i)
  510. {
  511. unsigned opcode = srcWords[i] & 0xffff;
  512. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  513. unsigned commentLength = srcWords[i] >> 16;
  514. // For now, skip comment only at fixed position to prevent false positives
  515. if (i == 1 && opcode == D3DSIO_COMMENT)
  516. {
  517. // Skip the comment
  518. i += commentLength;
  519. }
  520. else
  521. {
  522. // Not a comment, copy the data
  523. unsigned char* srcBytes = (unsigned char*)(srcWords + i);
  524. dest.Push(*srcBytes++);
  525. dest.Push(*srcBytes++);
  526. dest.Push(*srcBytes++);
  527. dest.Push(*srcBytes++);
  528. }
  529. }
  530. }