ShaderCompiler.cpp 26 KB

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