shaderc.cpp 63 KB

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