shaderc.cpp 72 KB

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