ShaderCompiler.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "List.h"
  27. #include "Mutex.h"
  28. #include "ProcessUtils.h"
  29. #include "StringUtils.h"
  30. #include "Thread.h"
  31. #include "XMLFile.h"
  32. #include <cstdio>
  33. #include <cstring>
  34. #include <windows.h>
  35. #include <d3d9.h>
  36. #include <d3dx9shader.h>
  37. #include "DebugNew.h"
  38. enum ShaderType
  39. {
  40. VS = 0,
  41. PS,
  42. Both
  43. };
  44. struct Parameter
  45. {
  46. Parameter()
  47. {
  48. }
  49. Parameter(const String& name, unsigned reg, unsigned regCount) :
  50. name_(name),
  51. register_(reg),
  52. regCount_(regCount)
  53. {
  54. }
  55. bool operator < (const Parameter& rhs) const
  56. {
  57. if (register_ != rhs.register_)
  58. return register_ < rhs.register_;
  59. else if (name_ != rhs.name_)
  60. return name_ < rhs.name_;
  61. else
  62. return regCount_ < rhs.regCount_;
  63. }
  64. bool operator > (const Parameter& rhs) const
  65. {
  66. if (register_ != rhs.register_)
  67. return register_ > rhs.register_;
  68. else if (name_ != rhs.name_)
  69. return name_ > rhs.name_;
  70. else
  71. return regCount_ > rhs.regCount_;
  72. }
  73. bool operator == (const Parameter& rhs) const { return register_ == rhs.register_ && name_ == rhs.name_ && regCount_ == rhs.regCount_; }
  74. bool operator != (const Parameter& rhs) const { return register_ != rhs.register_ || name_ != rhs.name_ || regCount_ != rhs.regCount_; }
  75. String name_;
  76. unsigned register_;
  77. unsigned regCount_;
  78. };
  79. struct Variation
  80. {
  81. Variation()
  82. {
  83. }
  84. Variation(const String& name, bool isOption) :
  85. name_(name),
  86. option_(isOption)
  87. {
  88. }
  89. String name_;
  90. Vector<String> defines_;
  91. Vector<String> defineValues_;
  92. Vector<String> excludes_;
  93. Vector<String> includes_;
  94. Vector<String> requires_;
  95. bool option_;
  96. };
  97. struct CompiledVariation
  98. {
  99. ShaderType type_;
  100. String name_;
  101. Vector<String> defines_;
  102. Vector<String> defineValues_;
  103. PODVector<unsigned char> byteCode_;
  104. unsigned byteCodeOffset_;
  105. Set<Parameter> constants_;
  106. Set<Parameter> textureUnits_;
  107. String errorMsg_;
  108. };
  109. struct Shader
  110. {
  111. Shader(const String& name, ShaderType type) :
  112. name_(name),
  113. type_(type)
  114. {
  115. }
  116. String name_;
  117. ShaderType type_;
  118. Vector<Variation> variations_;
  119. };
  120. SharedPtr<Context> context_(new Context());
  121. SharedPtr<FileSystem> fileSystem_(new FileSystem(context_));
  122. String inDir_;
  123. String inFile_;
  124. String outDir_;
  125. Vector<String> defines_;
  126. Vector<String> defineValues_;
  127. bool useSM3_ = false;
  128. volatile bool compileFailed_ = false;
  129. List<CompiledVariation*> workList_;
  130. Mutex globalParamMutex_;
  131. Mutex workMutex_;
  132. String hlslCode_;
  133. Set<String> constants_;
  134. Set<String> textureUnits_;
  135. int main(int argc, char** argv);
  136. void Run(const Vector<String>& arguments);
  137. void CompileVariations(const Shader& baseShader, XMLElement& shaders);
  138. void Compile(CompiledVariation* variation);
  139. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize);
  140. class WorkerThread : public RefCounted, public Thread
  141. {
  142. public:
  143. void ThreadFunction()
  144. {
  145. for (;;)
  146. {
  147. CompiledVariation* workItem = 0;
  148. {
  149. MutexLock lock(workMutex_);
  150. if (!workList_.Empty())
  151. {
  152. workItem = workList_.Front();
  153. workList_.Erase(workList_.Begin());
  154. }
  155. }
  156. if (!workItem)
  157. return;
  158. // If compile(s) failed, just empty the list, but do not compile more
  159. if (!compileFailed_)
  160. Compile(workItem);
  161. }
  162. }
  163. };
  164. class IncludeHandler : public ID3DXInclude
  165. {
  166. public:
  167. STDMETHOD(Open)(D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes)
  168. {
  169. String fileName = inDir_ + String((const char*)pFileName);
  170. File file(context_, fileName);
  171. if (!file.IsOpen())
  172. return E_FAIL;
  173. unsigned fileSize = file.GetSize();
  174. void* fileData = new unsigned char[fileSize];
  175. *pBytes = fileSize;
  176. *ppData = fileData;
  177. file.Read(fileData, fileSize);
  178. return S_OK;
  179. }
  180. STDMETHOD(Close)(LPCVOID pData)
  181. {
  182. delete[] (unsigned char*)pData;
  183. return S_OK;
  184. }
  185. };
  186. int main(int argc, char** argv)
  187. {
  188. Vector<String> arguments;
  189. for (int i = 1; i < argc; ++i)
  190. {
  191. String argument(argv[i]);
  192. arguments.Push(GetInternalPath(argument));
  193. }
  194. Run(arguments);
  195. return 0;
  196. }
  197. void Run(const Vector<String>& arguments)
  198. {
  199. if (arguments.Size() < 2)
  200. {
  201. ErrorExit(
  202. "Usage: ShaderCompiler <definitionfile> <outputpath> [SM3] [define1] [define2]\n\n"
  203. "HLSL files will be loaded from definition file directory, and binary files will\n"
  204. "be output to the output path, preserving the subdirectory structure.\n"
  205. );
  206. }
  207. unsigned pos = arguments[0].FindLast('/');
  208. if (pos != String::NPOS)
  209. {
  210. inDir_ = arguments[0].Substring(0, pos);
  211. inFile_ = arguments[0].Substring(pos + 1);
  212. }
  213. else
  214. {
  215. inFile_ = arguments[0];
  216. }
  217. outDir_ = arguments[1];
  218. inDir_ = AddTrailingSlash(inDir_);
  219. outDir_ = AddTrailingSlash(outDir_);
  220. for (unsigned i = 2; i < arguments.Size(); ++i)
  221. {
  222. String arg = arguments[i].ToUpper();
  223. if (arg == "SM3")
  224. useSM3_ = true;
  225. else if (arg == "SM2")
  226. useSM3_ = false;
  227. Vector<String> nameAndValue = arg.Split('=');
  228. if (nameAndValue.Size() == 2)
  229. {
  230. defines_.Push(nameAndValue[0]);
  231. defineValues_.Push(nameAndValue[1]);
  232. }
  233. else
  234. {
  235. defines_.Push(arg);
  236. defineValues_.Push("1");
  237. }
  238. }
  239. XMLFile doc(context_);
  240. File source(context_);
  241. source.Open(arguments[0]);
  242. if (!doc.Load(source))
  243. ErrorExit("Could not open input file " + arguments[0]);
  244. XMLElement shaders = doc.GetRoot("shaders");
  245. if (!shaders)
  246. ErrorExit("No shaders element in " + source.GetName());
  247. XMLFile outDoc(context_);
  248. XMLElement outShaders = outDoc.CreateRoot("shaders");
  249. XMLElement shader = shaders.GetChild("shader");
  250. while (shader)
  251. {
  252. String source = shader.GetAttribute("name");
  253. ShaderType compileType = Both;
  254. String type = shader.GetAttribute("type");
  255. if (type == "VS" || type == "vs")
  256. compileType = VS;
  257. if (type == "PS" || type == "ps")
  258. compileType = PS;
  259. Shader baseShader(source, compileType);
  260. XMLElement variation = shader.GetChild();
  261. while (variation)
  262. {
  263. String value = variation.GetName();
  264. if (value == "variation" || value == "option")
  265. {
  266. String name = variation.GetAttribute("name");
  267. Variation newVar(name, value == "option");
  268. String simpleDefine = variation.GetAttribute("define");
  269. if (!simpleDefine.Empty())
  270. {
  271. Vector<String> nameAndValue = simpleDefine.Split('=');
  272. if (nameAndValue.Size() == 2)
  273. {
  274. newVar.defines_.Push(nameAndValue[0]);
  275. newVar.defineValues_.Push(nameAndValue[1]);
  276. }
  277. else
  278. {
  279. newVar.defines_.Push(simpleDefine);
  280. newVar.defineValues_.Push("1");
  281. }
  282. }
  283. String simpleExclude = variation.GetAttribute("exclude");
  284. if (!simpleExclude.Empty())
  285. newVar.excludes_.Push(simpleExclude);
  286. String simpleInclude = variation.GetAttribute("include");
  287. if (!simpleInclude.Empty())
  288. newVar.includes_.Push(simpleInclude);
  289. String simpleRequire = variation.GetAttribute("require");
  290. if (!simpleRequire.Empty())
  291. newVar.requires_.Push(simpleRequire);
  292. XMLElement define = variation.GetChild("define");
  293. while (define)
  294. {
  295. String defineName = define.GetAttribute("name");
  296. Vector<String> nameAndValue = defineName.Split('=');
  297. if (nameAndValue.Size() == 2)
  298. {
  299. newVar.defines_.Push(nameAndValue[0]);
  300. newVar.defineValues_.Push(nameAndValue[1]);
  301. }
  302. else
  303. {
  304. newVar.defines_.Push(defineName);
  305. newVar.defineValues_.Push("1");
  306. }
  307. define = define.GetNext("define");
  308. }
  309. XMLElement exclude = variation.GetChild("exclude");
  310. while (exclude)
  311. {
  312. newVar.excludes_.Push(exclude.GetAttribute("name"));
  313. exclude = exclude.GetNext("exclude");
  314. }
  315. XMLElement include = variation.GetChild("include");
  316. while (include)
  317. {
  318. newVar.includes_.Push(include.GetAttribute("name"));
  319. include = include.GetNext("include");
  320. }
  321. XMLElement require = variation.GetChild("require");
  322. while (require)
  323. {
  324. newVar.requires_.Push(require.GetAttribute("name"));
  325. require = require.GetNext("require");
  326. }
  327. baseShader.variations_.Push(newVar);
  328. }
  329. variation = variation.GetNext();
  330. }
  331. if (baseShader.type_ != Both)
  332. CompileVariations(baseShader, outShaders);
  333. else
  334. {
  335. baseShader.type_ = VS;
  336. CompileVariations(baseShader, outShaders);
  337. baseShader.type_ = PS;
  338. CompileVariations(baseShader, outShaders);
  339. }
  340. shader = shader.GetNext("shader");
  341. }
  342. }
  343. void CompileVariations(const Shader& baseShader, XMLElement& shaders)
  344. {
  345. unsigned combinations = 1;
  346. Set<unsigned> usedCombinations;
  347. Map<String, unsigned> nameToIndex;
  348. Vector<CompiledVariation> compiledVariations;
  349. unsigned numVariationGroups = 0;
  350. const Vector<Variation>& variations = baseShader.variations_;
  351. if (variations.Size() > 32)
  352. ErrorExit("Maximum amount of variations exceeded");
  353. // Load the shader source code
  354. {
  355. String inputFileName = inDir_ + baseShader.name_ + ".hlsl";
  356. File hlslFile(context_, inputFileName);
  357. if (!hlslFile.IsOpen())
  358. ErrorExit("Could not open input file " + inputFileName);
  359. hlslCode_.Clear();
  360. while (!hlslFile.IsEof())
  361. hlslCode_ += hlslFile.ReadLine() + "\n";
  362. }
  363. for (unsigned i = 0; i < variations.Size(); ++i)
  364. {
  365. combinations *= 2;
  366. nameToIndex[variations[i].name_] = i;
  367. if (!variations[i].option_ && (i == 0 || variations[i - 1].option_))
  368. ++numVariationGroups;
  369. }
  370. for (unsigned i = 0; i < combinations; ++i)
  371. {
  372. unsigned active = i; // Variations/options active on this particular combination
  373. unsigned variationsActive = 0;
  374. bool skipThis = false;
  375. // Check for excludes/includes/requires
  376. for (unsigned j = 0; j < variations.Size(); ++j)
  377. {
  378. if ((active >> j) & 1)
  379. {
  380. for (unsigned k = 0; k < variations[j].includes_.Size(); ++k)
  381. {
  382. if (nameToIndex.Contains(variations[j].includes_[k]))
  383. active |= (1 << nameToIndex[variations[j].includes_[k]]);
  384. }
  385. for (unsigned k = 0; k < variations[j].excludes_.Size(); ++k)
  386. {
  387. if (nameToIndex.Contains(variations[j].excludes_[k]))
  388. active &= ~(1 << nameToIndex[variations[j].excludes_[k]]);
  389. }
  390. // Skip dummy separators (options without name and defines)
  391. if (variations[j].name_.Empty() && variations[j].option_ && variations[j].defines_.Empty())
  392. active &= ~(1 << j);
  393. // If it's a variation, exclude all other variations in the same group
  394. if (!variations[j].option_)
  395. {
  396. for (unsigned k = j - 1; k < variations.Size(); --k)
  397. {
  398. if (!variations[k].option_)
  399. active &= ~(1 << k);
  400. else
  401. break;
  402. }
  403. for (unsigned k = j + 1; k < variations.Size(); ++k)
  404. {
  405. if (!variations[k].option_)
  406. active &= ~(1 << k);
  407. else
  408. break;
  409. }
  410. ++variationsActive;
  411. }
  412. for (unsigned k = 0; k < variations[j].requires_.Size(); ++k)
  413. {
  414. bool requireFound = false;
  415. for (unsigned l = 0; l < defines_.Size(); ++l)
  416. {
  417. if (defines_[l] == variations[j].requires_[k])
  418. {
  419. requireFound = true;
  420. break;
  421. }
  422. }
  423. for (unsigned l = 0; l < variations.Size(); ++l)
  424. {
  425. if ((active >> l) & 1 && l != j)
  426. {
  427. if (variations[l].name_ == variations[j].requires_[k])
  428. {
  429. requireFound = true;
  430. break;
  431. }
  432. for (unsigned m = 0; m < variations[l].defines_.Size(); ++m)
  433. {
  434. if (variations[l].defines_[m] == variations[j].requires_[k])
  435. {
  436. requireFound = true;
  437. break;
  438. }
  439. }
  440. }
  441. if (requireFound)
  442. break;
  443. }
  444. if (!requireFound)
  445. skipThis = true;
  446. }
  447. }
  448. }
  449. // If variations are included, check that one from each group is active
  450. if (variationsActive < numVariationGroups)
  451. continue;
  452. if (skipThis)
  453. continue;
  454. // Check that this combination is unique
  455. if (usedCombinations.Contains(active))
  456. continue;
  457. // Build shader variation name & defines for active variations
  458. String outName;
  459. Vector<String> defines;
  460. Vector<String> defineValues;
  461. for (unsigned j = 0; j < variations.Size(); ++j)
  462. {
  463. if (active & (1 << j))
  464. {
  465. if (variations[j].name_.Length())
  466. outName += variations[j].name_;
  467. for (unsigned k = 0; k < variations[j].defines_.Size(); ++k)
  468. {
  469. defines.Push(variations[j].defines_[k]);
  470. defineValues.Push(variations[j].defineValues_[k]);
  471. }
  472. }
  473. }
  474. CompiledVariation compile;
  475. compile.type_ = baseShader.type_;
  476. compile.name_ = outName;
  477. compile.defines_ = defines;
  478. compile.defineValues_ = defineValues;
  479. compiledVariations.Push(compile);
  480. usedCombinations.Insert(active);
  481. }
  482. // Prepare the work list
  483. // (all variations must be created first, so that vector resize does not change pointers)
  484. for (unsigned i = 0; i < compiledVariations.Size(); ++i)
  485. workList_.Push(&compiledVariations[i]);
  486. // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely
  487. unsigned numWorkerThreads = GetNumLogicalCPUs() - 1;
  488. if (!numWorkerThreads)
  489. numWorkerThreads = 1;
  490. Vector<SharedPtr<WorkerThread> > workerThreads;
  491. workerThreads.Resize(numWorkerThreads);
  492. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  493. {
  494. workerThreads[i] = new WorkerThread();
  495. workerThreads[i]->Start();
  496. }
  497. // This will wait until the thread functions have stopped
  498. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  499. workerThreads[i]->Stop();
  500. // Check that all shaders compiled
  501. for (unsigned i = 0; i < compiledVariations.Size(); ++i)
  502. {
  503. if (!compiledVariations[i].errorMsg_.Empty())
  504. ErrorExit("Failed to compile shader " + baseShader.name_ + "_" + compiledVariations[i].name_ + ": " + compiledVariations[i].errorMsg_);
  505. }
  506. // Build the output file
  507. String outFileName = outDir_ + inDir_ + baseShader.name_;
  508. outFileName += (baseShader.type_ == VS) ? ".vs" : ".ps";
  509. outFileName += (useSM3_) ? "3" : "2";
  510. File outFile(context_, outFileName, FILE_WRITE);
  511. if (!outFile.IsOpen())
  512. ErrorExit("Could not open output file " + outFileName);
  513. outFile.WriteFileID("USHD");
  514. outFile.WriteShort(baseShader.type_);
  515. outFile.WriteShort(useSM3_ ? 3 : 2);
  516. outFile.WriteUInt(constants_.Size());
  517. for (Set<String>::ConstIterator i = constants_.Begin(); i != constants_.End(); ++i)
  518. outFile.WriteString(*i);
  519. outFile.WriteUInt(textureUnits_.Size());
  520. for (Set<String>::ConstIterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  521. outFile.WriteString(*i);
  522. outFile.WriteUInt(compiledVariations.Size());
  523. for (unsigned i = 0; i < compiledVariations.Size(); ++i)
  524. {
  525. CompiledVariation& variation = compiledVariations[i];
  526. outFile.WriteString(variation.name_);
  527. outFile.WriteUInt(variation.constants_.Size());
  528. for (Set<Parameter>::ConstIterator i = variation.constants_.Begin(); i != variation.constants_.End(); ++i)
  529. {
  530. outFile.WriteStringHash(StringHash(i->name_));
  531. outFile.WriteUByte(i->register_);
  532. outFile.WriteUByte(i->regCount_);
  533. }
  534. outFile.WriteUInt(variation.textureUnits_.Size());
  535. for (Set<Parameter>::ConstIterator i = variation.textureUnits_.Begin(); i != variation.textureUnits_.End(); ++i)
  536. {
  537. outFile.WriteStringHash(StringHash(i->name_));
  538. outFile.WriteUByte(i->register_);
  539. }
  540. unsigned dataSize = variation.byteCode_.Size();
  541. outFile.WriteUInt(dataSize);
  542. if (dataSize)
  543. outFile.Write(&variation.byteCode_[0], dataSize);
  544. }
  545. }
  546. void Compile(CompiledVariation* variation)
  547. {
  548. IncludeHandler includeHandler;
  549. PODVector<D3DXMACRO> macros;
  550. // Insert variation-specific and global defines
  551. for (unsigned i = 0; i < variation->defines_.Size(); ++i)
  552. {
  553. D3DXMACRO macro;
  554. macro.Name = variation->defines_[i].CString();
  555. macro.Definition = variation->defineValues_[i].CString();
  556. macros.Push(macro);
  557. }
  558. for (unsigned i = 0; i < defines_.Size(); ++i)
  559. {
  560. D3DXMACRO macro;
  561. macro.Name = defines_[i].CString();
  562. macro.Definition = defineValues_[i].CString();
  563. macros.Push(macro);
  564. }
  565. D3DXMACRO endMacro;
  566. endMacro.Name = 0;
  567. endMacro.Definition = 0;
  568. macros.Push(endMacro);
  569. LPD3DXBUFFER shaderCode = 0;
  570. LPD3DXBUFFER errorMsgs = 0;
  571. LPD3DXCONSTANTTABLE constantTable = 0;
  572. // Set the profile, entrypoint and flags according to the shader being compiled
  573. String profile;
  574. String entryPoint;
  575. unsigned flags = D3DXSHADER_OPTIMIZATION_LEVEL3;
  576. if (variation->type_ == VS)
  577. {
  578. entryPoint = "VS";
  579. if (!useSM3_)
  580. profile = "vs_2_0";
  581. else
  582. profile = "vs_3_0";
  583. }
  584. else
  585. {
  586. entryPoint = "PS";
  587. if (!useSM3_)
  588. profile = "ps_2_0";
  589. else
  590. {
  591. profile = "ps_3_0";
  592. flags |= D3DXSHADER_PREFER_FLOW_CONTROL;
  593. }
  594. }
  595. // Compile using D3DX
  596. HRESULT hr = D3DXCompileShader(hlslCode_.CString(), hlslCode_.Length(), &macros.Front(), &includeHandler,
  597. entryPoint.CString(), profile.CString(), flags, &shaderCode, &errorMsgs, &constantTable);
  598. if (FAILED(hr))
  599. {
  600. variation->errorMsg_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  601. compileFailed_ = true;
  602. }
  603. else
  604. {
  605. CopyStrippedCode(variation->byteCode_, shaderCode->GetBufferPointer(), shaderCode->GetBufferSize());
  606. if (!variation->name_.Empty())
  607. PrintLine("Compiled shader variation " + variation->name_ + ", code size " + String(variation->byteCode_.Size()));
  608. else
  609. PrintLine("Compiled base shader variation, code size " + String(variation->byteCode_.Size()));
  610. // Print warnings if any
  611. if (errorMsgs && errorMsgs->GetBufferSize())
  612. {
  613. String warning((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  614. PrintLine("WARNING: " + warning);
  615. }
  616. // Parse the constant table for constants and texture units
  617. D3DXCONSTANTTABLE_DESC desc;
  618. constantTable->GetDesc(&desc);
  619. for (unsigned i = 0; i < desc.Constants; ++i)
  620. {
  621. D3DXHANDLE handle = constantTable->GetConstant(NULL, i);
  622. D3DXCONSTANT_DESC constantDesc;
  623. unsigned numElements = 1;
  624. constantTable->GetConstantDesc(handle, &constantDesc, &numElements);
  625. String name(constantDesc.Name);
  626. unsigned reg = constantDesc.RegisterIndex;
  627. unsigned regCount = constantDesc.RegisterCount;
  628. // Check if the parameter is a constant or a texture sampler
  629. bool isSampler = (name[0] == 's');
  630. name = name.Substring(1);
  631. MutexLock lock(globalParamMutex_);
  632. if (isSampler)
  633. {
  634. // Skip if it's a G-buffer sampler
  635. if (name.Find("Buffer") == String::NPOS)
  636. {
  637. Parameter newTextureUnit(name, reg, 1);
  638. variation->textureUnits_.Insert(newTextureUnit);
  639. textureUnits_.Insert(name);
  640. }
  641. }
  642. else
  643. {
  644. Parameter newParam(name, reg, regCount);
  645. variation->constants_.Insert(newParam);
  646. constants_.Insert(name);
  647. }
  648. }
  649. }
  650. if (shaderCode)
  651. shaderCode->Release();
  652. if (constantTable)
  653. constantTable->Release();
  654. if (errorMsgs)
  655. errorMsgs->Release();
  656. }
  657. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize)
  658. {
  659. unsigned* srcWords = (unsigned*)src;
  660. unsigned srcWordSize = srcSize >> 2;
  661. dest.Clear();
  662. for (unsigned i = 0; i < srcWordSize; ++i)
  663. {
  664. unsigned opcode = srcWords[i] & 0xffff;
  665. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  666. unsigned commentLength = srcWords[i] >> 16;
  667. // For now, skip comment only at fixed position to prevent false positives
  668. if (i == 1 && opcode == D3DSIO_COMMENT)
  669. {
  670. // Skip the comment
  671. i += commentLength;
  672. }
  673. else
  674. {
  675. // Not a comment, copy the data
  676. unsigned char* srcBytes = (unsigned char*)(srcWords + i);
  677. dest.Push(*srcBytes++);
  678. dest.Push(*srcBytes++);
  679. dest.Push(*srcBytes++);
  680. dest.Push(*srcBytes++);
  681. }
  682. }
  683. }