shaderc.cpp 46 KB

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