shaderc.cpp 58 KB

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