2
0

shaderc.cpp 41 KB

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