shaderc.cpp 46 KB

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