shaderc.cpp 63 KB

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