shaderc.cpp 66 KB

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