shaderc.cpp 41 KB

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