shaderc.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #include "shaderc.h"
  6. bool g_verbose = false;
  7. #define MAX_TAGS 256
  8. extern "C"
  9. {
  10. #include <fpp.h>
  11. } // extern "C"
  12. #define BGFX_CHUNK_MAGIC_CSH BX_MAKEFOURCC('C', 'S', 'H', 0x1)
  13. #define BGFX_CHUNK_MAGIC_FSH BX_MAKEFOURCC('F', 'S', 'H', 0x3)
  14. #define BGFX_CHUNK_MAGIC_VSH BX_MAKEFOURCC('V', 'S', 'H', 0x3)
  15. long int fsize(FILE* _file)
  16. {
  17. long int pos = ftell(_file);
  18. fseek(_file, 0L, SEEK_END);
  19. long int size = ftell(_file);
  20. fseek(_file, pos, SEEK_SET);
  21. return size;
  22. }
  23. static const char* s_ARB_shader_texture_lod[] =
  24. {
  25. "texture2DLod",
  26. "texture2DProjLod",
  27. "texture3DLod",
  28. "texture3DProjLod",
  29. "textureCubeLod",
  30. "shadow2DLod",
  31. "shadow2DProjLod",
  32. NULL
  33. // "texture1DLod",
  34. // "texture1DProjLod",
  35. // "shadow1DLod",
  36. // "shadow1DProjLod",
  37. };
  38. static const char* s_EXT_shadow_samplers[] =
  39. {
  40. "shadow2D",
  41. "shadow2DProj",
  42. "sampler2DShadow",
  43. NULL
  44. };
  45. static const char* s_OES_standard_derivatives[] =
  46. {
  47. "dFdx",
  48. "dFdy",
  49. "fwidth",
  50. NULL
  51. };
  52. static const char* s_OES_texture_3D[] =
  53. {
  54. "texture3D",
  55. "texture3DProj",
  56. "texture3DLod",
  57. "texture3DProjLod",
  58. NULL
  59. };
  60. const char* s_uniformTypeName[UniformType::Count] =
  61. {
  62. "int",
  63. "float",
  64. NULL,
  65. "int",
  66. "float",
  67. "vec2",
  68. "vec3",
  69. "vec4",
  70. "mat3",
  71. "mat4",
  72. };
  73. const char* interpolationDx11(const char* _glsl)
  74. {
  75. if (0 == strcmp(_glsl, "smooth") )
  76. {
  77. return "linear";
  78. }
  79. else if (0 == strcmp(_glsl, "flat") )
  80. {
  81. return "nointerpolation";
  82. }
  83. return _glsl; // noperspective
  84. }
  85. const char* getUniformTypeName(UniformType::Enum _enum)
  86. {
  87. return s_uniformTypeName[_enum];
  88. }
  89. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  90. {
  91. for (uint32_t ii = 0; ii < UniformType::Count; ++ii)
  92. {
  93. if (NULL != s_uniformTypeName[ii]
  94. && 0 == strcmp(_name, s_uniformTypeName[ii]) )
  95. {
  96. return UniformType::Enum(ii);
  97. }
  98. }
  99. return UniformType::Count;
  100. }
  101. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  102. {
  103. va_list argList;
  104. va_start(argList, _format);
  105. char temp[2048];
  106. char* out = temp;
  107. int32_t max = sizeof(temp);
  108. int32_t len = bx::vsnprintf(out, max, _format, argList);
  109. if (len > max)
  110. {
  111. out = (char*)alloca(len);
  112. len = bx::vsnprintf(out, len, _format, argList);
  113. }
  114. len = bx::write(_writer, out, len);
  115. va_end(argList);
  116. return len;
  117. }
  118. class Bin2cWriter : public bx::CrtFileWriter
  119. {
  120. public:
  121. Bin2cWriter(const char* _name)
  122. : m_name(_name)
  123. {
  124. }
  125. virtual ~Bin2cWriter()
  126. {
  127. }
  128. virtual int32_t close() BX_OVERRIDE
  129. {
  130. generate();
  131. return bx::CrtFileWriter::close();
  132. }
  133. virtual int32_t write(const void* _data, int32_t _size) BX_OVERRIDE
  134. {
  135. const char* data = (const char*)_data;
  136. m_buffer.insert(m_buffer.end(), data, data+_size);
  137. return _size;
  138. }
  139. private:
  140. void generate()
  141. {
  142. #define HEX_DUMP_WIDTH 16
  143. #define HEX_DUMP_SPACE_WIDTH 96
  144. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  145. const uint8_t* data = &m_buffer[0];
  146. uint32_t size = (uint32_t)m_buffer.size();
  147. outf("static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size);
  148. if (NULL != data)
  149. {
  150. char hex[HEX_DUMP_SPACE_WIDTH+1];
  151. char ascii[HEX_DUMP_WIDTH+1];
  152. uint32_t hexPos = 0;
  153. uint32_t asciiPos = 0;
  154. for (uint32_t ii = 0; ii < size; ++ii)
  155. {
  156. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  157. hexPos += 6;
  158. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
  159. asciiPos++;
  160. if (HEX_DUMP_WIDTH == asciiPos)
  161. {
  162. ascii[asciiPos] = '\0';
  163. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  164. data += asciiPos;
  165. hexPos = 0;
  166. asciiPos = 0;
  167. }
  168. }
  169. if (0 != asciiPos)
  170. {
  171. ascii[asciiPos] = '\0';
  172. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  173. }
  174. }
  175. outf("};\n");
  176. #undef HEX_DUMP_WIDTH
  177. #undef HEX_DUMP_SPACE_WIDTH
  178. #undef HEX_DUMP_FORMAT
  179. }
  180. int32_t outf(const char* _format, ...)
  181. {
  182. va_list argList;
  183. va_start(argList, _format);
  184. char temp[2048];
  185. char* out = temp;
  186. int32_t max = sizeof(temp);
  187. int32_t len = bx::vsnprintf(out, max, _format, argList);
  188. if (len > max)
  189. {
  190. out = (char*)alloca(len);
  191. len = bx::vsnprintf(out, len, _format, argList);
  192. }
  193. int32_t size = bx::CrtFileWriter::write(out, len);
  194. va_end(argList);
  195. return size;
  196. }
  197. std::string m_filePath;
  198. std::string m_name;
  199. typedef std::vector<uint8_t> Buffer;
  200. Buffer m_buffer;
  201. };
  202. struct Varying
  203. {
  204. std::string m_precision;
  205. std::string m_interpolation;
  206. std::string m_name;
  207. std::string m_type;
  208. std::string m_init;
  209. std::string m_semantics;
  210. };
  211. typedef std::unordered_map<std::string, Varying> VaryingMap;
  212. class File
  213. {
  214. public:
  215. File(const char* _filePath)
  216. : m_data(NULL)
  217. {
  218. FILE* file = fopen(_filePath, "r");
  219. if (NULL != file)
  220. {
  221. m_size = fsize(file);
  222. m_data = new char[m_size+1];
  223. m_size = (uint32_t)fread(m_data, 1, m_size, file);
  224. m_data[m_size] = '\0';
  225. fclose(file);
  226. }
  227. }
  228. ~File()
  229. {
  230. delete [] m_data;
  231. }
  232. const char* getData() const
  233. {
  234. return m_data;
  235. }
  236. uint32_t getSize() const
  237. {
  238. return m_size;
  239. }
  240. private:
  241. char* m_data;
  242. uint32_t m_size;
  243. };
  244. void strins(char* _str, const char* _insert)
  245. {
  246. size_t len = strlen(_insert);
  247. memmove(&_str[len], _str, strlen(_str) );
  248. memcpy(_str, _insert, len);
  249. }
  250. void strreplace(char* _str, const char* _find, const char* _replace)
  251. {
  252. const size_t len = strlen(_find);
  253. char* replace = (char*)alloca(len+1);
  254. bx::strlcpy(replace, _replace, len+1);
  255. for (size_t ii = strlen(replace); ii < len; ++ii)
  256. {
  257. replace[ii] = ' ';
  258. }
  259. replace[len] = '\0';
  260. BX_CHECK(len >= strlen(_replace), "");
  261. for (char* ptr = strstr(_str, _find); NULL != ptr; ptr = strstr(ptr + len, _find) )
  262. {
  263. memcpy(ptr, replace, len);
  264. }
  265. }
  266. class LineReader
  267. {
  268. public:
  269. LineReader(const char* _str)
  270. : m_str(_str)
  271. , m_pos(0)
  272. , m_size( (uint32_t)strlen(_str) )
  273. {
  274. }
  275. std::string getLine()
  276. {
  277. const char* str = &m_str[m_pos];
  278. skipLine();
  279. const char* eol = &m_str[m_pos];
  280. std::string tmp;
  281. tmp.assign(str, eol-str);
  282. return tmp;
  283. }
  284. bool isEof() const
  285. {
  286. return m_str[m_pos] == '\0';
  287. }
  288. void skipLine()
  289. {
  290. const char* str = &m_str[m_pos];
  291. const char* nl = bx::strnl(str);
  292. m_pos += (uint32_t)(nl - str);
  293. }
  294. const char* m_str;
  295. uint32_t m_pos;
  296. uint32_t m_size;
  297. };
  298. void printCode(const char* _code, int32_t _line, int32_t _start, int32_t _end)
  299. {
  300. fprintf(stderr, "Code:\n---\n");
  301. LineReader lr(_code);
  302. for (int32_t line = 1; !lr.isEof() && line < _end; ++line)
  303. {
  304. if (line >= _start)
  305. {
  306. fprintf(stderr, "%s%3d: %s", _line == line ? ">>> " : " ", line, lr.getLine().c_str() );
  307. }
  308. else
  309. {
  310. lr.skipLine();
  311. }
  312. }
  313. fprintf(stderr, "---\n");
  314. }
  315. void writeFile(const char* _filePath, const void* _data, int32_t _size)
  316. {
  317. bx::CrtFileWriter out;
  318. if (0 == out.open(_filePath) )
  319. {
  320. out.write(_data, _size);
  321. out.close();
  322. }
  323. }
  324. struct Preprocessor
  325. {
  326. Preprocessor(const char* _filePath, bool _gles, const char* _includeDir = NULL)
  327. : m_tagptr(m_tags)
  328. , m_scratchPos(0)
  329. , m_fgetsPos(0)
  330. {
  331. m_tagptr->tag = FPPTAG_USERDATA;
  332. m_tagptr->data = this;
  333. m_tagptr++;
  334. m_tagptr->tag = FPPTAG_DEPENDS;
  335. m_tagptr->data = (void*)fppDepends;
  336. m_tagptr++;
  337. m_tagptr->tag = FPPTAG_INPUT;
  338. m_tagptr->data = (void*)fppInput;
  339. m_tagptr++;
  340. m_tagptr->tag = FPPTAG_OUTPUT;
  341. m_tagptr->data = (void*)fppOutput;
  342. m_tagptr++;
  343. m_tagptr->tag = FPPTAG_ERROR;
  344. m_tagptr->data = (void*)fppError;
  345. m_tagptr++;
  346. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  347. m_tagptr->data = (void*)0;
  348. m_tagptr++;
  349. m_tagptr->tag = FPPTAG_LINE;
  350. m_tagptr->data = (void*)0;
  351. m_tagptr++;
  352. m_tagptr->tag = FPPTAG_INPUT_NAME;
  353. m_tagptr->data = scratch(_filePath);
  354. m_tagptr++;
  355. if (NULL != _includeDir)
  356. {
  357. addInclude(_includeDir);
  358. }
  359. if (!_gles)
  360. {
  361. m_default = "#define lowp\n#define mediump\n#define highp\n";
  362. }
  363. }
  364. void setDefine(const char* _define)
  365. {
  366. m_tagptr->tag = FPPTAG_DEFINE;
  367. m_tagptr->data = scratch(_define);
  368. m_tagptr++;
  369. }
  370. void setDefaultDefine(const char* _name)
  371. {
  372. char temp[1024];
  373. bx::snprintf(temp, BX_COUNTOF(temp)
  374. , "#ifndef %s\n"
  375. "# define %s 0\n"
  376. "#endif // %s\n"
  377. "\n"
  378. , _name
  379. , _name
  380. , _name
  381. );
  382. m_default += temp;
  383. }
  384. void writef(const char* _format, ...)
  385. {
  386. va_list argList;
  387. va_start(argList, _format);
  388. bx::stringPrintfVargs(m_default, _format, argList);
  389. va_end(argList);
  390. }
  391. void addInclude(const char* _includeDir)
  392. {
  393. char* start = scratch(_includeDir);
  394. for (char* split = strchr(start, ';'); NULL != split; split = strchr(start, ';'))
  395. {
  396. *split = '\0';
  397. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  398. m_tagptr->data = start;
  399. m_tagptr++;
  400. start = split + 1;
  401. }
  402. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  403. m_tagptr->data = start;
  404. m_tagptr++;
  405. }
  406. void addDependency(const char* _fileName)
  407. {
  408. m_depends += " \\\n ";
  409. m_depends += _fileName;
  410. }
  411. bool run(const char* _input)
  412. {
  413. m_fgetsPos = 0;
  414. m_preprocessed.clear();
  415. m_input = m_default;
  416. m_input += "\n\n";
  417. size_t len = strlen(_input)+1;
  418. char* temp = new char[len];
  419. bx::eolLF(temp, len, _input);
  420. m_input += temp;
  421. delete [] temp;
  422. fppTag* tagptr = m_tagptr;
  423. tagptr->tag = FPPTAG_END;
  424. tagptr->data = 0;
  425. tagptr++;
  426. int result = fppPreProcess(m_tags);
  427. return 0 == result;
  428. }
  429. char* fgets(char* _buffer, int _size)
  430. {
  431. int ii = 0;
  432. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  433. {
  434. _buffer[ii++] = ch;
  435. if (ch == '\n' || ii == _size)
  436. {
  437. _buffer[ii] = '\0';
  438. m_fgetsPos++;
  439. return _buffer;
  440. }
  441. }
  442. return NULL;
  443. }
  444. static void fppDepends(char* _fileName, void* _userData)
  445. {
  446. Preprocessor* thisClass = (Preprocessor*)_userData;
  447. thisClass->addDependency(_fileName);
  448. }
  449. static char* fppInput(char* _buffer, int _size, void* _userData)
  450. {
  451. Preprocessor* thisClass = (Preprocessor*)_userData;
  452. return thisClass->fgets(_buffer, _size);
  453. }
  454. static void fppOutput(int _ch, void* _userData)
  455. {
  456. Preprocessor* thisClass = (Preprocessor*)_userData;
  457. thisClass->m_preprocessed += _ch;
  458. }
  459. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  460. {
  461. vfprintf(stderr, _format, _vargs);
  462. }
  463. char* scratch(const char* _str)
  464. {
  465. char* result = &m_scratch[m_scratchPos];
  466. strcpy(result, _str);
  467. m_scratchPos += (uint32_t)strlen(_str)+1;
  468. return result;
  469. }
  470. fppTag m_tags[MAX_TAGS];
  471. fppTag* m_tagptr;
  472. std::string m_depends;
  473. std::string m_default;
  474. std::string m_input;
  475. std::string m_preprocessed;
  476. char m_scratch[16<<10];
  477. uint32_t m_scratchPos;
  478. uint32_t m_fgetsPos;
  479. };
  480. typedef std::vector<std::string> InOut;
  481. uint32_t parseInOut(InOut& _inout, const char* _str, const char* _eol)
  482. {
  483. uint32_t hash = 0;
  484. _str = bx::strws(_str);
  485. if (_str < _eol)
  486. {
  487. const char* delim;
  488. do
  489. {
  490. delim = strpbrk(_str, " ,");
  491. if (NULL != delim)
  492. {
  493. delim = delim > _eol ? _eol : delim;
  494. std::string token;
  495. token.assign(_str, delim-_str);
  496. _inout.push_back(token);
  497. _str = bx::strws(delim + 1);
  498. }
  499. }
  500. while (delim < _eol && _str < _eol && NULL != delim);
  501. std::sort(_inout.begin(), _inout.end() );
  502. bx::HashMurmur2A murmur;
  503. murmur.begin();
  504. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  505. {
  506. murmur.add(it->c_str(), (uint32_t)it->size() );
  507. }
  508. hash = murmur.end();
  509. }
  510. return hash;
  511. }
  512. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  513. {
  514. char find[32];
  515. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  516. char replace[32];
  517. bx::snprintf(replace, sizeof(replace), "gl_FragData_%d_", _idx);
  518. strreplace(_data, find, replace);
  519. _preprocessor.writef(
  520. " \\\n\t%sout vec4 gl_FragData_%d_ : SV_TARGET%d"
  521. , _comma ? ", " : " "
  522. , _idx
  523. , _idx
  524. );
  525. }
  526. void voidFragData(char* _data, uint32_t _idx)
  527. {
  528. char find[32];
  529. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  530. strreplace(_data, find, "bgfx_VoidFrag");
  531. }
  532. // c - compute
  533. // d - domain
  534. // f - fragment
  535. // g - geometry
  536. // h - hull
  537. // v - vertex
  538. //
  539. // OpenGL #version Features Direct3D Features Shader Model
  540. // 2.1 120 vf 9.0 vf 2.0
  541. // 3.0 130
  542. // 3.1 140
  543. // 3.2 150 vgf
  544. // 3.3 330 10.0 vgf 4.0
  545. // 4.0 400 vhdgf
  546. // 4.1 410
  547. // 4.2 420 11.0 vhdgf+c 5.0
  548. // 4.3 430 vhdgf+c
  549. // 4.4 440
  550. void help(const char* _error = NULL)
  551. {
  552. if (NULL != _error)
  553. {
  554. fprintf(stderr, "Error:\n%s\n\n", _error);
  555. }
  556. fprintf(stderr
  557. , "shaderc, bgfx shader compiler tool\n"
  558. "Copyright 2011-2015 Branimir Karadzic. All rights reserved.\n"
  559. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  560. );
  561. fprintf(stderr
  562. , "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  563. "\n"
  564. "Options:\n"
  565. " -f <file path> Input file path.\n"
  566. " -i <include path> Include path (for multiple paths use semicolon).\n"
  567. " -o <file path> Output file path.\n"
  568. " --bin2c <file path> Generate C header file.\n"
  569. " --depends <file path> Generate makefile style depends file.\n"
  570. " --platform <platform> Target platform.\n"
  571. " android\n"
  572. " asm.js\n"
  573. " ios\n"
  574. " linux\n"
  575. " nacl\n"
  576. " osx\n"
  577. " windows\n"
  578. " --preprocess Preprocess only.\n"
  579. " --raw Do not process shader. No preprocessor, and no glsl-optimizer (GLSL only).\n"
  580. " --type <type> Shader type (vertex, fragment)\n"
  581. " --varyingdef <file path> Path to varying.def.sc file.\n"
  582. " --verbose Verbose.\n"
  583. "\n"
  584. "Options (DX9 and DX11 only):\n"
  585. "\n"
  586. " --debug Debug information.\n"
  587. " --disasm Disassemble compiled shader.\n"
  588. " -p, --profile <profile> Shader model (f.e. ps_3_0).\n"
  589. " -O <level> Optimization level (0, 1, 2, 3).\n"
  590. " --Werror Treat warnings as errors.\n"
  591. "\n"
  592. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  593. );
  594. }
  595. int main(int _argc, const char* _argv[])
  596. {
  597. bx::CommandLine cmdLine(_argc, _argv);
  598. if (cmdLine.hasArg('h', "help") )
  599. {
  600. help();
  601. return EXIT_FAILURE;
  602. }
  603. g_verbose = cmdLine.hasArg("verbose");
  604. const char* filePath = cmdLine.findOption('f');
  605. if (NULL == filePath)
  606. {
  607. help("Shader file name must be specified.");
  608. return EXIT_FAILURE;
  609. }
  610. const char* outFilePath = cmdLine.findOption('o');
  611. if (NULL == outFilePath)
  612. {
  613. help("Output file name must be specified.");
  614. return EXIT_FAILURE;
  615. }
  616. const char* type = cmdLine.findOption('\0', "type");
  617. if (NULL == type)
  618. {
  619. help("Must specify shader type.");
  620. return EXIT_FAILURE;
  621. }
  622. const char* platform = cmdLine.findOption('\0', "platform");
  623. if (NULL == platform)
  624. {
  625. help("Must specify platform.");
  626. return EXIT_FAILURE;
  627. }
  628. bool raw = cmdLine.hasArg('\0', "raw");
  629. uint32_t gles = 0;
  630. uint32_t hlsl = 2;
  631. uint32_t d3d = 11;
  632. const char* profile = cmdLine.findOption('p', "profile");
  633. if (NULL != profile)
  634. {
  635. if (0 == strncmp(&profile[1], "s_4_0_level", 11) )
  636. {
  637. hlsl = 2;
  638. }
  639. else if (0 == strncmp(&profile[1], "s_3", 3) )
  640. {
  641. hlsl = 3;
  642. d3d = 9;
  643. }
  644. else if (0 == strncmp(&profile[1], "s_4", 3) )
  645. {
  646. hlsl = 4;
  647. }
  648. else if (0 == strncmp(&profile[1], "s_5", 3) )
  649. {
  650. hlsl = 5;
  651. }
  652. }
  653. else
  654. {
  655. gles = 2;
  656. }
  657. const char* bin2c = NULL;
  658. if (cmdLine.hasArg("bin2c") )
  659. {
  660. bin2c = cmdLine.findOption("bin2c");
  661. if (NULL == bin2c)
  662. {
  663. bin2c = bx::baseName(outFilePath);
  664. uint32_t len = (uint32_t)strlen(bin2c);
  665. char* temp = (char*)alloca(len+1);
  666. for (char *out = temp; *bin2c != '\0';)
  667. {
  668. char ch = *bin2c++;
  669. if (isalnum(ch) )
  670. {
  671. *out++ = ch;
  672. }
  673. else
  674. {
  675. *out++ = '_';
  676. }
  677. }
  678. temp[len] = '\0';
  679. bin2c = temp;
  680. }
  681. }
  682. bool depends = cmdLine.hasArg("depends");
  683. bool preprocessOnly = cmdLine.hasArg("preprocess");
  684. const char* includeDir = cmdLine.findOption('i');
  685. Preprocessor preprocessor(filePath, 0 != gles, includeDir);
  686. std::string dir;
  687. {
  688. const char* base = bx::baseName(filePath);
  689. if (base != filePath)
  690. {
  691. dir.assign(filePath, base-filePath);
  692. preprocessor.addInclude(dir.c_str() );
  693. }
  694. }
  695. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  696. preprocessor.setDefaultDefine("BX_PLATFORM_EMSCRIPTEN");
  697. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  698. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  699. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  700. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  701. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  702. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  703. // preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_ESSL");
  704. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  705. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  706. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_COMPUTE");
  707. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  708. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  709. bool glsl = false;
  710. if (0 == bx::stricmp(platform, "android") )
  711. {
  712. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  713. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  714. glsl = true;
  715. }
  716. else if (0 == bx::stricmp(platform, "asm.js") )
  717. {
  718. preprocessor.setDefine("BX_PLATFORM_EMSCRIPTEN=1");
  719. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  720. glsl = true;
  721. }
  722. else if (0 == bx::stricmp(platform, "ios") )
  723. {
  724. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  725. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  726. glsl = true;
  727. }
  728. else if (0 == bx::stricmp(platform, "linux") )
  729. {
  730. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  731. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  732. glsl = true;
  733. }
  734. else if (0 == bx::stricmp(platform, "nacl") )
  735. {
  736. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  737. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  738. glsl = true;
  739. }
  740. else if (0 == bx::stricmp(platform, "osx") )
  741. {
  742. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  743. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  744. glsl = true;
  745. }
  746. else if (0 == bx::stricmp(platform, "windows") )
  747. {
  748. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  749. char temp[256];
  750. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  751. preprocessor.setDefine(temp);
  752. }
  753. else if (0 == bx::stricmp(platform, "xbox360") )
  754. {
  755. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  756. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=3");
  757. }
  758. else
  759. {
  760. fprintf(stderr, "Unknown platform %s?!", platform);
  761. return EXIT_FAILURE;
  762. }
  763. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  764. char shaderType = tolower(type[0]);
  765. switch (shaderType)
  766. {
  767. case 'c':
  768. preprocessor.setDefine("BGFX_SHADER_TYPE_COMPUTE=1");
  769. break;
  770. case 'f':
  771. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  772. break;
  773. case 'v':
  774. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  775. break;
  776. default:
  777. fprintf(stderr, "Unknown type: %s?!", type);
  778. return EXIT_FAILURE;
  779. }
  780. bool compiled = false;
  781. FILE* file = fopen(filePath, "r");
  782. if (NULL == file)
  783. {
  784. fprintf(stderr, "Unable to open file '%s'.\n", filePath);
  785. }
  786. else
  787. {
  788. VaryingMap varyingMap;
  789. std::string defaultVarying = dir + "varying.def.sc";
  790. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  791. File attribdef(varyingdef);
  792. const char* parse = attribdef.getData();
  793. if (NULL != parse
  794. && *parse != '\0')
  795. {
  796. preprocessor.addDependency(varyingdef);
  797. }
  798. while (NULL != parse
  799. && *parse != '\0')
  800. {
  801. parse = bx::strws(parse);
  802. const char* eol = strchr(parse, ';');
  803. if (NULL == eol)
  804. {
  805. eol = bx::streol(parse);
  806. }
  807. if (NULL != eol)
  808. {
  809. const char* precision = NULL;
  810. const char* interpolation = NULL;
  811. const char* type = parse;
  812. if (0 == strncmp(type, "lowp", 4)
  813. || 0 == strncmp(type, "mediump", 7)
  814. || 0 == strncmp(type, "highp", 5) )
  815. {
  816. precision = type;
  817. type = parse = bx::strws(bx::strword(parse) );
  818. }
  819. if (0 == strncmp(type, "flat", 4)
  820. || 0 == strncmp(type, "smooth", 6)
  821. || 0 == strncmp(type, "noperspective", 13) )
  822. {
  823. interpolation = type;
  824. type = parse = bx::strws(bx::strword(parse) );
  825. }
  826. const char* name = parse = bx::strws(bx::strword(parse) );
  827. const char* column = parse = bx::strws(bx::strword(parse) );
  828. const char* semantics = parse = bx::strws(bx::strnws (parse) );
  829. const char* assign = parse = bx::strws(bx::strword(parse) );
  830. const char* init = parse = bx::strws(bx::strnws (parse) );
  831. if (type < eol
  832. && name < eol
  833. && column < eol
  834. && ':' == *column
  835. && semantics < eol)
  836. {
  837. Varying var;
  838. if (NULL != precision)
  839. {
  840. var.m_precision.assign(precision, bx::strword(precision)-precision);
  841. }
  842. if (NULL != interpolation)
  843. {
  844. var.m_interpolation.assign(interpolation, bx::strword(interpolation)-interpolation);
  845. }
  846. var.m_type.assign(type, bx::strword(type)-type);
  847. var.m_name.assign(name, bx::strword(name)-name);
  848. var.m_semantics.assign(semantics, bx::strword(semantics)-semantics);
  849. if (d3d == 9
  850. && var.m_semantics == "BITANGENT")
  851. {
  852. var.m_semantics = "BINORMAL";
  853. }
  854. if (assign < eol
  855. && '=' == *assign
  856. && init < eol)
  857. {
  858. var.m_init.assign(init, eol-init);
  859. }
  860. varyingMap.insert(std::make_pair(var.m_name, var) );
  861. }
  862. parse = bx::strws(bx::strnl(eol) );
  863. }
  864. }
  865. InOut shaderInputs;
  866. InOut shaderOutputs;
  867. uint32_t inputHash = 0;
  868. uint32_t outputHash = 0;
  869. char* data;
  870. char* input;
  871. {
  872. const size_t padding = 1024;
  873. uint32_t size = (uint32_t)fsize(file);
  874. data = new char[size+padding+1];
  875. size = (uint32_t)fread(data, 1, size, file);
  876. // Compiler generates "error X3000: syntax error: unexpected end of file"
  877. // if input doesn't have empty line at EOF.
  878. data[size] = '\n';
  879. memset(&data[size+1], 0, padding);
  880. fclose(file);
  881. input = const_cast<char*>(bx::strws(data) );
  882. while (input[0] == '$')
  883. {
  884. const char* str = bx::strws(input+1);
  885. const char* eol = bx::streol(str);
  886. const char* nl = bx::strnl(eol);
  887. input = const_cast<char*>(nl);
  888. if (0 == strncmp(str, "input", 5) )
  889. {
  890. str += 5;
  891. const char* comment = strstr(str, "//");
  892. eol = NULL != comment && comment < eol ? comment : eol;
  893. inputHash = parseInOut(shaderInputs, str, eol);
  894. }
  895. else if (0 == strncmp(str, "output", 6) )
  896. {
  897. str += 6;
  898. const char* comment = strstr(str, "//");
  899. eol = NULL != comment && comment < eol ? comment : eol;
  900. outputHash = parseInOut(shaderOutputs, str, eol);
  901. }
  902. else if (0 == strncmp(str, "raw", 3) )
  903. {
  904. raw = true;
  905. str += 3;
  906. }
  907. input = const_cast<char*>(bx::strws(input) );
  908. }
  909. if (!raw)
  910. {
  911. // To avoid commented code being recognized as used feature,
  912. // first preprocess pass is used to strip all comments before
  913. // substituting code.
  914. preprocessor.run(input);
  915. delete [] data;
  916. size = (uint32_t)preprocessor.m_preprocessed.size();
  917. data = new char[size+padding+1];
  918. memcpy(data, preprocessor.m_preprocessed.c_str(), size);
  919. memset(&data[size], 0, padding+1);
  920. input = data;
  921. }
  922. }
  923. if (raw)
  924. {
  925. bx::CrtFileWriter* writer = NULL;
  926. if (NULL != bin2c)
  927. {
  928. writer = new Bin2cWriter(bin2c);
  929. }
  930. else
  931. {
  932. writer = new bx::CrtFileWriter;
  933. }
  934. if (0 != writer->open(outFilePath) )
  935. {
  936. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  937. return EXIT_FAILURE;
  938. }
  939. uint32_t inputHash = 0;
  940. uint32_t outputHash = 0;
  941. if ('f' == shaderType)
  942. {
  943. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  944. bx::write(writer, inputHash);
  945. }
  946. else if ('v' == shaderType)
  947. {
  948. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  949. bx::write(writer, outputHash);
  950. }
  951. else
  952. {
  953. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  954. bx::write(writer, outputHash);
  955. }
  956. if (glsl)
  957. {
  958. bx::write(writer, uint16_t(0) );
  959. uint32_t shaderSize = (uint32_t)strlen(input);
  960. bx::write(writer, shaderSize);
  961. bx::write(writer, input, shaderSize);
  962. bx::write(writer, uint8_t(0) );
  963. compiled = true;
  964. }
  965. else
  966. {
  967. if (d3d > 9)
  968. {
  969. compiled = compileHLSLShaderDx11(cmdLine, input, writer);
  970. }
  971. else
  972. {
  973. compiled = compileHLSLShaderDx9(cmdLine, input, writer);
  974. }
  975. }
  976. writer->close();
  977. delete writer;
  978. }
  979. else if ('c' == shaderType) // Compute
  980. {
  981. char* entry = strstr(input, "void main()");
  982. if (NULL == entry)
  983. {
  984. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  985. }
  986. else
  987. {
  988. if (glsl)
  989. {
  990. }
  991. else
  992. {
  993. preprocessor.writef(
  994. "#define lowp\n"
  995. "#define mediump\n"
  996. "#define highp\n"
  997. "#define ivec2 int2\n"
  998. "#define ivec3 int3\n"
  999. "#define ivec4 int4\n"
  1000. "#define uvec2 uint2\n"
  1001. "#define uvec3 uint3\n"
  1002. "#define uvec4 uint4\n"
  1003. "#define vec2 float2\n"
  1004. "#define vec3 float3\n"
  1005. "#define vec4 float4\n"
  1006. "#define mat2 float2x2\n"
  1007. "#define mat3 float3x3\n"
  1008. "#define mat4 float4x4\n"
  1009. );
  1010. entry[4] = '_';
  1011. preprocessor.writef("#define void_main()");
  1012. preprocessor.writef(" \\\n\tvoid main(");
  1013. uint32_t arg = 0;
  1014. const bool hasLocalInvocationID = NULL != strstr(input, "gl_LocalInvocationID");
  1015. const bool hasLocalInvocationIndex = NULL != strstr(input, "gl_LocalInvocationIndex");
  1016. const bool hasGlobalInvocationID = NULL != strstr(input, "gl_GlobalInvocationID");
  1017. const bool hasWorkGroupID = NULL != strstr(input, "gl_WorkGroupID");
  1018. if (hasLocalInvocationID)
  1019. {
  1020. preprocessor.writef(
  1021. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1022. , arg++ > 0 ? ", " : " "
  1023. );
  1024. }
  1025. if (hasLocalInvocationIndex)
  1026. {
  1027. preprocessor.writef(
  1028. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1029. , arg++ > 0 ? ", " : " "
  1030. );
  1031. }
  1032. if (hasGlobalInvocationID)
  1033. {
  1034. preprocessor.writef(
  1035. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1036. , arg++ > 0 ? ", " : " "
  1037. );
  1038. }
  1039. if (hasWorkGroupID)
  1040. {
  1041. preprocessor.writef(
  1042. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1043. , arg++ > 0 ? ", " : " "
  1044. );
  1045. }
  1046. preprocessor.writef(
  1047. " \\\n\t)\n"
  1048. );
  1049. }
  1050. if (preprocessor.run(input) )
  1051. {
  1052. BX_TRACE("Input file: %s", filePath);
  1053. BX_TRACE("Output file: %s", outFilePath);
  1054. if (preprocessOnly)
  1055. {
  1056. bx::CrtFileWriter writer;
  1057. if (0 != writer.open(outFilePath) )
  1058. {
  1059. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1060. return EXIT_FAILURE;
  1061. }
  1062. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1063. writer.close();
  1064. return EXIT_SUCCESS;
  1065. }
  1066. {
  1067. bx::CrtFileWriter* writer = NULL;
  1068. if (NULL != bin2c)
  1069. {
  1070. writer = new Bin2cWriter(bin2c);
  1071. }
  1072. else
  1073. {
  1074. writer = new bx::CrtFileWriter;
  1075. }
  1076. if (0 != writer->open(outFilePath) )
  1077. {
  1078. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1079. return EXIT_FAILURE;
  1080. }
  1081. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1082. bx::write(writer, outputHash);
  1083. if (glsl)
  1084. {
  1085. std::string code;
  1086. if (gles)
  1087. {
  1088. bx::stringPrintf(code, "#version 310 es\n");
  1089. }
  1090. else
  1091. {
  1092. int32_t version = atoi(profile);
  1093. bx::stringPrintf(code, "#version %d\n", version == 0 ? 430 : version);
  1094. }
  1095. code += preprocessor.m_preprocessed;
  1096. #if 1
  1097. bx::write(writer, uint16_t(0) );
  1098. uint32_t shaderSize = (uint32_t)code.size();
  1099. bx::write(writer, shaderSize);
  1100. bx::write(writer, code.c_str(), shaderSize);
  1101. bx::write(writer, uint8_t(0) );
  1102. compiled = true;
  1103. #else
  1104. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  1105. #endif // 0
  1106. }
  1107. else
  1108. {
  1109. if (d3d > 9)
  1110. {
  1111. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1112. }
  1113. else
  1114. {
  1115. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1116. }
  1117. }
  1118. writer->close();
  1119. delete writer;
  1120. }
  1121. if (compiled)
  1122. {
  1123. if (depends)
  1124. {
  1125. std::string ofp = outFilePath;
  1126. ofp += ".d";
  1127. bx::CrtFileWriter writer;
  1128. if (0 == writer.open(ofp.c_str() ) )
  1129. {
  1130. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1131. writer.close();
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. }
  1138. else // Vertex/Fragment
  1139. {
  1140. char* entry = strstr(input, "void main()");
  1141. if (NULL == entry)
  1142. {
  1143. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1144. }
  1145. else
  1146. {
  1147. if (glsl)
  1148. {
  1149. preprocessor.writef(
  1150. "#define ivec2 vec2\n"
  1151. "#define ivec3 vec3\n"
  1152. "#define ivec4 vec4\n"
  1153. );
  1154. if (0 == gles)
  1155. {
  1156. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1157. // not as GLSL language 1.2 specs shadow2D/Proj.
  1158. preprocessor.writef(
  1159. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1160. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1161. );
  1162. }
  1163. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1164. {
  1165. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1166. if (varyingIt != varyingMap.end() )
  1167. {
  1168. const Varying& var = varyingIt->second;
  1169. const char* name = var.m_name.c_str();
  1170. if (0 == strncmp(name, "a_", 2)
  1171. || 0 == strncmp(name, "i_", 2) )
  1172. {
  1173. preprocessor.writef("attribute %s %s %s %s;\n"
  1174. , var.m_precision.c_str()
  1175. , var.m_interpolation.c_str()
  1176. , var.m_type.c_str()
  1177. , name
  1178. );
  1179. }
  1180. else
  1181. {
  1182. preprocessor.writef("%s varying %s %s %s;\n"
  1183. , var.m_interpolation.c_str()
  1184. , var.m_precision.c_str()
  1185. , var.m_type.c_str()
  1186. , name
  1187. );
  1188. }
  1189. }
  1190. }
  1191. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1192. {
  1193. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1194. if (varyingIt != varyingMap.end() )
  1195. {
  1196. const Varying& var = varyingIt->second;
  1197. preprocessor.writef("%s varying %s %s;\n"
  1198. , var.m_interpolation.c_str()
  1199. , var.m_type.c_str()
  1200. , var.m_name.c_str()
  1201. );
  1202. }
  1203. }
  1204. }
  1205. else
  1206. {
  1207. preprocessor.writef(
  1208. "#define lowp\n"
  1209. "#define mediump\n"
  1210. "#define highp\n"
  1211. "#define ivec2 int2\n"
  1212. "#define ivec3 int3\n"
  1213. "#define ivec4 int4\n"
  1214. "#define uvec2 uint2\n"
  1215. "#define uvec3 uint3\n"
  1216. "#define uvec4 uint4\n"
  1217. "#define vec2 float2\n"
  1218. "#define vec3 float3\n"
  1219. "#define vec4 float4\n"
  1220. "#define mat2 float2x2\n"
  1221. "#define mat3 float3x3\n"
  1222. "#define mat4 float4x4\n"
  1223. );
  1224. if (hlsl < 4)
  1225. {
  1226. preprocessor.writef(
  1227. "#define flat\n"
  1228. "#define smooth\n"
  1229. "#define noperspective\n"
  1230. );
  1231. }
  1232. entry[4] = '_';
  1233. if ('f' == shaderType)
  1234. {
  1235. const char* brace = strstr(entry, "{");
  1236. if (NULL != brace)
  1237. {
  1238. strins(const_cast<char*>(brace+1), "\nvec4 bgfx_VoidFrag;\n");
  1239. }
  1240. const bool hasFragCoord = NULL != strstr(input, "gl_FragCoord") || hlsl > 3;
  1241. const bool hasFragDepth = NULL != strstr(input, "gl_FragDepth");
  1242. const bool hasFrontFacing = NULL != strstr(input, "gl_FrontFacing");
  1243. const bool hasPrimitiveId = NULL != strstr(input, "gl_PrimitiveID");
  1244. bool hasFragData[8] = {};
  1245. uint32_t numFragData = 0;
  1246. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1247. {
  1248. char temp[32];
  1249. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  1250. hasFragData[ii] = NULL != strstr(input, temp);
  1251. numFragData += hasFragData[ii];
  1252. }
  1253. if (0 == numFragData)
  1254. {
  1255. // GL errors when both gl_FragColor and gl_FragData is used.
  1256. // This will trigger the same error with HLSL compiler too.
  1257. preprocessor.writef("#define gl_FragColor gl_FragData_0_\n");
  1258. }
  1259. preprocessor.writef("#define void_main()");
  1260. preprocessor.writef(" \\\n\tvoid main(");
  1261. uint32_t arg = 0;
  1262. if (hasFragCoord)
  1263. {
  1264. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1265. ++arg;
  1266. }
  1267. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1268. {
  1269. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1270. if (varyingIt != varyingMap.end() )
  1271. {
  1272. const Varying& var = varyingIt->second;
  1273. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  1274. , arg++ > 0 ? ", " : " "
  1275. , interpolationDx11(var.m_interpolation.c_str() )
  1276. , var.m_type.c_str()
  1277. , var.m_name.c_str()
  1278. , var.m_semantics.c_str()
  1279. );
  1280. }
  1281. }
  1282. addFragData(preprocessor, input, 0, arg++ > 0);
  1283. const uint32_t maxRT = d3d > 9 ? BX_COUNTOF(hasFragData) : 4;
  1284. for (uint32_t ii = 1; ii < BX_COUNTOF(hasFragData); ++ii)
  1285. {
  1286. if (ii < maxRT)
  1287. {
  1288. if (hasFragData[ii])
  1289. {
  1290. addFragData(preprocessor, input, ii, arg++ > 0);
  1291. }
  1292. }
  1293. else
  1294. {
  1295. voidFragData(input, ii);
  1296. }
  1297. }
  1298. if (hasFragDepth)
  1299. {
  1300. preprocessor.writef(
  1301. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1302. , arg++ > 0 ? ", " : " "
  1303. );
  1304. }
  1305. if (hasFrontFacing
  1306. && hlsl >= 3)
  1307. {
  1308. preprocessor.writef(
  1309. " \\\n\t%sfloat __vface : VFACE"
  1310. , arg++ > 0 ? ", " : " "
  1311. );
  1312. }
  1313. if (hasPrimitiveId)
  1314. {
  1315. if (d3d > 9)
  1316. {
  1317. preprocessor.writef(
  1318. " \\\n\t%suint gl_PrimitiveID : SV_PrimitiveID"
  1319. , arg++ > 0 ? ", " : " "
  1320. );
  1321. }
  1322. else
  1323. {
  1324. fprintf(stderr, "PrimitiveID builtin is not supported by this D3D9 HLSL.\n");
  1325. return EXIT_FAILURE;
  1326. }
  1327. }
  1328. preprocessor.writef(
  1329. " \\\n\t)\n"
  1330. );
  1331. if (hasFrontFacing)
  1332. {
  1333. if (hlsl >= 3)
  1334. {
  1335. preprocessor.writef(
  1336. "#define gl_FrontFacing (__vface <= 0.0)\n"
  1337. );
  1338. }
  1339. else
  1340. {
  1341. preprocessor.writef(
  1342. "#define gl_FrontFacing false\n"
  1343. );
  1344. }
  1345. }
  1346. }
  1347. else if ('v' == shaderType)
  1348. {
  1349. const char* brace = strstr(entry, "{");
  1350. if (NULL != brace)
  1351. {
  1352. const char* end = bx::strmb(brace, '{', '}');
  1353. if (NULL != end)
  1354. {
  1355. strins(const_cast<char*>(end), "__RETURN__;\n");
  1356. }
  1357. }
  1358. preprocessor.writef(
  1359. "struct Output\n"
  1360. "{\n"
  1361. "\tvec4 gl_Position : SV_POSITION;\n"
  1362. "#define gl_Position _varying_.gl_Position\n"
  1363. );
  1364. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1365. {
  1366. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1367. if (varyingIt != varyingMap.end() )
  1368. {
  1369. const Varying& var = varyingIt->second;
  1370. preprocessor.writef("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1371. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  1372. }
  1373. }
  1374. preprocessor.writef(
  1375. "};\n"
  1376. );
  1377. preprocessor.writef("#define void_main() \\\n");
  1378. preprocessor.writef("Output main(");
  1379. bool first = true;
  1380. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1381. {
  1382. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1383. if (varyingIt != varyingMap.end() )
  1384. {
  1385. const Varying& var = varyingIt->second;
  1386. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1387. first = false;
  1388. }
  1389. }
  1390. preprocessor.writef(
  1391. ") \\\n"
  1392. "{ \\\n"
  1393. "\tOutput _varying_;"
  1394. );
  1395. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1396. {
  1397. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1398. if (varyingIt != varyingMap.end() )
  1399. {
  1400. const Varying& var = varyingIt->second;
  1401. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  1402. }
  1403. }
  1404. preprocessor.writef(
  1405. "\n#define __RETURN__ \\\n"
  1406. "\t} \\\n"
  1407. "\treturn _varying_"
  1408. );
  1409. }
  1410. }
  1411. if (preprocessor.run(input) )
  1412. {
  1413. BX_TRACE("Input file: %s", filePath);
  1414. BX_TRACE("Output file: %s", outFilePath);
  1415. if (preprocessOnly)
  1416. {
  1417. bx::CrtFileWriter writer;
  1418. if (0 != writer.open(outFilePath) )
  1419. {
  1420. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1421. return EXIT_FAILURE;
  1422. }
  1423. if (glsl)
  1424. {
  1425. const char* profile = cmdLine.findOption('p', "profile");
  1426. if (NULL == profile)
  1427. {
  1428. writef(&writer
  1429. , "#ifdef GL_ES\n"
  1430. "precision highp float;\n"
  1431. "#endif // GL_ES\n\n"
  1432. );
  1433. }
  1434. }
  1435. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1436. writer.close();
  1437. return EXIT_SUCCESS;
  1438. }
  1439. {
  1440. bx::CrtFileWriter* writer = NULL;
  1441. if (NULL != bin2c)
  1442. {
  1443. writer = new Bin2cWriter(bin2c);
  1444. }
  1445. else
  1446. {
  1447. writer = new bx::CrtFileWriter;
  1448. }
  1449. if (0 != writer->open(outFilePath) )
  1450. {
  1451. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1452. return EXIT_FAILURE;
  1453. }
  1454. if ('f' == shaderType)
  1455. {
  1456. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  1457. bx::write(writer, inputHash);
  1458. }
  1459. else if ('v' == shaderType)
  1460. {
  1461. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  1462. bx::write(writer, outputHash);
  1463. }
  1464. else
  1465. {
  1466. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1467. bx::write(writer, outputHash);
  1468. }
  1469. if (glsl)
  1470. {
  1471. std::string code;
  1472. bool hasTextureLod = NULL != bx::findIdentifierMatch(input, s_ARB_shader_texture_lod /*EXT_shader_texture_lod*/);
  1473. if (0 == gles)
  1474. {
  1475. bx::stringPrintf(code, "#version %s\n", profile);
  1476. int32_t version = atoi(profile);
  1477. bx::stringPrintf(code
  1478. , "#define bgfxShadow2D shadow2D\n"
  1479. "#define bgfxShadow2DProj shadow2DProj\n"
  1480. );
  1481. if (hasTextureLod
  1482. && 130 > version)
  1483. {
  1484. bx::stringPrintf(code
  1485. , "#extension GL_ARB_shader_texture_lod : enable\n"
  1486. );
  1487. }
  1488. }
  1489. else
  1490. {
  1491. // Pretend that all extensions are available.
  1492. // This will be stripped later.
  1493. if (hasTextureLod)
  1494. {
  1495. bx::stringPrintf(code
  1496. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1497. "#define texture2DLod texture2DLodEXT\n"
  1498. "#define texture2DProjLod texture2DProjLodEXT\n"
  1499. "#define textureCubeLod textureCubeLodEXT\n"
  1500. // "#define texture2DGrad texture2DGradEXT\n"
  1501. // "#define texture2DProjGrad texture2DProjGradEXT\n"
  1502. // "#define textureCubeGrad textureCubeGradEXT\n"
  1503. );
  1504. }
  1505. if (NULL != bx::findIdentifierMatch(input, s_OES_standard_derivatives) )
  1506. {
  1507. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  1508. }
  1509. if (NULL != bx::findIdentifierMatch(input, s_OES_texture_3D) )
  1510. {
  1511. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  1512. }
  1513. if (NULL != bx::findIdentifierMatch(input, s_EXT_shadow_samplers) )
  1514. {
  1515. bx::stringPrintf(code
  1516. , "#extension GL_EXT_shadow_samplers : enable\n"
  1517. "#define shadow2D shadow2DEXT\n"
  1518. "#define shadow2DProj shadow2DProjEXT\n"
  1519. );
  1520. }
  1521. if (NULL != bx::findIdentifierMatch(input, "gl_FragDepth") )
  1522. {
  1523. bx::stringPrintf(code
  1524. , "#extension GL_EXT_frag_depth : enable\n"
  1525. "#define gl_FragDepth gl_FragDepthEXT\n"
  1526. );
  1527. }
  1528. }
  1529. code += preprocessor.m_preprocessed;
  1530. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  1531. }
  1532. else
  1533. {
  1534. if (d3d > 9)
  1535. {
  1536. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1537. }
  1538. else
  1539. {
  1540. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1541. }
  1542. }
  1543. writer->close();
  1544. delete writer;
  1545. }
  1546. if (compiled)
  1547. {
  1548. if (depends)
  1549. {
  1550. std::string ofp = outFilePath;
  1551. ofp += ".d";
  1552. bx::CrtFileWriter writer;
  1553. if (0 == writer.open(ofp.c_str() ) )
  1554. {
  1555. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1556. writer.close();
  1557. }
  1558. }
  1559. }
  1560. }
  1561. }
  1562. }
  1563. delete [] data;
  1564. }
  1565. if (compiled)
  1566. {
  1567. return EXIT_SUCCESS;
  1568. }
  1569. remove(outFilePath);
  1570. fprintf(stderr, "Failed to build shader.\n");
  1571. return EXIT_FAILURE;
  1572. }