shaderc.cpp 41 KB

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