shaderc.cpp 63 KB

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