shaderc.cpp 48 KB

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