ShaderUnit.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. #include "ShaderUnit.h"
  2. #include "WallpaperEngine/Logging/Log.h"
  3. #include <cctype>
  4. #include <charconv>
  5. #include <exception>
  6. #include <mutex>
  7. #include <optional>
  8. #include <regex>
  9. #include <stack>
  10. #include <string>
  11. #include <unordered_map>
  12. #include <utility>
  13. #include "GLSLContext.h"
  14. #include "WallpaperEngine/Assets/AssetLoadException.h"
  15. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariable.h"
  16. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableFloat.h"
  17. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableInteger.h"
  18. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector2.h"
  19. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector3.h"
  20. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector4.h"
  21. #include "WallpaperEngine/Data/Builders/VectorBuilder.h"
  22. #include "WallpaperEngine/FileSystem/Container.h"
  23. #define SHADER_HEADER(filename) \
  24. "#version 330\n" \
  25. "// ======================================================\n" \
  26. "// Processed shader " \
  27. + filename \
  28. + "\n" \
  29. "// ======================================================\n" \
  30. "precision highp float;\n" \
  31. "#define mul(x, y) ((y) * (x))\n" \
  32. "#define max(x, y) max (y, x)\n" \
  33. "#define lerp mix\n" \
  34. "#define frac fract\n" \
  35. "#define CAST2(x) (vec2(x))\n" \
  36. "#define CAST3(x) (vec3(x))\n" \
  37. "#define CAST4(x) (vec4(x))\n" \
  38. "#define CAST3X3(x) (mat3(x))\n" \
  39. "#define float2 vec2\n" \
  40. "#define float3 vec3\n" \
  41. "#define float4 vec4\n" \
  42. "#define int2 ivec2\n" \
  43. "#define int3 ivec3\n" \
  44. "#define int4 ivec4\n" \
  45. "#define saturate(x) (clamp(x, 0.0, 1.0))\n" \
  46. "#define texSample2D texture\n" \
  47. "#define texSample2DLod textureLod\n" \
  48. "#define atan2 atan\n" \
  49. "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n" \
  50. "#define ddx dFdx\n" \
  51. "#define ddy(x) dFdy(-(x))\n" \
  52. "#define GLSL 1\n\n";
  53. #define FRAGMENT_SHADER_DEFINES \
  54. "out vec4 out_FragColor;\n" \
  55. "#define varying in\n"
  56. #define VERTEX_SHADER_DEFINES \
  57. "#define attribute in\n" \
  58. "#define varying out\n"
  59. #define DEFINE_COMBO(name, value) "#define " + name + " " + std::to_string (value) + "\n";
  60. using namespace WallpaperEngine::Render;
  61. using namespace WallpaperEngine::Data::Builders;
  62. using namespace WallpaperEngine::Render::Shaders;
  63. namespace {
  64. // the quoted filename of the #include at start, or nothing if the quotes aren't on the same line
  65. std::optional<std::string> includeFilename (const std::string& source, const size_t start) {
  66. const size_t lineEnd = std::min (source.find ('\n', start), source.size ());
  67. const size_t quoteStart = source.find ('"', start);
  68. if (quoteStart >= lineEnd) {
  69. return std::nullopt;
  70. }
  71. const size_t quoteEnd = source.find ('"', quoteStart + 1);
  72. if (quoteEnd >= lineEnd) {
  73. return std::nullopt;
  74. }
  75. return source.substr (quoteStart + 1, quoteEnd - quoteStart - 1);
  76. }
  77. } // namespace
  78. ShaderUnit::ShaderUnit (
  79. const GLSLContext::UnitType type, std::string file, std::string content, const AssetLocator& assetLocator,
  80. const ShaderConstantMap& constants, const TextureMap& passTextures, const TextureMap& overrideTextures,
  81. const ComboMap& combos, const ComboMap& overrideCombos
  82. ) :
  83. m_type (type), m_file (std::move (file)), m_content (std::move (content)), m_combos (combos),
  84. m_overrideCombos (overrideCombos), m_constants (constants), m_passTextures (passTextures),
  85. m_overrideTextures (overrideTextures), m_link (nullptr), m_assetLocator (assetLocator) {
  86. this->preprocess ();
  87. }
  88. void ShaderUnit::preprocess () {
  89. this->m_preprocessed = this->m_content;
  90. this->m_includes = "";
  91. this->preprocessIncludes ();
  92. this->preprocessRequires ();
  93. this->preprocessVariables ();
  94. this->preprocessBalanceConditionals ();
  95. this->preprocessSwizzledDeclarations ();
  96. const std::string from = "gl_FragColor";
  97. const std::string to = "out_FragColor";
  98. size_t start_pos = 0;
  99. while ((start_pos = this->m_preprocessed.find (from, start_pos)) != std::string::npos) {
  100. this->m_preprocessed.replace (start_pos, from.length (), to);
  101. start_pos += to.length (); // avoids re-matching if 'to' is a substring of 'from'
  102. }
  103. }
  104. void ShaderUnit::preprocessVariables () {
  105. size_t start = 0, end = 0;
  106. while ((end = this->m_preprocessed.find ('\n', start)) != std::string::npos) {
  107. std::string line = this->m_preprocessed.substr (start, end - start);
  108. const size_t combo = line.find ("// [COMBO] ");
  109. const size_t uniform = line.find ("uniform ");
  110. const size_t comment = line.find ("// ");
  111. const size_t semicolon = line.find (';');
  112. if (combo != std::string::npos) {
  113. this->parseComboConfiguration (line.substr (combo + strlen ("// [COMBO] ")), 0);
  114. } else if (
  115. uniform != std::string::npos && comment != std::string::npos && semicolon != std::string::npos &&
  116. // semicolon before comment means it's a trailing comment, not a commented-out line
  117. // (doesn't account for block comments)
  118. semicolon < comment
  119. ) {
  120. // uniforms with trailing comments never have a value assigned, which is what lets this find type/name
  121. const size_t last_space = line.find_last_of (' ', semicolon);
  122. if (last_space != std::string::npos) {
  123. const size_t previous_space = line.find_last_of (' ', last_space - 1);
  124. if (previous_space != std::string::npos) {
  125. std::string type = line.substr (previous_space + 1, last_space - previous_space - 1);
  126. std::string name = line.substr (last_space + 1, semicolon - last_space - 1);
  127. std::string json = line.substr (comment + 2);
  128. this->parseParameterConfiguration (type, name, json);
  129. }
  130. }
  131. }
  132. start = end + 1;
  133. }
  134. }
  135. void ShaderUnit::preprocessIncludes () {
  136. size_t start = 0, end = 0;
  137. while ((start = this->m_preprocessed.find ("#include", end)) != std::string::npos) {
  138. const auto parsed = includeFilename (this->m_preprocessed, start);
  139. // comment out just the "#i" so the string length/offsets are unaffected
  140. this->m_preprocessed = this->m_preprocessed.replace (start, 2, "//");
  141. end = start;
  142. if (!parsed.has_value ()) {
  143. sLog.error ("Malformed #include directive in shader ", this->m_file);
  144. continue;
  145. }
  146. const std::string& filename = *parsed;
  147. // a missing include isn't necessarily an error - it may come from commented-out content
  148. std::string content;
  149. try {
  150. content += "// begin of include from file ";
  151. content += filename;
  152. content += "\n";
  153. content += this->m_assetLocator.includeShader (filename);
  154. content += "\n// end of included from file ";
  155. content += filename;
  156. content += "\n";
  157. } catch (AssetLoadException&) {
  158. content += "// tried including file ";
  159. content += filename;
  160. content += " but was not found\n";
  161. }
  162. this->m_includes += content;
  163. }
  164. // resolve #include directives found inside already-included content too
  165. end = 0;
  166. while ((start = this->m_includes.find ("#include", end)) != std::string::npos) {
  167. const size_t lineEnd = this->m_includes.find_first_of ('\n', start);
  168. const auto parsed = includeFilename (this->m_includes, start);
  169. end = start;
  170. if (!parsed.has_value ()) {
  171. sLog.error ("Malformed #include directive in an include of shader ", this->m_file);
  172. this->m_includes = this->m_includes.replace (start, 2, "//");
  173. continue;
  174. }
  175. const std::string& filename = *parsed;
  176. // a missing include isn't necessarily an error - it may come from commented-out content
  177. std::string content;
  178. try {
  179. content = "// begin of include from file ";
  180. content += filename;
  181. content += "\n";
  182. content += this->m_assetLocator.includeShader (filename);
  183. content += "\n// end of included from file ";
  184. content += filename;
  185. content += "\n";
  186. } catch (AssetLoadException&) {
  187. content = "// tried including file ";
  188. content += filename;
  189. content += " but was not found\n";
  190. }
  191. this->m_includes = this->m_includes.replace (start, lineEnd - start, content);
  192. }
  193. // place the accumulated include contents right before the main function
  194. end = 0;
  195. bool includesAdded = false;
  196. while ((start = this->m_preprocessed.find (" main", end)) != std::string::npos) {
  197. char value = this->m_preprocessed.at (start + 5);
  198. end = start + 5;
  199. if (value != ' ' && value != '(') {
  200. continue;
  201. }
  202. size_t lastAttribute = this->m_preprocessed.rfind ("attribute", start);
  203. size_t lastVarying = this->m_preprocessed.rfind ("varying", start);
  204. size_t lastUniform = this->m_preprocessed.rfind ("uniform", start);
  205. size_t latest = lastAttribute;
  206. if (latest == std::string::npos) {
  207. latest = lastVarying;
  208. } else if (latest < lastVarying && lastVarying != std::string::npos) {
  209. latest = lastVarying;
  210. }
  211. if (latest == std::string::npos) {
  212. latest = lastUniform;
  213. } else if (latest < lastUniform && lastUniform != std::string::npos) {
  214. latest = lastUniform;
  215. }
  216. if (latest < start) {
  217. // find the end of the current line
  218. latest = this->m_preprocessed.find ('\n', latest);
  219. } else {
  220. // find the end of the previous line
  221. latest = this->m_preprocessed.rfind ('\n', start);
  222. }
  223. // start points at the end of the previous line, used below to place the includes
  224. start = this->m_preprocessed.rfind ('\n', start);
  225. // tracks nested #if/#endif so the includes can be moved before the start of the enclosing chain
  226. std::stack<size_t> ifdefStack;
  227. const std::regex ifdef (R"((#if|#endif))");
  228. std::smatch match;
  229. size_t current = 0;
  230. while (
  231. std::regex_search (this->m_preprocessed.cbegin () + current, this->m_preprocessed.cend (), match, ifdef)) {
  232. current += match.position ();
  233. if (this->m_preprocessed.substr (current, 3) == "#if") {
  234. ifdefStack.push (current++); // advance past this match so regex_search doesn't rematch it
  235. continue;
  236. }
  237. current++; // same reason: advance past this match
  238. // an unmatched #endif is most likely a syntax error; ignored for now
  239. if (ifdefStack.empty ()) {
  240. continue;
  241. }
  242. size_t stackStart = ifdefStack.top ();
  243. ifdefStack.pop ();
  244. if (latest > stackStart && latest <= current) {
  245. // insertion point is inside a conditional block - move before the #if so includes are
  246. // available to all branches (e.g. genericropeparticle.vert has #if GS_ENABLED wrapping two main()s)
  247. size_t beforeIfdef = this->m_preprocessed.rfind ('\n', stackStart);
  248. latest = (beforeIfdef != std::string::npos) ? beforeIfdef : 0;
  249. }
  250. }
  251. // TODO: IS THIS GOOD ENOUGH? MAYBE WE SHOULD BE GETTING THE FIRST #IF BLOCK INSTEAD?
  252. latest = std::min (latest, start);
  253. this->m_preprocessed.insert (latest + 1, this->m_includes + '\n');
  254. includesAdded = true;
  255. break;
  256. }
  257. if (!includesAdded) {
  258. sLog.exception ("Could not find where to place includes for shader unit ", this->m_file);
  259. }
  260. }
  261. void ShaderUnit::preprocessRequires () {
  262. size_t start = 0, end = 0;
  263. while ((start = this->m_preprocessed.find ("#require", end)) != std::string::npos) {
  264. const size_t lineEnd = this->m_preprocessed.find_first_of ('\n', start);
  265. const size_t nameStart = start + std::string ("#require ").length ();
  266. if (nameStart >= lineEnd) {
  267. sLog.error ("Malformed #require directive (no module name) in shader ", this->m_file);
  268. end = lineEnd;
  269. continue;
  270. }
  271. std::string moduleName = this->m_preprocessed.substr (nameStart, lineEnd - nameStart);
  272. while (!moduleName.empty () && (moduleName.back () == ' ' || moduleName.back () == '\r')) {
  273. moduleName.pop_back ();
  274. }
  275. if (moduleName.empty ()) {
  276. sLog.error ("Malformed #require directive (empty module name) in shader ", this->m_file);
  277. end = lineEnd;
  278. continue;
  279. }
  280. sLog.out ("Resolving require module: ", moduleName, " in shader ", this->m_file);
  281. std::string moduleCode = this->resolveRequireModule (moduleName);
  282. this->m_preprocessed = this->m_preprocessed.replace (start, 2, "//");
  283. if (!moduleCode.empty ()) {
  284. // inserted directly here, not appended to m_includes - that was already consumed by preprocessIncludes
  285. this->m_preprocessed.insert (start, moduleCode);
  286. end = start + moduleCode.length ();
  287. } else {
  288. end = lineEnd;
  289. }
  290. }
  291. }
  292. std::string ShaderUnit::resolveRequireModule (const std::string& moduleName) const {
  293. if (moduleName == "LightingV1") {
  294. return this->generateLightingV1 ();
  295. }
  296. sLog.error ("Unknown #require module: ", moduleName, " in shader ", this->m_file);
  297. return "";
  298. }
  299. std::string ShaderUnit::generateLightingV1 () const {
  300. // Wallpaper Engine generates this from the scene's light sources; since light objects
  301. // aren't supported yet, stub it out with no dynamic light contribution.
  302. return "// begin of generated module LightingV1\n"
  303. "vec3 PerformLighting_V1(vec3 worldPos, vec3 albedo, vec3 normal, vec3 viewDir,\n"
  304. " vec3 specularTint, vec3 baseReflectance, float roughness, float metallic)\n"
  305. "{\n"
  306. " return vec3(0.0);\n"
  307. "}\n"
  308. "// end of generated module LightingV1\n";
  309. }
  310. void ShaderUnit::preprocessBalanceConditionals () {
  311. static const std::regex directive (R"((?:^|\n)[ \t]*#(ifndef|ifdef|if|endif)\b)");
  312. int depth = 0;
  313. std::vector<size_t> extraEndifs;
  314. auto begin = std::sregex_iterator (this->m_preprocessed.cbegin (), this->m_preprocessed.cend (), directive);
  315. auto end = std::sregex_iterator ();
  316. for (auto it = begin; it != end; ++it) {
  317. const std::string& keyword = (*it)[1].str ();
  318. if (keyword == "endif") {
  319. if (depth == 0) {
  320. // position of the '#' character for this directive
  321. extraEndifs.push_back (it->position (1) - 1);
  322. } else {
  323. depth--;
  324. }
  325. } else {
  326. depth++;
  327. }
  328. }
  329. // comment out the extra #endif directives, from the end so earlier offsets stay valid
  330. for (auto it = extraEndifs.rbegin (); it != extraEndifs.rend (); ++it) {
  331. sLog.out ("Found #endif with no matching #if in shader ", this->m_file, ", ignoring it");
  332. this->m_preprocessed.replace (*it, 2, "//");
  333. }
  334. }
  335. void ShaderUnit::preprocessSwizzledDeclarations () {
  336. static const std::regex swizzledDecl (
  337. R"(\b(varying|uniform|attribute)(\s+[A-Za-z0-9_]+\s+[A-Za-z_][A-Za-z0-9_]*)\.[xyzwrgba]+(\s*;))"
  338. );
  339. const std::string original = this->m_preprocessed;
  340. this->m_preprocessed = std::regex_replace (this->m_preprocessed, swizzledDecl, "$1$2$3");
  341. if (this->m_preprocessed != original) {
  342. sLog.out ("Dropped swizzle from declaration name in shader ", this->m_file);
  343. }
  344. }
  345. std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source) const {
  346. static const std::regex vectorDecl (R"(\b(vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
  347. static const std::regex narrowAssign (R"(\b(vec[23])\s+[A-Za-z_][A-Za-z0-9_]*\s*=\s*([^;{}]+);)");
  348. // name -> width, 0 when the same name is declared with different widths in different scopes
  349. std::unordered_map<std::string, int> widths;
  350. for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), vectorDecl); it != std::sregex_iterator ();
  351. ++it) {
  352. const int width = (*it)[1].str ().back () - '0';
  353. const std::string name = (*it)[2].str ();
  354. const auto found = widths.find (name);
  355. if (found == widths.end ()) {
  356. widths.emplace (name, width);
  357. } else if (found->second != width) {
  358. found->second = 0;
  359. }
  360. }
  361. static const char* swizzles[] = { "", "", ".xy", ".xyz" };
  362. std::string result;
  363. size_t last = 0;
  364. bool changed = false;
  365. for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), narrowAssign);
  366. it != std::sregex_iterator (); ++it) {
  367. const int targetWidth = (*it)[1].str ().back () - '0';
  368. const size_t exprStart = it->position (2);
  369. const std::string expr = (*it)[2].str ();
  370. std::string fixed;
  371. int depth = 0;
  372. for (size_t i = 0; i < expr.size ();) {
  373. const char c = expr[i];
  374. if (c == '(' || c == '[') {
  375. depth++;
  376. } else if (c == ')' || c == ']') {
  377. depth--;
  378. }
  379. if (!(std::isalpha (static_cast<unsigned char> (c)) || c == '_')) {
  380. fixed += c;
  381. i++;
  382. continue;
  383. }
  384. size_t end = i;
  385. while (end < expr.size () && (std::isalnum (static_cast<unsigned char> (expr[end])) || expr[end] == '_')) {
  386. end++;
  387. }
  388. const std::string ident = expr.substr (i, end - i);
  389. fixed += ident;
  390. size_t before = i;
  391. while (before > 0 && std::isspace (static_cast<unsigned char> (expr[before - 1]))) {
  392. before--;
  393. }
  394. size_t after = end;
  395. while (after < expr.size () && std::isspace (static_cast<unsigned char> (expr[after]))) {
  396. after++;
  397. }
  398. const bool member = before > 0 && expr[before - 1] == '.';
  399. const bool accessed = after < expr.size () && (expr[after] == '.' || expr[after] == '(' || expr[after] == '[');
  400. const auto found = widths.find (ident);
  401. if (depth == 0 && !member && !accessed && found != widths.end () && found->second > targetWidth) {
  402. fixed += swizzles[targetWidth];
  403. changed = true;
  404. }
  405. i = end;
  406. }
  407. result.append (source, last, exprStart - last);
  408. result += fixed;
  409. last = exprStart + expr.size ();
  410. }
  411. if (!changed) {
  412. return source;
  413. }
  414. result.append (source, last, std::string::npos);
  415. sLog.out ("Applied vector truncation compatibility in shader ", this->m_file);
  416. return result;
  417. }
  418. std::string ShaderUnit::applyFloatConditionCompatibility (std::string source) const {
  419. static const std::regex floatDecl (R"(\b(float|vec[234]|int|bool|mat[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
  420. static const std::regex ternaryCond (R"(\b([A-Za-z_][A-Za-z0-9_]*)\s*\?)");
  421. static const std::regex ifCond (R"(\bif\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\))");
  422. // names that are only ever declared as float
  423. std::unordered_map<std::string, bool> onlyFloat;
  424. for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), floatDecl); it != std::sregex_iterator ();
  425. ++it) {
  426. const bool isFloat = (*it)[1].str () == "float";
  427. const std::string name = (*it)[2].str ();
  428. const auto found = onlyFloat.find (name);
  429. if (found == onlyFloat.end()) {
  430. onlyFloat.emplace (name, isFloat);
  431. } else if (!isFloat) {
  432. found->second = false;
  433. }
  434. }
  435. std::string result;
  436. size_t last = 0;
  437. bool changed = false;
  438. auto rewrite = [&] (const std::regex& pattern, bool ternary) {
  439. result.clear ();
  440. last = 0;
  441. for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), pattern); it != std::sregex_iterator ();
  442. ++it) {
  443. const std::string name = (*it)[1].str ();
  444. const auto found = onlyFloat.find (name);
  445. if (found == onlyFloat.end () || !found->second) {
  446. continue;
  447. }
  448. const size_t nameStart = it->position (1);
  449. const size_t nameEnd = nameStart + name.size ();
  450. if (ternary) {
  451. size_t before = nameStart;
  452. while (before > 0 && std::isspace (static_cast<unsigned char> (source[before - 1]))) {
  453. before--;
  454. }
  455. if (before == 0) {
  456. continue;
  457. }
  458. // only where the float is the whole condition (or a whole && / || operand), not e.g. `x == f ? ..`
  459. const char prev = source[before - 1];
  460. const char beforePrev = before > 1 ? source[before - 2] : ' ';
  461. const bool assignment = prev == '=' && std::string ("=!<>").find (beforePrev) == std::string::npos;
  462. if (!assignment && prev != '(' && prev != ',' && prev != '&' && prev != '|') {
  463. continue;
  464. }
  465. }
  466. result.append (source, last, nameStart - last);
  467. result += "(" + name + " != 0.0)";
  468. last = nameEnd;
  469. changed = true;
  470. }
  471. result.append (source, last, std::string::npos);
  472. source = result;
  473. };
  474. rewrite (ternaryCond, true);
  475. rewrite (ifCond, false);
  476. if (changed) {
  477. sLog.out ("Applied float condition compatibility in shader ", this->m_file);
  478. }
  479. return source;
  480. }
  481. std::string ShaderUnit::applyLinkedVaryingCompatibility (std::string source) const {
  482. if (this->m_type != GLSLContext::UnitType_Vertex || this->m_link == nullptr) {
  483. return source;
  484. }
  485. std::regex fragmentVec4Varying (R"(\bvarying\s+vec4\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
  486. std::smatch varyingMatch;
  487. std::string linked = this->m_link->m_preprocessed;
  488. size_t linkedOffset = 0;
  489. while (std::regex_search (linked.cbegin () + linkedOffset, linked.cend (), varyingMatch, fragmentVec4Varying)) {
  490. const std::string name = varyingMatch[1].str ();
  491. linkedOffset += varyingMatch.position () + varyingMatch.length ();
  492. const std::regex vertexVec2Decl ("\\bvarying\\s+vec2\\s+" + name + "\\s*;");
  493. if (!std::regex_search (source, vertexVec2Decl)) {
  494. continue;
  495. }
  496. source = std::regex_replace (source, vertexVec2Decl, "varying vec4 " + name + ";");
  497. const std::regex assignment ("(^|\\n)([ \\t]*)" + name + "\\s*=\\s*([^;\\n]+);");
  498. std::smatch assignmentMatch;
  499. size_t offset = 0;
  500. while (std::regex_search (source.cbegin () + offset, source.cend (), assignmentMatch, assignment)) {
  501. const std::string prefix = assignmentMatch[1].str ();
  502. const std::string indent = assignmentMatch[2].str ();
  503. const std::string expression = assignmentMatch[3].str ();
  504. const std::string replacement = prefix + indent + name + " = vec4(" + expression + ", 0.0, 1.0);";
  505. const size_t position = offset + assignmentMatch.position ();
  506. source.replace (position, assignmentMatch.length (), replacement);
  507. offset = position + replacement.length ();
  508. }
  509. }
  510. return source;
  511. }
  512. std::string ShaderUnit::applyFragmentTexCoordCompatibility (std::string source) const {
  513. if (this->m_type != GLSLContext::UnitType_Fragment) {
  514. return source;
  515. }
  516. const std::regex texCoordBeforeCast2 (R"(\bv_TexCoord\b(\s*[-+*/]\s*CAST2\s*\())");
  517. const std::regex cast2BeforeTexCoord (R"((CAST2\s*\([^)]+\)\s*[-+*/]\s*)\bv_TexCoord\b)");
  518. const std::regex wideTexCoordDecl (R"(\bvarying\s+vec[34]\s+v_TexCoord\s*;)");
  519. if (!std::regex_search (source, wideTexCoordDecl)
  520. || (!std::regex_search (source, texCoordBeforeCast2) && !std::regex_search (source, cast2BeforeTexCoord))) {
  521. return source;
  522. }
  523. const std::string original = source;
  524. source = std::regex_replace (source, texCoordBeforeCast2, "v_TexCoord.xy$1");
  525. source = std::regex_replace (source, cast2BeforeTexCoord, "$1v_TexCoord.xy");
  526. if (source != original) {
  527. sLog.out ("Applied fragment TexCoord vec2 compatibility in ", this->m_file);
  528. }
  529. return source;
  530. }
  531. std::string ShaderUnit::applyFragmentVaryingShadowCompatibility (std::string source) const {
  532. if (this->m_type != GLSLContext::UnitType_Fragment) {
  533. return source;
  534. }
  535. static const std::regex varyingDecl (R"(\bvarying\s+(vec[234]|float)\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
  536. std::vector<std::pair<std::string, std::string>> shadowed;
  537. for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), varyingDecl); it != std::sregex_iterator ();
  538. ++it) {
  539. const std::string type = (*it)[1].str ();
  540. const std::string name = (*it)[2].str ();
  541. // only shadow varyings the shader actually reassigns - a plain read-only "in" is fine as-is,
  542. // and touching the declaration unnecessarily risks breaking a shader that works today
  543. // a typed local of the same name already shadows the varying, blank the write or the shadow local collides
  544. const std::regex localDecl ("\\b(?:vec[234]|float|int|bool)\\s+" + name + "\\b");
  545. const std::string withoutLocals = std::regex_replace (source, localDecl, " ");
  546. const std::regex assignmentUse (
  547. "\\b" + name + "\\b(?:\\.[xyzwrgba]+)?\\s*(?:=(?!=)|\\+=|-=|\\*=|/=)"
  548. );
  549. if (!std::regex_search (withoutLocals, assignmentUse)) {
  550. continue;
  551. }
  552. shadowed.emplace_back (type, name);
  553. }
  554. if (shadowed.empty ()) {
  555. return source;
  556. }
  557. static const std::regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
  558. std::smatch mainMatch;
  559. if (!std::regex_search (source, mainMatch, mainOpen)) {
  560. return source;
  561. }
  562. // shadows each with a same-named local, initialized from the real (read-only) input, so the
  563. // rest of main() can keep mutating it exactly like the original compatibility-profile shader did
  564. std::string shadowCode;
  565. for (const auto& [type, name] : shadowed) {
  566. shadowCode += " " + type + " wpeShadowIn_" + name + " = " + name + "; " + type + " " + name + " = wpeShadowIn_" + name + ";";
  567. }
  568. const size_t insertAt = mainMatch.position (0) + mainMatch.length (0);
  569. source.insert (insertAt, shadowCode);
  570. std::string names;
  571. for (const auto& [type, name] : shadowed) {
  572. names += (names.empty () ? "" : ", ") + name;
  573. }
  574. sLog.out ("Applied fragment varying shadow compatibility in ", this->m_file, " for ", names);
  575. return source;
  576. }
  577. std::string ShaderUnit::applyNonConstantConstCompatibility (std::string source) const {
  578. // locals only, globals sit at column 0
  579. static const std::regex constLocal (R"((^|\n)([ \t]+)const\s+([^;=]+=([^;]*);))");
  580. static const std::regex nonConstant (R"(\b(?:texSample2D\w*|texture\w*|g_\w+|v_\w+)\b)");
  581. std::string result;
  582. size_t count = 0;
  583. auto last = source.cbegin ();
  584. for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), constLocal); it != std::sregex_iterator ();
  585. ++it) {
  586. const auto& match = *it;
  587. if (!std::regex_search (match[4].first, match[4].second, nonConstant)) {
  588. continue;
  589. }
  590. result.append (last, match[0].first);
  591. result += match[1].str () + match[2].str () + match[3].str ();
  592. last = match[0].second;
  593. count++;
  594. }
  595. if (count == 0) {
  596. return source;
  597. }
  598. result.append (last, source.cend ());
  599. sLog.out ("Dropped const from ", count, " non-constant local(s) in ", this->m_file);
  600. return result;
  601. }
  602. void ShaderUnit::parseComboConfiguration (const std::string& content, const int defaultValue) {
  603. // TODO: SUPPORT REQUIRES SO WE PROPERLY FOLLOW THE REQUIRED CHAIN
  604. JSON data;
  605. try {
  606. data = JSON::parse (content);
  607. } catch (const std::exception& e) {
  608. sLog.error ("Cannot parse combo metadata in shader ", this->m_file, ": ", e.what ());
  609. return;
  610. }
  611. const auto combo = data.require<std::string> ("combo", "cannot parse combo information");
  612. // "type" is ignored - appears to be editor-only metadata
  613. const auto defvalue = data.find ("default");
  614. const auto entry = this->m_combos.find (combo);
  615. const auto entryOverride = this->m_overrideCombos.find (combo);
  616. this->m_usedCombos.emplace (combo, true);
  617. // not predefined anywhere -> fall back to the JSON's own default value
  618. if (entry == this->m_combos.end () && entryOverride == this->m_overrideCombos.end ()) {
  619. if (defvalue == data.end ()) {
  620. // TODO: PROPERLY SUPPORT EMPTY COMBOS
  621. this->m_discoveredCombos.emplace (combo, defaultValue);
  622. } else if (defvalue->is_number_float ()) {
  623. sLog.exception ("float combos are not supported in shader ", this->m_file, ". ", combo);
  624. } else if (defvalue->is_number_integer ()) {
  625. this->m_discoveredCombos.emplace (combo, defvalue->get<int> ());
  626. } else if (defvalue->is_string ()) {
  627. sLog.exception ("string combos are not supported in shader ", this->m_file, ". ", combo);
  628. } else {
  629. sLog.exception ("cannot parse combo information ", combo, ". unknown type for ", defvalue->dump ());
  630. }
  631. }
  632. }
  633. void ShaderUnit::parseParameterConfiguration (
  634. const std::string& type, const std::string& name, const std::string& content
  635. ) {
  636. JSON data;
  637. try {
  638. data = JSON::parse (content);
  639. } catch (const std::exception& e) {
  640. sLog.error ("Cannot parse parameter metadata for ", name, " in shader ", this->m_file, ": ", e.what ());
  641. return;
  642. }
  643. const auto material = data.optional ("material");
  644. const auto defvalue = data.optional ("default");
  645. const auto combo = data.find ("combo");
  646. auto constant = this->m_constants.end ();
  647. if (material.has_value ()) {
  648. constant = this->m_constants.find (*material);
  649. }
  650. if (constant == this->m_constants.end () && !defvalue.has_value ()) {
  651. if (type != "sampler2D") {
  652. sLog.exception ("Cannot parse parameter data for ", name, " in shader ", this->m_file);
  653. }
  654. }
  655. Variables::ShaderVariable* parameter = nullptr;
  656. if (type == "vec4") {
  657. parameter
  658. = new Variables::ShaderVariableVector4 (VectorBuilder::parse<glm::vec4> (defvalue->get<std::string> ()));
  659. } else if (type == "vec3") {
  660. parameter = new Variables::ShaderVariableVector3 (VectorBuilder::parse<glm::vec3> (*defvalue));
  661. } else if (type == "vec2") {
  662. parameter = new Variables::ShaderVariableVector2 (VectorBuilder::parse<glm::vec2> (*defvalue));
  663. } else if (type == "float") {
  664. if (defvalue->is_string ()) {
  665. parameter = new Variables::ShaderVariableFloat (std::stoi (defvalue->get<std::string> ()));
  666. } else {
  667. parameter = new Variables::ShaderVariableFloat (defvalue->get<float> ());
  668. }
  669. } else if (type == "int") {
  670. if (defvalue->is_string ()) {
  671. parameter = new Variables::ShaderVariableInteger (std::stoi (defvalue->get<std::string> ()));
  672. } else {
  673. parameter = new Variables::ShaderVariableInteger (defvalue->get<int> ());
  674. }
  675. } else if (type == "sampler2D" || type == "sampler2DComparison") {
  676. const auto textureName = data.find ("default");
  677. // TODO: CREATE TEXTURE WITH THE GIVEN COLOR
  678. const auto requireany = data.find ("requireany");
  679. const auto require = data.find ("require");
  680. constexpr std::string_view prefix = "g_Texture";
  681. size_t index = 0;
  682. const char* digits = name.data () + std::min (name.size (), prefix.size ());
  683. const char* nameEnd = name.data () + name.size ();
  684. if (!name.starts_with (prefix) || std::from_chars (digits, nameEnd, index).ptr != nameEnd) {
  685. sLog.error ("Cannot determine texture slot for ", name, " in shader ", this->m_file);
  686. return;
  687. }
  688. // TODO: SUPPORT USER TEXTURES!!
  689. if (combo != data.end ()) {
  690. // TODO: CLEANUP HOW THIS IS DETERMINED FIRST
  691. const auto textureSlotUsed
  692. = this->m_passTextures.contains (index) || this->m_overrideTextures.contains (index);
  693. bool isRequired = false;
  694. int comboValue = 1;
  695. if (textureSlotUsed) {
  696. // texture already exists, so the combo must be set; these tend to have no default value
  697. isRequired = true;
  698. } else if (require != data.end ()) {
  699. if (requireany != data.end () && requireany->get<bool> ()) {
  700. // requireany: any one mismatching value makes this required (OR semantics)
  701. for (const auto& item : require->items ()) {
  702. const std::string& macro = item.key ();
  703. const auto it = this->m_combos.find (macro);
  704. if (it == this->m_combos.end () || this->m_overrideCombos.contains (macro)
  705. || it->second != item.value ()) {
  706. isRequired = true;
  707. break;
  708. }
  709. }
  710. } else {
  711. isRequired = true;
  712. // require without requireany: every listed value must match (AND semantics)
  713. for (const auto& item : require->items ()) {
  714. const std::string& macro = item.key ();
  715. const auto it = this->m_combos.find (macro);
  716. // a missing macro is fine here, only the value comparison matters
  717. if ((it != this->m_combos.end () || this->m_overrideCombos.contains (macro))
  718. && it->second == item.value ()) {
  719. isRequired = false;
  720. break;
  721. }
  722. }
  723. }
  724. }
  725. if (isRequired && !textureSlotUsed) {
  726. if (!defvalue.has_value ()) {
  727. isRequired = false;
  728. } else {
  729. if (this->m_combos.contains (*combo) || this->m_overrideCombos.contains (*combo)) {
  730. isRequired = false;
  731. } else if (defvalue->is_string ()) {
  732. comboValue = std::stoi (defvalue->get<std::string> ().c_str ());
  733. } else if (defvalue->is_number ()) {
  734. comboValue = *defvalue;
  735. } else {
  736. sLog.exception (
  737. "Cannot determine default value for combo ", combo->get<std::string> (),
  738. " because it's not specified by the shader and is not given a default value: ", this->m_file
  739. );
  740. }
  741. }
  742. }
  743. if (isRequired) {
  744. this->m_discoveredCombos.emplace (*combo, comboValue);
  745. this->m_usedCombos.emplace (*combo, true);
  746. }
  747. }
  748. // Some shaders (e.g. effects/refract.frag's normal map) declare `"default":""` on purpose -
  749. // an explicitly empty default means "no texture unless the object's own effect config
  750. // supplies one", not "a texture literally named the empty string". Registering it anyway
  751. // sent every such object into a doomed asset lookup for a blank path on every use of that
  752. // shader, whether or not the combo gating it was even active.
  753. if (textureName != data.end () && !textureName->get<std::string> ().empty ()) {
  754. this->m_defaultTextures.emplace (index, *textureName);
  755. }
  756. return;
  757. } else {
  758. sLog.error ("Unknown parameter type: ", type, " for ", name, " in shader ", this->m_file);
  759. return;
  760. }
  761. if (material.has_value () && parameter != nullptr) {
  762. parameter->setIdentifierName (*material);
  763. parameter->setName (name);
  764. this->m_parameters.push_back (parameter);
  765. }
  766. }
  767. const ComboMap& ShaderUnit::getCombos () const { return this->m_combos; }
  768. const ComboMap& ShaderUnit::getDiscoveredCombos () const { return this->m_discoveredCombos; }
  769. void ShaderUnit::linkToUnit (const ShaderUnit* unit) { this->m_link = unit; }
  770. const ShaderUnit* ShaderUnit::getLinkedUnit () const { return this->m_link; }
  771. const std::string& ShaderUnit::compile () {
  772. if (!this->m_final.empty ()) {
  773. return this->m_final;
  774. }
  775. this->m_final = SHADER_HEADER (this->m_file);
  776. // GLSL has no builtin log10 (unlike HLSL), so some shaders provide their own under "#if GLSL"
  777. // (which is always true here). Adding a blanket compatibility macro would get expanded right
  778. // over such a shader's own function definition and mangle it, so only add it when the shader
  779. // doesn't already define log10 itself.
  780. static const std::regex log10Definition (
  781. R"(\b(?:void|float|int|uint|bool|vec[234]|ivec[234]|uvec[234]|bvec[234]|mat[234](?:x[234])?)\s+log10\s*\()"
  782. );
  783. // memoized per source, compile() runs again for every pass a text layer rebuilds
  784. static std::mutex cacheMutex;
  785. static std::unordered_map<std::string, bool> definesLog10;
  786. static std::unordered_map<std::string, std::string> compatCache;
  787. bool hasLog10 = false;
  788. {
  789. std::lock_guard lock (cacheMutex);
  790. auto found = definesLog10.find (this->m_content);
  791. if (found == definesLog10.end ()) {
  792. found = definesLog10.emplace (this->m_content, std::regex_search (this->m_content, log10Definition)).first;
  793. }
  794. hasLog10 = found->second;
  795. }
  796. if (!hasLog10) {
  797. this->m_final += "#define log10(x) (log2(x) * 0.301029995663981)\n";
  798. }
  799. if (this->m_type == GLSLContext::UnitType_Fragment) {
  800. this->m_final += FRAGMENT_SHADER_DEFINES;
  801. } else {
  802. this->m_final += VERTEX_SHADER_DEFINES;
  803. }
  804. std::map<std::string, bool> addedCombos;
  805. for (const auto& [name, value] : this->m_overrideCombos) {
  806. std::string uppercase;
  807. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  808. if (!addedCombos.contains (uppercase)) {
  809. this->m_final += DEFINE_COMBO (uppercase, value);
  810. addedCombos.emplace (uppercase, true);
  811. }
  812. }
  813. for (const auto& [name, value] : this->m_combos) {
  814. std::string uppercase;
  815. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  816. if (!addedCombos.contains (uppercase)) {
  817. this->m_final += DEFINE_COMBO (uppercase, value);
  818. addedCombos.emplace (uppercase, true);
  819. }
  820. }
  821. for (const auto& [name, value] : this->m_discoveredCombos) {
  822. std::string uppercase;
  823. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  824. if (!addedCombos.contains (uppercase)) {
  825. this->m_final += DEFINE_COMBO (uppercase, value);
  826. addedCombos.emplace (uppercase, true);
  827. }
  828. }
  829. if (this->m_link != nullptr) {
  830. for (const auto& [name, value] : this->m_link->getCombos ()) {
  831. std::string uppercase;
  832. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  833. if (!addedCombos.contains (uppercase)) {
  834. this->m_final += DEFINE_COMBO (uppercase, value);
  835. addedCombos.emplace (uppercase, true);
  836. }
  837. }
  838. for (const auto& [name, value] : this->m_link->getDiscoveredCombos ()) {
  839. std::string uppercase;
  840. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  841. if (!addedCombos.contains (uppercase)) {
  842. this->m_final += DEFINE_COMBO (uppercase, value);
  843. addedCombos.emplace (uppercase, true);
  844. }
  845. }
  846. }
  847. // the header above already encodes the unit type and every define, so it works as the key
  848. std::string cacheKey = this->m_final;
  849. cacheKey += '\x1f';
  850. cacheKey += this->m_preprocessed;
  851. cacheKey += '\x1f';
  852. if (this->m_link != nullptr) {
  853. cacheKey += this->m_link->m_preprocessed;
  854. }
  855. for (const auto& [name, value] : this->m_combos) {
  856. cacheKey += '\x1f';
  857. cacheKey += name;
  858. cacheKey += '=';
  859. cacheKey += std::to_string (value);
  860. }
  861. {
  862. std::lock_guard lock (cacheMutex);
  863. if (const auto cached = compatCache.find (cacheKey); cached != compatCache.end ()) {
  864. this->m_final += cached->second;
  865. return this->m_final;
  866. }
  867. }
  868. const std::string compat = this->applyNonConstantConstCompatibility (this->applyFloatConditionCompatibility (
  869. this->applyVectorTruncationCompatibility (this->applyFragmentVaryingShadowCompatibility (
  870. this->applyFragmentTexCoordCompatibility (this->applyLinkedVaryingCompatibility (this->m_preprocessed))
  871. ))
  872. ));
  873. {
  874. std::lock_guard lock (cacheMutex);
  875. compatCache.emplace (std::move (cacheKey), compat);
  876. }
  877. this->m_final += compat;
  878. // actual GLSL compilation happens in the pass, which has the context this unit doesn't
  879. return this->m_final;
  880. }
  881. const std::vector<Variables::ShaderVariable*>& ShaderUnit::getParameters () const { return this->m_parameters; }
  882. const TextureMap& ShaderUnit::getTextures () const { return this->m_defaultTextures; }