compiler.cpp 19 KB

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