shaderc.cpp 71 KB

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