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