shaderc.cpp 42 KB

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