compiler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. #include <irrlicht/irrlicht.h>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. // filesystem
  6. #include <wallpaperengine/fs/utils.h>
  7. // video engine
  8. #include <wallpaperengine/irrlicht.h>
  9. // shader compiler
  10. #include <wallpaperengine/shaders/compiler.h>
  11. #include <wallpaperengine/core.h>
  12. namespace wp
  13. {
  14. namespace shaders
  15. {
  16. compiler::compiler (irr::io::path& file, Type type, std::map<std::string, int>* combos, bool recursive)
  17. {
  18. this->m_recursive = recursive;
  19. this->m_combos = combos;
  20. // begin with an space so it gets ignored properly on parse
  21. if (recursive == false)
  22. {
  23. // compatibility layer for OpenGL shaders
  24. this->m_content = "#version 120\n"
  25. "#define highp\n"
  26. "#define mediump\n"
  27. "#define lowp\n"
  28. "#define mul(x, y) (y * x)\n"
  29. "#define frac fract\n"
  30. "#define CAST2(x) (vec2(x))\n"
  31. "#define CAST3(x) (vec3(x))\n"
  32. "#define CAST4(x) (vec4(x))\n"
  33. "#define CAST3X3(x) (mat3(x))\n"
  34. "#define saturate(x) (clamp(x, 0.0, 1.0))\n"
  35. "#define texSample2D texture2D\n"
  36. "#define texSample2DLod texture2DLod\n"
  37. "#define texture2DLod texture2D\n"
  38. "#define atan2 atan\n"
  39. "#define ddx dFdx\n"
  40. "#define ddy(x) dFdy(-(x))\n"
  41. "#define GLSL 1\n\n";
  42. std::map<std::string, int>::const_iterator cur = this->m_combos->begin ();
  43. std::map<std::string, int>::const_iterator end = this->m_combos->end ();
  44. for (; cur != end; cur ++)
  45. {
  46. this->m_content += "#define " + (*cur).first + " " + std::to_string ((*cur).second) + "\n";
  47. }
  48. }
  49. else
  50. {
  51. this->m_content = "";
  52. }
  53. this->m_content.append (wp::fs::utils::loadFullFile (file));
  54. // append file content
  55. this->m_type = type;
  56. this->m_file = file;
  57. }
  58. bool compiler::peekString(std::string str, std::string::const_iterator& it)
  59. {
  60. std::string::const_iterator check = str.begin();
  61. std::string::const_iterator cur = it;
  62. while (cur != this->m_content.end () && check != str.end ())
  63. {
  64. if (*cur != *check) return false;
  65. cur ++; check ++;
  66. }
  67. if (cur == this->m_content.end ())
  68. {
  69. return false;
  70. }
  71. if (check != str.end ())
  72. {
  73. return false;
  74. }
  75. it = cur;
  76. return true;
  77. }
  78. bool compiler::expectSemicolon (std::string::const_iterator& it)
  79. {
  80. if (*it != ';')
  81. {
  82. this->m_error = true;
  83. this->m_errorInfo = "Expected semicolon but got " + *it;
  84. return false;
  85. }
  86. it ++;
  87. return true;
  88. }
  89. void compiler::ignoreSpaces(std::string::const_iterator &it)
  90. {
  91. while (it != this->m_content.end() && (*it == ' ' || *it == '\t')) it ++;
  92. }
  93. void compiler::ignoreUpToNextLineFeed (std::string::const_iterator& it)
  94. {
  95. while (it != this->m_content.end() && *it != '\n') it ++;
  96. }
  97. void compiler::ignoreUpToBlockCommentEnd (std::string::const_iterator& it)
  98. {
  99. while (it != this->m_content.end() && this->peekString ("*/", it) == false) it ++;
  100. }
  101. std::string compiler::extractType (std::string::const_iterator& it)
  102. {
  103. std::vector<std::string>::const_iterator cur = sTypes.begin ();
  104. std::vector<std::string>::const_iterator end = sTypes.end ();
  105. while (cur != end)
  106. {
  107. if (this->peekString (*cur, it) == true)
  108. {
  109. return *cur;
  110. }
  111. cur ++;
  112. }
  113. this->m_error = true;
  114. this->m_errorInfo = "Expected type";
  115. return "";
  116. }
  117. std::string compiler::extractName (std::string::const_iterator& it)
  118. {
  119. std::string::const_iterator cur = it;
  120. std::string::const_iterator begin = cur;
  121. // first character has to be a valid alphabetic characer
  122. if (this->isChar (cur) == false && *cur != '_')
  123. {
  124. this->m_error = true;
  125. this->m_errorInfo = "Expected name doesn't start with a valid character";
  126. return "";
  127. }
  128. cur ++;
  129. while (cur != this->m_content.end () && (this->isChar (cur) == true || *cur == '_' || this->isNumeric (cur) == true)) cur ++;
  130. it = cur;
  131. return std::string (begin, cur);
  132. }
  133. bool compiler::isChar (std::string::const_iterator& it)
  134. {
  135. return ((*it) >= 'A' && (*it) <= 'Z') || ((*it) >= 'a' && (*it) <= 'z');
  136. }
  137. bool compiler::isNumeric (std::string::const_iterator& it)
  138. {
  139. return (*it) >= '0' && (*it) <= '9';
  140. }
  141. std::string compiler::extractQuotedValue(std::string::const_iterator& it)
  142. {
  143. std::string::const_iterator cur = it;
  144. if (*cur != '"')
  145. {
  146. m_error = true;
  147. m_errorInfo = "Expected opening \" but got " + (*cur);
  148. return "";
  149. }
  150. cur ++;
  151. while (cur != this->m_content.end () && *cur != '\n' && *cur != '"') cur ++;
  152. if (cur == this->m_content.end ())
  153. {
  154. m_error = true;
  155. m_errorInfo = "Expected closing \" not found";
  156. it = cur;
  157. return "";
  158. }
  159. std::string filename = std::string (++it, cur);
  160. it = ++cur;
  161. return filename;
  162. }
  163. std::string compiler::lookupShaderFile (std::string filename)
  164. {
  165. // get file information
  166. irr::io::path shader = ("shaders/" + filename).c_str ();
  167. if (shader == "")
  168. {
  169. this->m_error = true;
  170. this->m_errorInfo = "Cannot find file " + filename + " to include";
  171. return "";
  172. }
  173. // now compile the new shader
  174. // do not include the default header (as it's already included in the parent)
  175. compiler loader (shader, this->m_type, this->m_combos, true);
  176. return loader.precompile ();
  177. }
  178. std::string compiler::lookupReplaceSymbol (std::string symbol)
  179. {
  180. std::map<std::string, std::string>::const_iterator cur = sVariableReplacement.begin ();
  181. std::map<std::string, std::string>::const_iterator end = sVariableReplacement.end ();
  182. while (cur != end)
  183. {
  184. if (cur->first == symbol)
  185. {
  186. return cur->second;
  187. }
  188. cur ++;
  189. }
  190. // if there is no replacement, return the original
  191. return symbol;
  192. }
  193. std::string compiler::precompile()
  194. {
  195. #define BREAK_IF_ERROR if (this->m_error == true) { wp::irrlicht::device->getLogger ()->log ("ERROR PRE-COMPILING SHADER", irr::ELL_ERROR); wp::irrlicht::device->getLogger ()->log (this->m_errorInfo.c_str (), irr::ELL_ERROR); return ""; }
  196. // parse the shader and find #includes and such things and translate them to the correct name
  197. // also remove any #version definition to prevent errors
  198. std::string::const_iterator it = this->m_content.begin ();
  199. // reset error indicator
  200. this->m_error = false;
  201. this->m_errorInfo = "";
  202. // search preprocessor macros and parse them
  203. while (it != this->m_content.end () && this->m_error == false)
  204. {
  205. if (*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r' || *it == '\0' || *it == '{' || *it == '}' || *it == '[' || *it == ']' || *it == '.')
  206. {
  207. this->m_compiledContent += *it;
  208. it ++;
  209. }
  210. else if (*it == '#')
  211. {
  212. if (this->peekString ("#include", it) == true)
  213. {
  214. std::string filename = "";
  215. // ignore whitespaces
  216. this->ignoreSpaces (it); BREAK_IF_ERROR
  217. // extract value between quotes
  218. filename = this->extractQuotedValue (it); BREAK_IF_ERROR
  219. // try to find the file first
  220. this->m_compiledContent += "// begin of included from file " + filename + "\r\n";
  221. this->m_compiledContent += this->lookupShaderFile (filename);
  222. this->m_compiledContent += "\r\n// end of included from file " + filename + "\r\n";
  223. }
  224. else
  225. {
  226. this->m_compiledContent += '#';
  227. it ++;
  228. }
  229. }
  230. else if (*it == 'u')
  231. {
  232. // uniforms might have extra information for their values
  233. if (this->peekString ("uniform", it) == true)
  234. {
  235. this->ignoreSpaces (it);
  236. std::string type = this->extractType (it); BREAK_IF_ERROR
  237. this->ignoreSpaces (it);
  238. std::string name = this->extractName (it); BREAK_IF_ERROR
  239. this->ignoreSpaces (it);
  240. this->expectSemicolon (it); BREAK_IF_ERROR
  241. this->ignoreSpaces (it);
  242. // check if there is any actual extra information and parse it
  243. if (this->peekString ("//", it) == true)
  244. {
  245. this->ignoreSpaces (it);
  246. std::string::const_iterator begin = it;
  247. this->ignoreUpToNextLineFeed (it);
  248. std::string configuration; configuration.append (begin, it);
  249. // parse the parameter information
  250. this->parseParameterConfiguration (type, name, configuration); BREAK_IF_ERROR
  251. this->m_compiledContent += "uniform " + type + " " + name + "; // " + configuration;
  252. }
  253. else
  254. {
  255. this->m_compiledContent += "uniform " + type + " " + name + ";";
  256. }
  257. }
  258. }
  259. else if (*it == 'a')
  260. {
  261. // find attribute definitions
  262. if (this->peekString ("attribute", it) == true)
  263. {
  264. this->ignoreSpaces (it);
  265. std::string type = this->extractType (it); BREAK_IF_ERROR
  266. this->ignoreSpaces (it);
  267. std::string name = this->extractName (it); BREAK_IF_ERROR
  268. this->ignoreSpaces (it);
  269. this->expectSemicolon (it); BREAK_IF_ERROR
  270. this->m_compiledContent += "// attribute";
  271. this->m_compiledContent += " " + type + " ";
  272. this->m_compiledContent += name;
  273. this->m_compiledContent += "; /* replaced by " + this->lookupReplaceSymbol (name) + " */";
  274. }
  275. else
  276. {
  277. // check for types first
  278. std::string type = this->extractType (it);
  279. // types not found, try names
  280. if (this->m_error == false)
  281. {
  282. this->m_compiledContent += type;
  283. }
  284. else
  285. {
  286. this->m_error = false;
  287. std::string name = this->extractName (it);
  288. if (this->m_error == false)
  289. {
  290. // check if the name is a translated one or not
  291. this->m_compiledContent += this->lookupReplaceSymbol (name);
  292. }
  293. else
  294. {
  295. this->m_error = false;
  296. this->m_compiledContent += *it;
  297. it ++;
  298. }
  299. }
  300. }
  301. }
  302. else if (*it == '/')
  303. {
  304. if (this->peekString ("//", it) == true)
  305. {
  306. std::string::const_iterator begin = it - 2;
  307. // is there a COMBO mark to take care of?
  308. this->ignoreSpaces (it);
  309. if (this->peekString ("[COMBO]", it) == true)
  310. {
  311. // parse combo json data to define the proper variables
  312. this->ignoreSpaces (it);
  313. begin = it;
  314. this->ignoreUpToNextLineFeed (it);
  315. std::string configuration; configuration.append (begin, it);
  316. this->m_compiledContent += "// [COMBO] " + configuration;
  317. this->parseComboConfiguration (configuration); BREAK_IF_ERROR;
  318. }
  319. else if (this->peekString ("[COMBO_OFF]", it) == true)
  320. {
  321. // parse combo json data to define the proper variables
  322. this->ignoreSpaces (it);
  323. begin = it;
  324. this->ignoreUpToNextLineFeed (it);
  325. std::string configuration; configuration.append (begin, it);
  326. this->m_compiledContent += "// [COMBO_OFF] " + configuration;
  327. this->parseComboConfiguration (configuration); BREAK_IF_ERROR;
  328. }
  329. else
  330. {
  331. this->ignoreUpToNextLineFeed (it);
  332. this->m_compiledContent.append (begin, it);
  333. }
  334. }
  335. else if (this->peekString ("/*", it) == true)
  336. {
  337. std::string::const_iterator begin = it - 2;
  338. this->ignoreUpToBlockCommentEnd (it);
  339. this->m_compiledContent.append (begin, it);
  340. }
  341. else
  342. {
  343. this->m_compiledContent += *it;
  344. it ++;
  345. }
  346. }
  347. else
  348. {
  349. // check for types first
  350. std::string type = this->extractType (it);
  351. // types not found, try names
  352. if (this->m_error == false)
  353. {
  354. this->m_compiledContent += type;
  355. }
  356. else
  357. {
  358. this->m_error = false;
  359. std::string name = this->extractName (it);
  360. if (this->m_error == false)
  361. {
  362. // check if the name is a translated one or not
  363. this->m_compiledContent += this->lookupReplaceSymbol (name);
  364. }
  365. else
  366. {
  367. this->m_error = false;
  368. this->m_compiledContent += *it;
  369. it ++;
  370. }
  371. }
  372. }
  373. }
  374. if (this->m_recursive == false)
  375. {
  376. wp::irrlicht::device->getLogger ()->log ("Compiled shader output for", this->m_file.c_str ());
  377. wp::irrlicht::device->getLogger ()->log (this->m_compiledContent.c_str ());
  378. }
  379. return this->m_compiledContent;
  380. #undef BREAK_IF_ERROR
  381. }
  382. void compiler::parseComboConfiguration (const std::string& content)
  383. {
  384. json data = json::parse (content);
  385. json::const_iterator combo = data.find ("combo");
  386. json::const_iterator defvalue = data.find ("default");
  387. // add line feed just in case
  388. this->m_compiledContent += "\n";
  389. if (combo == data.end () || defvalue == data.end ())
  390. {
  391. wp::irrlicht::device->getLogger ()->log ("Cannot parse combo information", irr::ELL_ERROR);
  392. return;
  393. }
  394. // check the combos
  395. std::map<std::string, int>::const_iterator entry = this->m_combos->find ((*combo).get <std::string> ());
  396. // if the combo was not found in the predefined values this means that the default value in the JSON data can be used
  397. // so only define the ones that are not already defined
  398. if (entry == this->m_combos->end ())
  399. {
  400. // if no combo is defined just load the default settings
  401. if ((*defvalue).is_number_float ())
  402. {
  403. this->m_compiledContent += "#define " + (*combo).get <std::string> () + " " + std::to_string ((*defvalue).get <irr::f32> ()) + "\n";
  404. }
  405. else if ((*defvalue).is_number_integer ())
  406. {
  407. this->m_compiledContent += "#define " + (*combo).get <std::string> () + " " + std::to_string ((*defvalue).get <irr::s32> ()) + "\n";
  408. }
  409. else if ((*defvalue).is_string ())
  410. {
  411. this->m_compiledContent += "#define " + (*combo).get <std::string> () + " " + (*defvalue).get <std::string> () + "\n";
  412. }
  413. else
  414. {
  415. wp::irrlicht::device->getLogger ()->log ("Cannot parse combo information, unknown type", irr::ELL_ERROR);
  416. }
  417. }
  418. }
  419. void compiler::parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content)
  420. {
  421. json data = json::parse (content);
  422. json::const_iterator material = data.find ("material");
  423. json::const_iterator defvalue = data.find ("default");
  424. json::const_iterator range = data.find ("range");
  425. // this is not a real parameter
  426. if (material == data.end () || defvalue == data.end ())
  427. {
  428. if (type != "sampler2D")
  429. wp::irrlicht::device->getLogger ()->log ("Cannot parse parameter info for ", name.c_str (), irr::ELL_ERROR);
  430. return;
  431. }
  432. ShaderParameter* param = new ShaderParameter;
  433. param->identifierName = (*material).get <std::string> ();
  434. param->variableName = name;
  435. param->type = type;
  436. if (type == "vec4" || type == "vec3")
  437. {
  438. if ((*defvalue).is_string () == false)
  439. {
  440. irr::core::vector3df* vector = new irr::core::vector3df;
  441. vector->X = 0.0f;
  442. vector->Y = 0.0f;
  443. vector->Z = 0.0f;
  444. param->defaultValue = vector;
  445. }
  446. else
  447. {
  448. irr::core::vector3df tmp = wp::core::ato3vf ((*defvalue).get <std::string> ().c_str ());
  449. irr::core::vector3df* vector = new irr::core::vector3df;
  450. vector->X = tmp.X;
  451. vector->Y = tmp.Y;
  452. vector->Z = tmp.Z;
  453. param->defaultValue = vector;
  454. }
  455. }
  456. else if (type == "vec2")
  457. {
  458. if ((*defvalue).is_string () == false)
  459. {
  460. irr::core::vector2df* vector = new irr::core::vector2df;
  461. vector->X = 0.0f;
  462. vector->Y = 0.0f;
  463. param->defaultValue = vector;
  464. }
  465. else
  466. {
  467. irr::core::vector2df* vector = new irr::core::vector2df;
  468. irr::core::vector2df tmp = wp::core::ato2vf ((*defvalue).get <std::string> ().c_str ());
  469. vector->X = tmp.X;
  470. vector->Y = tmp.Y;
  471. param->defaultValue = vector;
  472. }
  473. }
  474. else if (type == "float")
  475. {
  476. if ((*defvalue).is_number () == false)
  477. {
  478. irr::f32* val = new irr::f32;
  479. *val = 0.0f;
  480. param->defaultValue = val;
  481. }
  482. else
  483. {
  484. irr::f32* val = new irr::f32;
  485. *val = (*defvalue).get <irr::f32> ();
  486. param->defaultValue = val;
  487. }
  488. }
  489. else if (type == "sampler2D")
  490. {
  491. // samplers are not saved, we can ignore them for now
  492. delete param;
  493. return;
  494. }
  495. else
  496. {
  497. this->m_error = true;
  498. this->m_errorInfo = "Unknown parameter type: " + type + " for " + param->identifierName + " (" + param->variableName + ")";
  499. return;
  500. }
  501. this->m_parameters.push_back (param);
  502. }
  503. compiler::ShaderParameter* compiler::findParameter (std::string identifier)
  504. {
  505. std::vector<ShaderParameter*>::const_iterator cur = this->m_parameters.begin ();
  506. std::vector<ShaderParameter*>::const_iterator end = this->m_parameters.end ();
  507. for (; cur != end; cur ++)
  508. {
  509. if ((*cur)->identifierName == identifier)
  510. {
  511. return (*cur);
  512. }
  513. }
  514. return nullptr;
  515. }
  516. std::vector <compiler::ShaderParameter*>& compiler::getParameters ()
  517. {
  518. return this->m_parameters;
  519. }
  520. std::map<std::string, std::string> compiler::sVariableReplacement =
  521. {
  522. // attribute vec3 a_position
  523. {"a_Position", "gl_Vertex.xyz"},
  524. // attribute vec2 a_TexCoord
  525. {"a_TexCoord", "gl_MultiTexCoord0.xy"},
  526. // attribute vec3 a_Normal
  527. {"a_Normal", "gl_Normal.xyz"}
  528. };
  529. std::vector<std::string> compiler::sTypes =
  530. {
  531. "vec4", "vec3", "vec2", "float", "sampler2D", "mat4"
  532. };
  533. }
  534. }