shaderc.cpp 59 KB

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