2
0

shaderc.cpp 59 KB

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