GLShaderProcessor.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 "DebugNew.h"
  35. enum ShaderType
  36. {
  37. VS = 0,
  38. PS,
  39. Both
  40. };
  41. struct Parameter
  42. {
  43. Parameter()
  44. {
  45. }
  46. Parameter(const String& name, unsigned index) :
  47. name_(name),
  48. index_(index)
  49. {
  50. }
  51. bool operator < (const Parameter& rhs) const
  52. {
  53. if (index_ != rhs.index_)
  54. return index_ < rhs.index_;
  55. else
  56. return name_ < rhs.name_;
  57. }
  58. bool operator > (const Parameter& rhs) const
  59. {
  60. if (index_ != rhs.index_)
  61. return index_ > rhs.index_;
  62. else
  63. return name_ > rhs.name_;
  64. }
  65. bool operator == (const Parameter& rhs) const { return index_ == rhs.index_ && name_ == rhs.name_; }
  66. bool operator != (const Parameter& rhs) const { return index_ != rhs.index_ || name_ != rhs.name_; }
  67. String name_;
  68. unsigned index_;
  69. };
  70. struct Variation
  71. {
  72. Variation()
  73. {
  74. }
  75. Variation(const String& name, bool isOption) :
  76. name_(name),
  77. option_(isOption)
  78. {
  79. }
  80. String name_;
  81. Vector<String> defines_;
  82. Vector<String> excludes_;
  83. Vector<String> includes_;
  84. Vector<String> requires_;
  85. bool option_;
  86. };
  87. struct ProcessedVariation
  88. {
  89. ShaderType type_;
  90. String name_;
  91. Vector<String> defines_;
  92. };
  93. struct Shader
  94. {
  95. Shader(const String& name, ShaderType type) :
  96. name_(name),
  97. type_(type)
  98. {
  99. }
  100. String name_;
  101. ShaderType type_;
  102. Vector<Variation> variations_;
  103. };
  104. SharedPtr<Context> context_(new Context());
  105. SharedPtr<FileSystem> fileSystem_(new FileSystem(context_));
  106. String inDir_;
  107. String inFile_;
  108. String outDir_;
  109. Set<Parameter> constants_;
  110. Set<Parameter> textureUnits_;
  111. Vector<String> defines_;
  112. Vector<String> glslCode_;
  113. int main(int argc, char** argv);
  114. void Run(const Vector<String>& arguments);
  115. void ProcessVariations(const Shader& baseShader, XMLElement& shaders);
  116. int main(int argc, char** argv)
  117. {
  118. Vector<String> arguments;
  119. for (int i = 1; i < argc; ++i)
  120. {
  121. String argument(argv[i]);
  122. arguments.Push(GetInternalPath(argument));
  123. }
  124. Run(arguments);
  125. return 0;
  126. }
  127. void Run(const Vector<String>& arguments)
  128. {
  129. if (arguments.Size() < 2)
  130. {
  131. ErrorExit(
  132. "Usage: GLShaderProcessor <definitionfile> <outputpath> [define1] [define2]\n\n"
  133. "GLSL files will be loaded from definition file directory, and finalized GLSL +\n"
  134. "XML files are saved to the output path, preserving the subdirectory structure.\n"
  135. );
  136. }
  137. unsigned pos = arguments[0].FindLast('/');
  138. if (pos != String::NPOS)
  139. {
  140. inDir_ = arguments[0].Substring(0, pos);
  141. inFile_ = arguments[0].Substring(pos + 1);
  142. }
  143. else
  144. {
  145. inFile_ = arguments[0];
  146. }
  147. outDir_ = arguments[1];
  148. inDir_ = AddTrailingSlash(inDir_);
  149. outDir_ = AddTrailingSlash(outDir_);
  150. for (unsigned i = 2; i < arguments.Size(); ++i)
  151. {
  152. String arg = arguments[i].ToUpper();
  153. defines_.Push(arg);
  154. }
  155. XMLFile doc(context_);
  156. File source(context_);
  157. source.Open(arguments[0]);
  158. if (!doc.Load(source))
  159. ErrorExit("Could not open input file " + arguments[0]);
  160. XMLElement shaders = doc.GetRoot("shaders");
  161. if (!shaders)
  162. ErrorExit("No shaders element in " + source.GetName());
  163. XMLFile outDoc(context_);
  164. XMLElement outShaders = outDoc.CreateRoot("shaders");
  165. XMLElement shader = shaders.GetChild("shader");
  166. while (shader)
  167. {
  168. String source = shader.GetString("name");
  169. ShaderType compileType = Both;
  170. String type = shader.GetString("type");
  171. if (type == "VS" || type == "vs")
  172. compileType = VS;
  173. if (type == "PS" || type == "ps")
  174. compileType = PS;
  175. Shader baseShader(source, compileType);
  176. XMLElement variation = shader.GetChild("");
  177. while (variation)
  178. {
  179. String value = variation.GetName();
  180. if (value == "variation" || value == "option")
  181. {
  182. String name = variation.GetString("name");
  183. Variation newVar(name, value == "option");
  184. String simpleDefine = variation.GetString("define");
  185. if (!simpleDefine.Empty())
  186. newVar.defines_.Push(simpleDefine);
  187. String simpleExclude = variation.GetString("exclude");
  188. if (!simpleExclude.Empty())
  189. newVar.excludes_.Push(simpleExclude);
  190. String simpleInclude = variation.GetString("include");
  191. if (!simpleInclude.Empty())
  192. newVar.includes_.Push(simpleInclude);
  193. String simpleRequire = variation.GetString("require");
  194. if (!simpleRequire.Empty())
  195. newVar.requires_.Push(simpleRequire);
  196. XMLElement define = variation.GetChild("define");
  197. while (define)
  198. {
  199. newVar.defines_.Push(define.GetString("name"));
  200. define = define.GetNext("define");
  201. }
  202. XMLElement exclude = variation.GetChild("exclude");
  203. while (exclude)
  204. {
  205. newVar.excludes_.Push(exclude.GetString("name"));
  206. exclude = exclude.GetNext("exclude");
  207. }
  208. XMLElement include = variation.GetChild("include");
  209. while (include)
  210. {
  211. newVar.includes_.Push(include.GetString("name"));
  212. include = include.GetNext("include");
  213. }
  214. XMLElement require = variation.GetChild("require");
  215. while (require)
  216. {
  217. newVar.requires_.Push(require.GetString("name"));
  218. require = require.GetNext("require");
  219. }
  220. baseShader.variations_.Push(newVar);
  221. }
  222. variation = variation.GetNext();
  223. }
  224. if (baseShader.type_ != Both)
  225. ProcessVariations(baseShader, outShaders);
  226. else
  227. {
  228. baseShader.type_ = VS;
  229. ProcessVariations(baseShader, outShaders);
  230. baseShader.type_ = PS;
  231. ProcessVariations(baseShader, outShaders);
  232. }
  233. shader = shader.GetNext("shader");
  234. }
  235. }
  236. void ProcessVariations(const Shader& baseShader, XMLElement& shaders)
  237. {
  238. constants_.Clear();
  239. textureUnits_.Clear();
  240. unsigned combinations = 1;
  241. Set<unsigned> usedCombinations;
  242. Map<String, unsigned> nameToIndex;
  243. Vector<ProcessedVariation> processedVariations;
  244. unsigned numVariationGroups = 0;
  245. const Vector<Variation>& variations = baseShader.variations_;
  246. if (variations.Size() > 32)
  247. ErrorExit("Maximum amount of variations exceeded");
  248. // Load the shader source code
  249. String inputFileName = inDir_ + baseShader.name_;
  250. if (baseShader.type_ == VS)
  251. inputFileName += ".vert";
  252. if (baseShader.type_ == PS)
  253. inputFileName += ".frag";
  254. {
  255. File glslFile(context_, inputFileName);
  256. if (!glslFile.IsOpen())
  257. ErrorExit("Could not open input file " + inputFileName);
  258. glslCode_.Clear();
  259. while (!glslFile.IsEof())
  260. glslCode_.Push(glslFile.ReadLine());
  261. }
  262. // Process the code for includes
  263. for (unsigned i = 0; i < glslCode_.Size(); ++i)
  264. {
  265. if (glslCode_[i].Find("#include") == 0)
  266. {
  267. unsigned quoteStart = glslCode_[i].Find('<');
  268. unsigned quoteEnd = glslCode_[i].FindLast('>');
  269. if (quoteStart == String::NPOS)
  270. {
  271. quoteStart = glslCode_[i].Find('\"');
  272. quoteEnd = glslCode_[i].FindLast('\"');
  273. }
  274. if (quoteStart != String::NPOS)
  275. {
  276. ++quoteStart;
  277. String includeFileName = glslCode_[i].Substring(quoteStart, quoteEnd - quoteStart);
  278. String inputFilePath = GetPath(inputFileName);
  279. while (includeFileName.Find("../") == 0 || includeFileName.Find("..\\") == 0)
  280. {
  281. includeFileName = includeFileName.Substring(3);
  282. inputFilePath = GetParentPath(inputFilePath);
  283. }
  284. includeFileName = inputFilePath + includeFileName;
  285. File glslIncludeFile(context_, includeFileName);
  286. if (!glslIncludeFile.IsOpen())
  287. ErrorExit("Could not open input file " + includeFileName);
  288. // Remove the #include line, then include the code
  289. glslCode_.Erase(i);
  290. unsigned pos = i;
  291. while (!glslIncludeFile.IsEof())
  292. {
  293. glslCode_.Insert(pos, glslIncludeFile.ReadLine());
  294. ++pos;
  295. }
  296. // Finally insert an empty line to mark the space between files
  297. glslCode_.Insert(pos, "");
  298. }
  299. }
  300. }
  301. for (unsigned i = 0; i < variations.Size(); ++i)
  302. {
  303. combinations *= 2;
  304. nameToIndex[variations[i].name_] = i;
  305. if (!variations[i].option_ && (i == 0 || variations[i - 1].option_))
  306. ++numVariationGroups;
  307. }
  308. for (unsigned i = 0; i < combinations; ++i)
  309. {
  310. unsigned active = i; // Variations/options active on this particular combination
  311. unsigned variationsActive = 0;
  312. bool skipThis = false;
  313. // Check for excludes/includes/requires
  314. for (unsigned j = 0; j < variations.Size(); ++j)
  315. {
  316. if ((active >> j) & 1)
  317. {
  318. for (unsigned k = 0; k < variations[j].includes_.Size(); ++k)
  319. {
  320. if (nameToIndex.Find(variations[j].includes_[k]) != nameToIndex.End())
  321. active |= (1 << nameToIndex[variations[j].includes_[k]]);
  322. }
  323. for (unsigned k = 0; k < variations[j].excludes_.Size(); ++k)
  324. {
  325. if (nameToIndex.Find(variations[j].excludes_[k]) != nameToIndex.End())
  326. active &= ~(1 << nameToIndex[variations[j].excludes_[k]]);
  327. }
  328. // Skip dummy separators (options without name and defines)
  329. if (variations[j].name_.Empty() && variations[j].option_ && variations[j].defines_.Empty())
  330. active &= ~(1 << j);
  331. // If it's a variation, exclude all other variations in the same group
  332. if (!variations[j].option_)
  333. {
  334. for (unsigned k = j - 1; k < variations.Size(); --k)
  335. {
  336. if (!variations[k].option_)
  337. active &= ~(1 << k);
  338. else
  339. break;
  340. }
  341. for (unsigned k = j + 1; k < variations.Size(); ++k)
  342. {
  343. if (!variations[k].option_)
  344. active &= ~(1 << k);
  345. else
  346. break;
  347. }
  348. ++variationsActive;
  349. }
  350. for (unsigned k = 0; k < variations[j].requires_.Size(); ++k)
  351. {
  352. bool requireFound = false;
  353. for (unsigned l = 0; l < defines_.Size(); ++l)
  354. {
  355. if (defines_[l] == variations[j].requires_[k])
  356. {
  357. requireFound = true;
  358. break;
  359. }
  360. }
  361. for (unsigned l = 0; l < variations.Size(); ++l)
  362. {
  363. if ((active >> l) & 1 && l != j)
  364. {
  365. if (variations[l].name_ == variations[j].requires_[k])
  366. {
  367. requireFound = true;
  368. break;
  369. }
  370. for (unsigned m = 0; m < variations[l].defines_.Size(); ++m)
  371. {
  372. if (variations[l].defines_[m] == variations[j].requires_[k])
  373. {
  374. requireFound = true;
  375. break;
  376. }
  377. }
  378. }
  379. if (requireFound)
  380. break;
  381. }
  382. if (!requireFound)
  383. skipThis = true;
  384. }
  385. }
  386. }
  387. // If variations are included, check that one from each group is active
  388. if (variationsActive < numVariationGroups)
  389. continue;
  390. if (skipThis)
  391. continue;
  392. // Check that this combination is unique
  393. if (usedCombinations.Contains(active))
  394. continue;
  395. // Build shader variation name & define active variations
  396. String outName;
  397. Vector<String> defines;
  398. for (unsigned j = 0; j < variations.Size(); ++j)
  399. {
  400. if (active & (1 << j))
  401. {
  402. if (variations[j].name_.Length())
  403. outName += variations[j].name_;
  404. for (unsigned k = 0; k < variations[j].defines_.Size(); ++k)
  405. defines.Push(variations[j].defines_[k]);
  406. }
  407. }
  408. ProcessedVariation processed;
  409. processed.type_ = baseShader.type_;
  410. processed.name_ = outName;
  411. processed.defines_ = defines;
  412. processedVariations.Push(processed);
  413. usedCombinations.Insert(active);
  414. }
  415. // Build the output file
  416. String glslOutFileName = outDir_ + inDir_ + baseShader.name_;
  417. glslOutFileName += baseShader.type_ == VS ? ".vert" : ".frag";
  418. String xmlOutFileName = glslOutFileName + ".xml";
  419. File outFile(context_, glslOutFileName, FILE_WRITE);
  420. if (!outFile.IsOpen())
  421. ErrorExit("Could not open output file " + glslOutFileName);
  422. for (unsigned i = 0; i < glslCode_.Size(); ++i)
  423. {
  424. if (!glslCode_[i].Empty())
  425. outFile.Write(&glslCode_[i][0], glslCode_[i].Length());
  426. outFile.WriteByte(10);
  427. }
  428. outFile.Close();
  429. XMLFile xmlOutFile(context_);
  430. XMLElement shaderElem = xmlOutFile.CreateRoot("shader");
  431. shaderElem.SetString("type", baseShader.type_ == VS ? "vs" : "ps");
  432. for (unsigned i = 0; i < processedVariations.Size(); ++i)
  433. {
  434. XMLElement variationElem = shaderElem.CreateChild("variation");
  435. variationElem.SetString("name", processedVariations[i].name_);
  436. String allDefines;
  437. for (unsigned j = 0; j < processedVariations[i].defines_.Size(); ++j)
  438. {
  439. if (j)
  440. allDefines += " ";
  441. allDefines += processedVariations[i].defines_[j];
  442. }
  443. variationElem.SetString("defines", allDefines);
  444. }
  445. outFile.Open(xmlOutFileName, FILE_WRITE);
  446. if (!outFile.IsOpen())
  447. ErrorExit("Could not open output file " + xmlOutFileName);
  448. xmlOutFile.Save(outFile);
  449. outFile.Close();
  450. }