shaderc.cpp 48 KB

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