shaderc.cpp 61 KB

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