shaderc.cpp 42 KB

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