shaderc.cpp 59 KB

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