shaderc.cpp 63 KB

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