shaderc.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871
  1. /*
  2. * Copyright 2011-2023 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, bx::WriterI* _messageWriter)
  629. : m_tagptr(m_tags)
  630. , m_scratchPos(0)
  631. , m_fgetsPos(0)
  632. , m_messageWriter(_messageWriter)
  633. {
  634. m_tagptr->tag = FPPTAG_USERDATA;
  635. m_tagptr->data = this;
  636. m_tagptr++;
  637. m_tagptr->tag = FPPTAG_DEPENDS;
  638. m_tagptr->data = (void*)fppDepends;
  639. m_tagptr++;
  640. m_tagptr->tag = FPPTAG_INPUT;
  641. m_tagptr->data = (void*)fppInput;
  642. m_tagptr++;
  643. m_tagptr->tag = FPPTAG_OUTPUT;
  644. m_tagptr->data = (void*)fppOutput;
  645. m_tagptr++;
  646. m_tagptr->tag = FPPTAG_ERROR;
  647. m_tagptr->data = (void*)fppError;
  648. m_tagptr++;
  649. m_tagptr->tag = FPPTAG_SHOWVERSION;
  650. m_tagptr->data = (void*)0;
  651. m_tagptr++;
  652. m_tagptr->tag = FPPTAG_LINE;
  653. m_tagptr->data = (void*)0;
  654. m_tagptr++;
  655. m_tagptr->tag = FPPTAG_INPUT_NAME;
  656. m_tagptr->data = scratch(_filePath);
  657. m_tagptr++;
  658. if (!_essl)
  659. {
  660. m_default = "#define lowp\n#define mediump\n#define highp\n";
  661. }
  662. }
  663. void setDefine(const char* _define)
  664. {
  665. m_tagptr->tag = FPPTAG_DEFINE;
  666. m_tagptr->data = scratch(_define);
  667. m_tagptr++;
  668. }
  669. void setDefaultDefine(const char* _name)
  670. {
  671. char temp[1024];
  672. bx::snprintf(temp, BX_COUNTOF(temp)
  673. , "#ifndef %s\n"
  674. "# define %s 0\n"
  675. "#endif // %s\n"
  676. "\n"
  677. , _name
  678. , _name
  679. , _name
  680. );
  681. m_default += temp;
  682. }
  683. void writef(const char* _format, ...)
  684. {
  685. va_list argList;
  686. va_start(argList, _format);
  687. bx::stringPrintfVargs(m_default, _format, argList);
  688. va_end(argList);
  689. }
  690. void addInclude(const char* _includeDir)
  691. {
  692. char* start = scratch(_includeDir);
  693. for (bx::StringView split = bx::strFind(start, ';')
  694. ; !split.isEmpty()
  695. ; split = bx::strFind(start, ';')
  696. )
  697. {
  698. *const_cast<char*>(split.getPtr() ) = '\0';
  699. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  700. m_tagptr->data = start;
  701. m_tagptr++;
  702. start = const_cast<char*>(split.getPtr() ) + 1;
  703. }
  704. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  705. m_tagptr->data = start;
  706. m_tagptr++;
  707. }
  708. void addDependency(const char* _fileName)
  709. {
  710. m_depends += " \\\n ";
  711. m_depends += _fileName;
  712. }
  713. bool run(const char* _input)
  714. {
  715. m_fgetsPos = 0;
  716. m_preprocessed.clear();
  717. m_input = m_default;
  718. m_input += "\n\n";
  719. int32_t len = bx::strLen(_input)+1;
  720. char* temp = new char[len];
  721. bx::StringView normalized = bx::normalizeEolLf(temp, len, _input);
  722. std::string str;
  723. str.assign(normalized.getPtr(), normalized.getTerm() );
  724. m_input += str;
  725. delete [] temp;
  726. fppTag* tagptr = m_tagptr;
  727. tagptr->tag = FPPTAG_END;
  728. tagptr->data = 0;
  729. tagptr++;
  730. int result = fppPreProcess(m_tags);
  731. return 0 == result;
  732. }
  733. char* fgets(char* _buffer, int _size)
  734. {
  735. int ii = 0;
  736. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  737. {
  738. _buffer[ii++] = ch;
  739. if (ch == '\n' || ii == _size)
  740. {
  741. _buffer[ii] = '\0';
  742. m_fgetsPos++;
  743. return _buffer;
  744. }
  745. }
  746. return NULL;
  747. }
  748. static void fppDepends(char* _fileName, void* _userData)
  749. {
  750. Preprocessor* thisClass = (Preprocessor*)_userData;
  751. thisClass->addDependency(_fileName);
  752. }
  753. static char* fppInput(char* _buffer, int _size, void* _userData)
  754. {
  755. Preprocessor* thisClass = (Preprocessor*)_userData;
  756. return thisClass->fgets(_buffer, _size);
  757. }
  758. static void fppOutput(int _ch, void* _userData)
  759. {
  760. Preprocessor* thisClass = (Preprocessor*)_userData;
  761. thisClass->m_preprocessed += char(_ch);
  762. }
  763. static void fppError(void* _userData, char* _format, va_list _vargs)
  764. {
  765. bx::ErrorAssert err;
  766. Preprocessor* thisClass = (Preprocessor*)_userData;
  767. bx::write(thisClass->m_messageWriter, _format, _vargs, &err);
  768. }
  769. char* scratch(const char* _str)
  770. {
  771. char* result = &m_scratch[m_scratchPos];
  772. bx::strCopy(result, uint32_t(sizeof(m_scratch)-m_scratchPos), _str);
  773. m_scratchPos += (uint32_t)bx::strLen(_str)+1;
  774. return result;
  775. }
  776. fppTag m_tags[MAX_TAGS];
  777. fppTag* m_tagptr;
  778. std::string m_depends;
  779. std::string m_default;
  780. std::string m_input;
  781. std::string m_preprocessed;
  782. char m_scratch[16<<10];
  783. uint32_t m_scratchPos;
  784. uint32_t m_fgetsPos;
  785. bx::WriterI* m_messageWriter;
  786. };
  787. typedef std::vector<std::string> InOut;
  788. uint32_t parseInOut(InOut& _inout, const bx::StringView& _str)
  789. {
  790. uint32_t hash = 0;
  791. bx::StringView str = bx::strLTrimSpace(_str);
  792. if (!str.isEmpty() )
  793. {
  794. bx::StringView delim;
  795. do
  796. {
  797. delim = bx::strFind(str, ',');
  798. if (delim.isEmpty() )
  799. {
  800. delim = bx::strFind(str, ' ');
  801. }
  802. const bx::StringView token(bx::strRTrim(bx::StringView(str.getPtr(), delim.getPtr() ), " ") );
  803. if (!token.isEmpty() )
  804. {
  805. _inout.push_back(std::string(token.getPtr(), token.getTerm() ) );
  806. str = bx::strLTrimSpace(bx::StringView(delim.getPtr() + 1, str.getTerm() ) );
  807. }
  808. }
  809. while (!delim.isEmpty() );
  810. std::sort(_inout.begin(), _inout.end() );
  811. bx::HashMurmur2A murmur;
  812. murmur.begin();
  813. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  814. {
  815. murmur.add(it->c_str(), (uint32_t)it->size() );
  816. }
  817. hash = murmur.end();
  818. }
  819. return hash;
  820. }
  821. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  822. {
  823. char find[32];
  824. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  825. char replace[32];
  826. bx::snprintf(replace, sizeof(replace), "bgfx_FragData%d", _idx);
  827. strReplace(_data, find, replace);
  828. _preprocessor.writef(
  829. " \\\n\t%sout vec4 bgfx_FragData%d : SV_TARGET%d"
  830. , _comma ? ", " : " "
  831. , _idx
  832. , _idx
  833. );
  834. }
  835. void voidFragData(char* _data, uint32_t _idx)
  836. {
  837. char find[32];
  838. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  839. strReplace(_data, find, "bgfx_VoidFrag");
  840. }
  841. bx::StringView baseName(const bx::StringView& _filePath)
  842. {
  843. bx::FilePath fp(_filePath);
  844. return bx::strFind(_filePath, fp.getBaseName() );
  845. }
  846. void help(const char* _error = NULL)
  847. {
  848. if (NULL != _error)
  849. {
  850. bx::printf("Error:\n%s\n\n", _error);
  851. }
  852. bx::printf(
  853. "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  854. "Copyright 2011-2023 Branimir Karadzic. All rights reserved.\n"
  855. "License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE\n\n"
  856. , BGFX_SHADERC_VERSION_MAJOR
  857. , BGFX_SHADERC_VERSION_MINOR
  858. , BGFX_API_VERSION
  859. );
  860. bx::printf(
  861. "Usage: shaderc -f <in> -o <out> --type <v/f/c> --platform <platform>\n"
  862. "\n"
  863. "Options:\n"
  864. " -h, --help Display this help and exit.\n"
  865. " -v, --version Output version information and exit.\n"
  866. " -f <file path> Input's file path.\n"
  867. " -i <include path> Include path. (for multiple paths use -i multiple times)\n"
  868. " -o <file path> Output's file path.\n"
  869. " --stdout Output to console.\n"
  870. " --bin2c [array name] Generate C header file. If array name is not specified base file name will be used as name.\n"
  871. " --depends Generate makefile style depends file.\n"
  872. " --platform <platform> Target platform.\n"
  873. " android\n"
  874. " asm.js\n"
  875. " ios\n"
  876. " linux\n"
  877. " orbis\n"
  878. " osx\n"
  879. " windows\n"
  880. " -p, --profile <profile> Shader model. Defaults to GLSL.\n"
  881. );
  882. {
  883. ShadingLang::Enum lang = ShadingLang::Count;
  884. for (uint32_t ii = 0; ii < BX_COUNTOF(s_profiles); ++ii)
  885. {
  886. const Profile& profile = s_profiles[ii];
  887. if (lang != profile.lang)
  888. {
  889. lang = profile.lang;
  890. bx::printf("\n");
  891. bx::printf(" %-20s %s\n", profile.name, getName(profile.lang) );
  892. }
  893. else
  894. {
  895. bx::printf(" %s\n", profile.name);
  896. }
  897. }
  898. }
  899. bx::printf(
  900. " --preprocess Only pre-process.\n"
  901. " --define <defines> Add defines to preprocessor. (Semicolon-separated)\n"
  902. " --raw Do not process shader. No preprocessor, and no glsl-optimizer. (GLSL only)\n"
  903. " --type <type> Shader type. Can be 'vertex', 'fragment, or 'compute'.\n"
  904. " --varyingdef <file path> varying.def.sc's file path.\n"
  905. " --verbose Be verbose.\n"
  906. "\n"
  907. "(DX9 and DX11 only):\n"
  908. "\n"
  909. " --debug Debug information.\n"
  910. " --disasm Disassemble compiled shader.\n"
  911. " -O <level> Set optimization level. Can be 0 to 3.\n"
  912. " --Werror Treat warnings as errors.\n"
  913. "\n"
  914. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  915. );
  916. }
  917. bx::StringView nextWord(bx::StringView& _parse)
  918. {
  919. bx::StringView word = bx::strWord(bx::strLTrimSpace(_parse) );
  920. _parse = bx::strLTrimSpace(bx::StringView(word.getTerm(), _parse.getTerm() ) );
  921. return word;
  922. }
  923. bool compileShader(const char* _varying, const char* _comment, char* _shader, uint32_t _shaderLen, Options& _options, bx::WriterI* _shaderWriter, bx::WriterI* _messageWriter)
  924. {
  925. bx::ErrorAssert messageErr;
  926. uint32_t profile_id = 0;
  927. const char* profile_opt = _options.profile.c_str();
  928. if ('\0' != profile_opt[0])
  929. {
  930. const uint32_t count = BX_COUNTOF(s_profiles);
  931. for (profile_id=0; profile_id<count; profile_id++ )
  932. {
  933. if (0 == bx::strCmp(profile_opt, s_profiles[profile_id].name) )
  934. {
  935. break;
  936. }
  937. else if (s_profiles[profile_id].lang == ShadingLang::HLSL
  938. && 0 == bx::strCmp(&profile_opt[1], s_profiles[profile_id].name) )
  939. {
  940. // This test is here to allow hlsl profile names e.g:
  941. // cs_4_0, gs_5_0, etc...
  942. // There's no check to ensure that the profile name matches the shader type set via the cli.
  943. // This means that you can pass `hs_5_0` when compiling a fragment shader.
  944. break;
  945. }
  946. }
  947. if (profile_id == count)
  948. {
  949. bx::write(_messageWriter, &messageErr, "Unknown profile: %s\n", profile_opt);
  950. return false;
  951. }
  952. }
  953. const Profile *profile = &s_profiles[profile_id];
  954. Preprocessor preprocessor(_options.inputFilePath.c_str(), profile->lang == ShadingLang::ESSL, _messageWriter);
  955. for (size_t ii = 0; ii < _options.includeDirs.size(); ++ii)
  956. {
  957. preprocessor.addInclude(_options.includeDirs[ii].c_str() );
  958. }
  959. for (size_t ii = 0; ii < _options.defines.size(); ++ii)
  960. {
  961. preprocessor.setDefine(_options.defines[ii].c_str() );
  962. }
  963. for (size_t ii = 0; ii < _options.dependencies.size(); ++ii)
  964. {
  965. preprocessor.addDependency(_options.dependencies[ii].c_str() );
  966. }
  967. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  968. preprocessor.setDefaultDefine("BX_PLATFORM_EMSCRIPTEN");
  969. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  970. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  971. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  972. preprocessor.setDefaultDefine("BX_PLATFORM_PS4");
  973. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  974. preprocessor.setDefaultDefine("BX_PLATFORM_XBOXONE");
  975. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  976. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  977. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_METAL");
  978. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_PSSL");
  979. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_SPIRV");
  980. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_COMPUTE");
  981. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  982. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  983. char glslDefine[128];
  984. if (profile->lang == ShadingLang::GLSL
  985. || profile->lang == ShadingLang::ESSL)
  986. {
  987. bx::snprintf(glslDefine, BX_COUNTOF(glslDefine)
  988. , "BGFX_SHADER_LANGUAGE_GLSL=%d"
  989. , profile->id
  990. );
  991. }
  992. char hlslDefine[128];
  993. if (profile->lang == ShadingLang::HLSL)
  994. {
  995. bx::snprintf(hlslDefine, BX_COUNTOF(hlslDefine)
  996. , "BGFX_SHADER_LANGUAGE_HLSL=%d"
  997. , profile->id);
  998. }
  999. const char* platform = _options.platform.c_str();
  1000. if (0 == bx::strCmpI(platform, "android") )
  1001. {
  1002. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  1003. if (profile->lang == ShadingLang::SpirV)
  1004. {
  1005. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  1006. }
  1007. else
  1008. {
  1009. preprocessor.setDefine(glslDefine);
  1010. }
  1011. }
  1012. else if (0 == bx::strCmpI(platform, "asm.js") )
  1013. {
  1014. preprocessor.setDefine("BX_PLATFORM_EMSCRIPTEN=1");
  1015. preprocessor.setDefine(glslDefine);
  1016. }
  1017. else if (0 == bx::strCmpI(platform, "ios") )
  1018. {
  1019. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1020. if (profile->lang == ShadingLang::Metal)
  1021. {
  1022. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_METAL=1");
  1023. }
  1024. else
  1025. {
  1026. preprocessor.setDefine(glslDefine);
  1027. }
  1028. }
  1029. else if (0 == bx::strCmpI(platform, "linux") )
  1030. {
  1031. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  1032. if (profile->lang == ShadingLang::SpirV)
  1033. {
  1034. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  1035. }
  1036. else
  1037. {
  1038. preprocessor.setDefine(glslDefine);
  1039. }
  1040. }
  1041. else if (0 == bx::strCmpI(platform, "osx") )
  1042. {
  1043. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  1044. if (profile->lang != ShadingLang::Metal)
  1045. {
  1046. preprocessor.setDefine(glslDefine);
  1047. }
  1048. char temp[256];
  1049. bx::snprintf(
  1050. temp
  1051. , sizeof(temp)
  1052. , "BGFX_SHADER_LANGUAGE_METAL=%d"
  1053. , (profile->lang == ShadingLang::Metal) ? profile->id : 0
  1054. );
  1055. preprocessor.setDefine(temp);
  1056. }
  1057. else if (0 == bx::strCmpI(platform, "windows") )
  1058. {
  1059. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  1060. if (profile->lang == ShadingLang::HLSL)
  1061. {
  1062. preprocessor.setDefine(hlslDefine);
  1063. }
  1064. else if (profile->lang == ShadingLang::GLSL
  1065. || profile->lang == ShadingLang::ESSL)
  1066. {
  1067. preprocessor.setDefine(glslDefine);
  1068. }
  1069. else if (profile->lang == ShadingLang::SpirV)
  1070. {
  1071. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  1072. }
  1073. }
  1074. else if (0 == bx::strCmpI(platform, "orbis") )
  1075. {
  1076. preprocessor.setDefine("BX_PLATFORM_PS4=1");
  1077. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_PSSL=1");
  1078. preprocessor.setDefine("lit=lit_reserved");
  1079. }
  1080. else
  1081. {
  1082. if (profile->lang == ShadingLang::HLSL)
  1083. {
  1084. preprocessor.setDefine(hlslDefine);
  1085. }
  1086. else if (profile->lang == ShadingLang::GLSL
  1087. || profile->lang == ShadingLang::ESSL)
  1088. {
  1089. preprocessor.setDefine(glslDefine);
  1090. }
  1091. else if (profile->lang == ShadingLang::SpirV)
  1092. {
  1093. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  1094. }
  1095. }
  1096. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  1097. switch (_options.shaderType)
  1098. {
  1099. case 'c':
  1100. preprocessor.setDefine("BGFX_SHADER_TYPE_COMPUTE=1");
  1101. break;
  1102. case 'f':
  1103. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1104. break;
  1105. case 'v':
  1106. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1107. break;
  1108. default:
  1109. bx::write(_messageWriter, &messageErr, "Unknown type: %c?!", _options.shaderType);
  1110. return false;
  1111. }
  1112. bool compiled = false;
  1113. VaryingMap varyingMap;
  1114. bx::StringView parse(_varying);
  1115. bx::StringView term(parse);
  1116. bool usesInterpolationQualifiers = false;
  1117. while (!parse.isEmpty() )
  1118. {
  1119. parse = bx::strLTrimSpace(parse);
  1120. bx::StringView eol = bx::strFind(parse, ';');
  1121. if (eol.isEmpty() )
  1122. {
  1123. eol = bx::strFindEol(parse);
  1124. }
  1125. if (!eol.isEmpty() )
  1126. {
  1127. eol.set(eol.getPtr() + 1, parse.getTerm() );
  1128. bx::StringView precision;
  1129. bx::StringView interpolation;
  1130. bx::StringView typen = nextWord(parse);
  1131. if (0 == bx::strCmp(typen, "lowp", 4)
  1132. || 0 == bx::strCmp(typen, "mediump", 7)
  1133. || 0 == bx::strCmp(typen, "highp", 5) )
  1134. {
  1135. precision = typen;
  1136. typen = nextWord(parse);
  1137. }
  1138. if (0 == bx::strCmp(typen, "flat", 4)
  1139. || 0 == bx::strCmp(typen, "smooth", 6)
  1140. || 0 == bx::strCmp(typen, "noperspective", 13)
  1141. || 0 == bx::strCmp(typen, "centroid", 8) )
  1142. {
  1143. if ('f' == _options.shaderType
  1144. || profile->lang == ShadingLang::GLSL
  1145. || profile->lang == ShadingLang::ESSL)
  1146. {
  1147. interpolation = typen;
  1148. usesInterpolationQualifiers = true;
  1149. }
  1150. typen = nextWord(parse);
  1151. }
  1152. bx::StringView name = nextWord(parse);
  1153. bx::StringView column = bx::strSubstr(parse, 0, 1);
  1154. bx::StringView semantics;
  1155. if (0 == bx::strCmp(column, ":", 1) )
  1156. {
  1157. parse = bx::strLTrimSpace(bx::StringView(parse.getPtr() + 1, parse.getTerm() ) );
  1158. semantics = nextWord(parse);
  1159. }
  1160. bx::StringView assign = bx::strSubstr(parse, 0, 1);
  1161. bx::StringView init;
  1162. if (0 == bx::strCmp(assign, "=", 1))
  1163. {
  1164. parse = bx::strLTrimSpace(bx::StringView(parse.getPtr() + 1, parse.getTerm() ) );
  1165. init.set(parse.getPtr(), eol.getPtr() );
  1166. }
  1167. if (!typen.isEmpty()
  1168. && !name.isEmpty()
  1169. && !semantics.isEmpty() )
  1170. {
  1171. Varying var;
  1172. if (!precision.isEmpty() )
  1173. {
  1174. var.m_precision.assign(precision.getPtr(), precision.getTerm() );
  1175. }
  1176. if (!interpolation.isEmpty() )
  1177. {
  1178. var.m_interpolation.assign(interpolation.getPtr(), interpolation.getTerm() );
  1179. }
  1180. var.m_type.assign(typen.getPtr(), typen.getTerm() );
  1181. var.m_name.assign(name.getPtr(), name.getTerm() );
  1182. var.m_semantics.assign(semantics.getPtr(), semantics.getTerm() );
  1183. if (profile->lang == ShadingLang::HLSL
  1184. && profile->id < 400
  1185. && var.m_semantics == "BITANGENT")
  1186. {
  1187. var.m_semantics = "BINORMAL";
  1188. }
  1189. if (!init.isEmpty() )
  1190. {
  1191. var.m_init.assign(init.getPtr(), init.getTerm() );
  1192. }
  1193. varyingMap.insert(std::make_pair(var.m_name, var) );
  1194. }
  1195. parse = bx::strLTrimSpace(bx::strFindNl(bx::StringView(eol.getPtr(), term.getTerm() ) ) );
  1196. }
  1197. }
  1198. bool raw = _options.raw;
  1199. InOut shaderInputs;
  1200. InOut shaderOutputs;
  1201. uint32_t inputHash = 0;
  1202. uint32_t outputHash = 0;
  1203. bx::ErrorAssert err;
  1204. char* data;
  1205. char* input;
  1206. {
  1207. data = _shader;
  1208. uint32_t size = _shaderLen;
  1209. const size_t padding = 16384;
  1210. if (!raw)
  1211. {
  1212. // To avoid commented code being recognized as used feature,
  1213. // first preprocess pass is used to strip all comments before
  1214. // substituting code.
  1215. bool ok = preprocessor.run(data);
  1216. delete [] data;
  1217. if (!ok)
  1218. {
  1219. return false;
  1220. }
  1221. size = (uint32_t)preprocessor.m_preprocessed.size();
  1222. data = new char[size+padding+1];
  1223. bx::memCopy(data, preprocessor.m_preprocessed.c_str(), size);
  1224. bx::memSet(&data[size], 0, padding+1);
  1225. }
  1226. strNormalizeEol(data);
  1227. input = const_cast<char*>(bx::strLTrimSpace(data).getPtr() );
  1228. while (input[0] == '$')
  1229. {
  1230. bx::StringView str = bx::strLTrimSpace(input+1);
  1231. bx::StringView eol = bx::strFindEol(str);
  1232. bx::StringView nl = bx::strFindNl(eol);
  1233. input = const_cast<char*>(nl.getPtr() );
  1234. if (0 == bx::strCmp(str, "input", 5) )
  1235. {
  1236. str = bx::StringView(str.getPtr() + 5, str.getTerm() );
  1237. bx::StringView comment = bx::strFind(str, "//");
  1238. eol = !comment.isEmpty() && comment.getPtr() < eol.getPtr() ? comment.getPtr() : eol;
  1239. inputHash = parseInOut(shaderInputs, bx::StringView(str.getPtr(), eol.getPtr() ) );
  1240. }
  1241. else if (0 == bx::strCmp(str, "output", 6) )
  1242. {
  1243. str = bx::StringView(str.getPtr() + 6, str.getTerm() );
  1244. bx::StringView comment = bx::strFind(str, "//");
  1245. eol = !comment.isEmpty() && comment.getPtr() < eol.getPtr() ? comment.getPtr() : eol;
  1246. outputHash = parseInOut(shaderOutputs, bx::StringView(str.getPtr(), eol.getPtr() ) );
  1247. }
  1248. else if (0 == bx::strCmp(str, "raw", 3) )
  1249. {
  1250. raw = true;
  1251. str = bx::StringView(str.getPtr() + 3, str.getTerm() );
  1252. }
  1253. input = const_cast<char*>(bx::strLTrimSpace(input).getPtr() );
  1254. }
  1255. }
  1256. bool invalidShaderAttribute = false;
  1257. if ('v' == _options.shaderType)
  1258. {
  1259. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1260. {
  1261. if (bx::findIdentifierMatch(it->c_str(), s_allowedVertexShaderInputs).isEmpty() )
  1262. {
  1263. invalidShaderAttribute = true;
  1264. bx::write(_messageWriter, &messageErr,
  1265. "Invalid vertex shader input attribute '%s'.\n"
  1266. "\n"
  1267. "Valid input attributes:\n"
  1268. " a_position, a_normal, a_tangent, a_bitangent, a_color0, a_color1, a_color2, a_color3, a_indices, a_weight,\n"
  1269. " a_texcoord0, a_texcoord1, a_texcoord2, a_texcoord3, a_texcoord4, a_texcoord5, a_texcoord6, a_texcoord7,\n"
  1270. " i_data0, i_data1, i_data2, i_data3, i_data4.\n"
  1271. "\n"
  1272. , it->c_str() );
  1273. break;
  1274. }
  1275. }
  1276. }
  1277. if (invalidShaderAttribute)
  1278. {
  1279. }
  1280. else if (raw)
  1281. {
  1282. if ('f' == _options.shaderType)
  1283. {
  1284. bx::write(_shaderWriter, BGFX_CHUNK_MAGIC_FSH, &err);
  1285. }
  1286. else if ('v' == _options.shaderType)
  1287. {
  1288. bx::write(_shaderWriter, BGFX_CHUNK_MAGIC_VSH, &err);
  1289. }
  1290. else
  1291. {
  1292. bx::write(_shaderWriter, BGFX_CHUNK_MAGIC_CSH, &err);
  1293. }
  1294. bx::write(_shaderWriter, inputHash, &err);
  1295. bx::write(_shaderWriter, outputHash, &err);
  1296. }
  1297. if (raw)
  1298. {
  1299. if (profile->lang == ShadingLang::GLSL)
  1300. {
  1301. bx::write(_shaderWriter, uint16_t(0), &err);
  1302. uint32_t shaderSize = (uint32_t)bx::strLen(input);
  1303. bx::write(_shaderWriter, shaderSize, &err);
  1304. bx::write(_shaderWriter, input, shaderSize, &err);
  1305. bx::write(_shaderWriter, uint8_t(0), &err);
  1306. compiled = true;
  1307. }
  1308. else if (profile->lang == ShadingLang::Metal)
  1309. {
  1310. compiled = compileMetalShader(_options, BX_MAKEFOURCC('M', 'T', 'L', 0), input, _shaderWriter, _messageWriter);
  1311. }
  1312. else if (profile->lang == ShadingLang::SpirV)
  1313. {
  1314. compiled = compileSPIRVShader(_options, profile->id, input, _shaderWriter, _messageWriter);
  1315. }
  1316. else if (profile->lang == ShadingLang::PSSL)
  1317. {
  1318. compiled = compilePSSLShader(_options, 0, input, _shaderWriter, _messageWriter);
  1319. }
  1320. else
  1321. {
  1322. compiled = compileHLSLShader(_options, profile->id, input, _shaderWriter, _messageWriter);
  1323. }
  1324. }
  1325. else if ('c' == _options.shaderType) // Compute
  1326. {
  1327. bx::StringView entry = bx::strFind(input, "void main()");
  1328. if (entry.isEmpty() )
  1329. {
  1330. bx::write(_messageWriter, &messageErr, "Shader entry point 'void main()' is not found.\n");
  1331. }
  1332. else
  1333. {
  1334. if (profile->lang == ShadingLang::GLSL
  1335. || profile->lang == ShadingLang::ESSL)
  1336. {
  1337. }
  1338. else
  1339. {
  1340. if (profile->lang != ShadingLang::PSSL)
  1341. {
  1342. preprocessor.writef(getPsslPreamble() );
  1343. }
  1344. preprocessor.writef(
  1345. "#define lowp\n"
  1346. "#define mediump\n"
  1347. "#define highp\n"
  1348. "#define ivec2 int2\n"
  1349. "#define ivec3 int3\n"
  1350. "#define ivec4 int4\n"
  1351. "#define uvec2 uint2\n"
  1352. "#define uvec3 uint3\n"
  1353. "#define uvec4 uint4\n"
  1354. "#define vec2 float2\n"
  1355. "#define vec3 float3\n"
  1356. "#define vec4 float4\n"
  1357. "#define mat2 float2x2\n"
  1358. "#define mat3 float3x3\n"
  1359. "#define mat4 float4x4\n"
  1360. );
  1361. *const_cast<char*>(entry.getPtr() + 4) = '_';
  1362. preprocessor.writef("#define void_main()");
  1363. preprocessor.writef(" \\\n\tvoid main(");
  1364. uint32_t arg = 0;
  1365. const bool hasLocalInvocationID = !bx::strFind(input, "gl_LocalInvocationID").isEmpty();
  1366. const bool hasLocalInvocationIndex = !bx::strFind(input, "gl_LocalInvocationIndex").isEmpty();
  1367. const bool hasGlobalInvocationID = !bx::strFind(input, "gl_GlobalInvocationID").isEmpty();
  1368. const bool hasWorkGroupID = !bx::strFind(input, "gl_WorkGroupID").isEmpty();
  1369. if (hasLocalInvocationID)
  1370. {
  1371. preprocessor.writef(
  1372. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1373. , arg++ > 0 ? ", " : " "
  1374. );
  1375. }
  1376. if (hasLocalInvocationIndex)
  1377. {
  1378. preprocessor.writef(
  1379. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1380. , arg++ > 0 ? ", " : " "
  1381. );
  1382. }
  1383. if (hasGlobalInvocationID)
  1384. {
  1385. preprocessor.writef(
  1386. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1387. , arg++ > 0 ? ", " : " "
  1388. );
  1389. }
  1390. if (hasWorkGroupID)
  1391. {
  1392. preprocessor.writef(
  1393. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1394. , arg++ > 0 ? ", " : " "
  1395. );
  1396. }
  1397. preprocessor.writef(
  1398. " \\\n\t)\n"
  1399. );
  1400. }
  1401. if (preprocessor.run(input) )
  1402. {
  1403. if (_options.preprocessOnly)
  1404. {
  1405. bx::write(
  1406. _shaderWriter
  1407. , preprocessor.m_preprocessed.c_str()
  1408. , (int32_t)preprocessor.m_preprocessed.size()
  1409. , &err
  1410. );
  1411. return true;
  1412. }
  1413. {
  1414. std::string code;
  1415. bx::write(_shaderWriter, BGFX_CHUNK_MAGIC_CSH, &err);
  1416. bx::write(_shaderWriter, uint32_t(0), &err);
  1417. bx::write(_shaderWriter, outputHash, &err);
  1418. if (profile->lang == ShadingLang::GLSL
  1419. || profile->lang == ShadingLang::ESSL)
  1420. {
  1421. if (profile->lang == ShadingLang::ESSL)
  1422. {
  1423. bx::stringPrintf(code, "#version 310 es\n");
  1424. }
  1425. else
  1426. {
  1427. bx::stringPrintf(
  1428. code
  1429. , "#version %d\n"
  1430. , (profile->lang != ShadingLang::GLSL) ? 430 : profile->id
  1431. );
  1432. }
  1433. code += preprocessor.m_preprocessed;
  1434. bx::write(_shaderWriter, uint16_t(0), &err);
  1435. uint32_t shaderSize = (uint32_t)code.size();
  1436. bx::write(_shaderWriter, shaderSize, &err);
  1437. bx::write(_shaderWriter, code.c_str(), shaderSize, &err);
  1438. bx::write(_shaderWriter, uint8_t(0), &err);
  1439. compiled = true;
  1440. }
  1441. else
  1442. {
  1443. code += _comment;
  1444. code += preprocessor.m_preprocessed;
  1445. if (profile->lang == ShadingLang::Metal)
  1446. {
  1447. compiled = compileMetalShader(_options, BX_MAKEFOURCC('M', 'T', 'L', 0), code, _shaderWriter, _messageWriter);
  1448. }
  1449. else if (profile->lang == ShadingLang::SpirV)
  1450. {
  1451. compiled = compileSPIRVShader(_options, profile->id, code, _shaderWriter, _messageWriter);
  1452. }
  1453. else if (profile->lang == ShadingLang::PSSL)
  1454. {
  1455. compiled = compilePSSLShader(_options, 0, code, _shaderWriter, _messageWriter);
  1456. }
  1457. else
  1458. {
  1459. compiled = compileHLSLShader(_options, profile->id, code, _shaderWriter, _messageWriter);
  1460. }
  1461. }
  1462. }
  1463. if (compiled)
  1464. {
  1465. if (_options.depends)
  1466. {
  1467. std::string ofp = _options.outputFilePath;
  1468. ofp += ".d";
  1469. bx::FileWriter writer;
  1470. if (bx::open(&writer, ofp.c_str() ) )
  1471. {
  1472. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  1473. bx::close(&writer);
  1474. }
  1475. }
  1476. }
  1477. }
  1478. }
  1479. }
  1480. else // Vertex/Fragment
  1481. {
  1482. bx::StringView shader(input);
  1483. bx::StringView entry = bx::strFind(shader, "void main()");
  1484. if (entry.isEmpty() )
  1485. {
  1486. bx::write(_messageWriter, &messageErr, "Shader entry point 'void main()' is not found.\n");
  1487. }
  1488. else
  1489. {
  1490. if (profile->lang == ShadingLang::GLSL
  1491. || profile->lang == ShadingLang::ESSL)
  1492. {
  1493. if (profile->lang != ShadingLang::ESSL)
  1494. {
  1495. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1496. // not as GLSL language 1.2 specs shadow2D/Proj.
  1497. preprocessor.writef(
  1498. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1499. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1500. );
  1501. }
  1502. // gl_FragColor and gl_FragData are deprecated for essl > 300
  1503. if (profile->lang == ShadingLang::ESSL
  1504. && profile->id >= 300)
  1505. {
  1506. const bool hasFragColor = !bx::strFind(input, "gl_FragColor").isEmpty();
  1507. bool hasFragData[8] = {};
  1508. uint32_t numFragData = 0;
  1509. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1510. {
  1511. char temp[32];
  1512. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  1513. hasFragData[ii] = !bx::strFind(input, temp).isEmpty();
  1514. numFragData += hasFragData[ii];
  1515. }
  1516. if (hasFragColor)
  1517. {
  1518. preprocessor.writef("#define gl_FragColor bgfx_FragColor\n");
  1519. preprocessor.writef("out mediump vec4 bgfx_FragColor;\n");
  1520. }
  1521. else if (numFragData)
  1522. {
  1523. preprocessor.writef("#define gl_FragData bgfx_FragData\n");
  1524. preprocessor.writef("out mediump vec4 bgfx_FragData[gl_MaxDrawBuffers];\n");
  1525. }
  1526. }
  1527. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1528. {
  1529. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1530. if (varyingIt != varyingMap.end() )
  1531. {
  1532. const Varying& var = varyingIt->second;
  1533. const char* name = var.m_name.c_str();
  1534. if (0 == bx::strCmp(name, "a_", 2)
  1535. || 0 == bx::strCmp(name, "i_", 2) )
  1536. {
  1537. preprocessor.writef(
  1538. "attribute %s %s %s %s;\n"
  1539. , var.m_precision.c_str()
  1540. , var.m_interpolation.c_str()
  1541. , var.m_type.c_str()
  1542. , name
  1543. );
  1544. }
  1545. else
  1546. {
  1547. preprocessor.writef(
  1548. "%s varying %s %s %s;\n"
  1549. , var.m_interpolation.c_str()
  1550. , var.m_precision.c_str()
  1551. , var.m_type.c_str()
  1552. , name
  1553. );
  1554. }
  1555. }
  1556. }
  1557. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1558. {
  1559. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1560. if (varyingIt != varyingMap.end() )
  1561. {
  1562. const Varying& var = varyingIt->second;
  1563. preprocessor.writef("%s varying %s %s;\n"
  1564. , var.m_interpolation.c_str()
  1565. , var.m_type.c_str()
  1566. , var.m_name.c_str()
  1567. );
  1568. }
  1569. }
  1570. }
  1571. else
  1572. {
  1573. if (profile->lang == ShadingLang::PSSL)
  1574. {
  1575. preprocessor.writef(getPsslPreamble() );
  1576. }
  1577. preprocessor.writef(
  1578. "#define lowp\n"
  1579. "#define mediump\n"
  1580. "#define highp\n"
  1581. "#define ivec2 int2\n"
  1582. "#define ivec3 int3\n"
  1583. "#define ivec4 int4\n"
  1584. "#define uvec2 uint2\n"
  1585. "#define uvec3 uint3\n"
  1586. "#define uvec4 uint4\n"
  1587. "#define vec2 float2\n"
  1588. "#define vec3 float3\n"
  1589. "#define vec4 float4\n"
  1590. "#define mat2 float2x2\n"
  1591. "#define mat3 float3x3\n"
  1592. "#define mat4 float4x4\n"
  1593. );
  1594. if (profile->lang == ShadingLang::HLSL
  1595. && profile->id < 400)
  1596. {
  1597. preprocessor.writef(
  1598. "#define centroid\n"
  1599. "#define flat\n"
  1600. "#define noperspective\n"
  1601. "#define smooth\n"
  1602. );
  1603. }
  1604. *const_cast<char*>(entry.getPtr() + 4) = '_';
  1605. if ('f' == _options.shaderType)
  1606. {
  1607. bx::StringView insert = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1608. if (!insert.isEmpty() )
  1609. {
  1610. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\nvec4 bgfx_VoidFrag = vec4_splat(0.0);\n");
  1611. }
  1612. const bool hasFragColor = !bx::strFind(input, "gl_FragColor").isEmpty();
  1613. const bool hasFragCoord = !bx::strFind(input, "gl_FragCoord").isEmpty() || profile->id >= 400;
  1614. const bool hasFragDepth = !bx::strFind(input, "gl_FragDepth").isEmpty();
  1615. const bool hasFrontFacing = !bx::strFind(input, "gl_FrontFacing").isEmpty();
  1616. const bool hasPrimitiveId = !bx::strFind(input, "gl_PrimitiveID").isEmpty();
  1617. bool hasFragData[8] = {};
  1618. uint32_t numFragData = 0;
  1619. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1620. {
  1621. char temp[32];
  1622. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  1623. hasFragData[ii] = !bx::strFind(input, temp).isEmpty();
  1624. numFragData += hasFragData[ii];
  1625. }
  1626. if (0 == numFragData)
  1627. {
  1628. // GL errors when both gl_FragColor and gl_FragData is used.
  1629. // This will trigger the same error with HLSL compiler too.
  1630. preprocessor.writef("#define gl_FragColor bgfx_FragData0\n");
  1631. // If it has gl_FragData or gl_FragColor, color target at
  1632. // index 0 exists, otherwise shader is not modifying color
  1633. // targets.
  1634. hasFragData[0] |= hasFragColor || profile->id < 400;
  1635. if (!insert.isEmpty()
  1636. && profile->id < 400
  1637. && !hasFragColor)
  1638. {
  1639. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\ngl_FragColor = bgfx_VoidFrag;\n");
  1640. }
  1641. }
  1642. preprocessor.writef("#define void_main()");
  1643. preprocessor.writef(" \\\n\tvoid main(");
  1644. uint32_t arg = 0;
  1645. if (hasFragCoord)
  1646. {
  1647. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1648. ++arg;
  1649. }
  1650. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1651. {
  1652. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1653. if (varyingIt != varyingMap.end() )
  1654. {
  1655. const Varying& var = varyingIt->second;
  1656. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  1657. , arg++ > 0 ? ", " : " "
  1658. , interpolationDx11(var.m_interpolation.c_str() )
  1659. , var.m_type.c_str()
  1660. , var.m_name.c_str()
  1661. , var.m_semantics.c_str()
  1662. );
  1663. }
  1664. }
  1665. const uint32_t maxRT = profile->id >= 400 ? BX_COUNTOF(hasFragData) : 4;
  1666. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1667. {
  1668. if (ii < maxRT)
  1669. {
  1670. if (hasFragData[ii])
  1671. {
  1672. addFragData(preprocessor, input, ii, arg++ > 0);
  1673. }
  1674. }
  1675. else
  1676. {
  1677. voidFragData(input, ii);
  1678. }
  1679. }
  1680. if (hasFragDepth)
  1681. {
  1682. preprocessor.writef(
  1683. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1684. , arg++ > 0 ? ", " : " "
  1685. );
  1686. }
  1687. if (hasFrontFacing)
  1688. {
  1689. if (profile->id < 400)
  1690. {
  1691. preprocessor.writef(
  1692. " \\\n\t%sfloat __vface : VFACE"
  1693. , arg++ > 0 ? ", " : " "
  1694. );
  1695. }
  1696. else
  1697. {
  1698. preprocessor.writef(
  1699. " \\\n\t%sbool gl_FrontFacing : SV_IsFrontFace"
  1700. , arg++ > 0 ? ", " : " "
  1701. );
  1702. }
  1703. }
  1704. if (hasPrimitiveId)
  1705. {
  1706. if (profile->id >= 400)
  1707. {
  1708. preprocessor.writef(
  1709. " \\\n\t%suint gl_PrimitiveID : SV_PrimitiveID"
  1710. , arg++ > 0 ? ", " : " "
  1711. );
  1712. }
  1713. else
  1714. {
  1715. bx::write(_messageWriter, &messageErr, "gl_PrimitiveID builtin is not supported by D3D9 HLSL.\n");
  1716. return false;
  1717. }
  1718. }
  1719. preprocessor.writef(
  1720. " \\\n\t)\n"
  1721. );
  1722. if (hasFrontFacing)
  1723. {
  1724. if (profile->id < 400)
  1725. {
  1726. preprocessor.writef(
  1727. "#define gl_FrontFacing (__vface >= 0.0)\n"
  1728. );
  1729. }
  1730. }
  1731. }
  1732. else if ('v' == _options.shaderType)
  1733. {
  1734. const bool hasVertexId = !bx::strFind(input, "gl_VertexID").isEmpty();
  1735. const bool hasInstanceId = !bx::strFind(input, "gl_InstanceID").isEmpty();
  1736. const bool hasViewportId = !bx::strFind(input, "gl_ViewportIndex").isEmpty();
  1737. const bool hasLayerId = !bx::strFind(input, "gl_Layer").isEmpty();
  1738. bx::StringView brace = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1739. if (!brace.isEmpty() )
  1740. {
  1741. bx::StringView block = bx::strFindBlock(bx::StringView(brace.getPtr(), shader.getTerm() ), '{', '}');
  1742. if (!block.isEmpty() )
  1743. {
  1744. strInsert(const_cast<char*>(block.getTerm()-1), "__RETURN__;\n");
  1745. }
  1746. }
  1747. preprocessor.writef(
  1748. "struct Output\n"
  1749. "{\n"
  1750. "\tvec4 gl_Position : SV_POSITION;\n"
  1751. "#define gl_Position _varying_.gl_Position\n"
  1752. );
  1753. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1754. {
  1755. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1756. if (varyingIt != varyingMap.end() )
  1757. {
  1758. const Varying& var = varyingIt->second;
  1759. preprocessor.writef(
  1760. "\t%s %s %s : %s;\n"
  1761. , interpolationDx11(var.m_interpolation.c_str() )
  1762. , var.m_type.c_str()
  1763. , var.m_name.c_str()
  1764. , var.m_semantics.c_str()
  1765. );
  1766. preprocessor.writef(
  1767. "#define %s _varying_.%s\n"
  1768. , var.m_name.c_str()
  1769. , var.m_name.c_str()
  1770. );
  1771. }
  1772. }
  1773. if (hasViewportId)
  1774. {
  1775. if (profile->id >= 400)
  1776. {
  1777. preprocessor.writef(
  1778. "\tuint gl_ViewportIndex : SV_ViewportArrayIndex;\n"
  1779. "#define gl_ViewportIndex _varying_.gl_ViewportIndex\n"
  1780. );
  1781. }
  1782. else
  1783. {
  1784. bx::write(_messageWriter, &messageErr, "gl_ViewportIndex builtin is not supported by D3D9 HLSL.\n");
  1785. return false;
  1786. }
  1787. }
  1788. if (hasLayerId)
  1789. {
  1790. if (profile->id >= 400)
  1791. {
  1792. preprocessor.writef(
  1793. "\tuint gl_Layer : SV_RenderTargetArrayIndex;\n"
  1794. "#define gl_Layer _varying_.gl_Layer\n"
  1795. );
  1796. }
  1797. else
  1798. {
  1799. bx::write(_messageWriter, &messageErr, "gl_Layer builtin is not supported by D3D9 HLSL.\n");
  1800. return false;
  1801. }
  1802. }
  1803. preprocessor.writef(
  1804. "};\n"
  1805. );
  1806. preprocessor.writef("#define void_main() \\\n");
  1807. preprocessor.writef("Output main(");
  1808. uint32_t arg = 0;
  1809. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1810. {
  1811. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1812. if (varyingIt != varyingMap.end() )
  1813. {
  1814. const Varying& var = varyingIt->second;
  1815. preprocessor.writef(
  1816. " \\\n\t%s%s %s : %s"
  1817. , arg++ > 0 ? ", " : ""
  1818. , var.m_type.c_str()
  1819. , var.m_name.c_str()
  1820. , var.m_semantics.c_str()
  1821. );
  1822. }
  1823. }
  1824. if (hasVertexId)
  1825. {
  1826. if (profile->id >= 400)
  1827. {
  1828. preprocessor.writef(
  1829. " \\\n\t%suint gl_VertexID : SV_VertexID"
  1830. , arg++ > 0 ? ", " : " "
  1831. );
  1832. }
  1833. else
  1834. {
  1835. bx::write(_messageWriter, &messageErr, "gl_VertexID builtin is not supported by D3D9 HLSL.\n");
  1836. return false;
  1837. }
  1838. }
  1839. if (hasInstanceId)
  1840. {
  1841. if (profile->id >= 400)
  1842. {
  1843. preprocessor.writef(
  1844. " \\\n\t%suint gl_InstanceID : SV_InstanceID"
  1845. , arg++ > 0 ? ", " : " "
  1846. );
  1847. }
  1848. else
  1849. {
  1850. bx::write(_messageWriter, &messageErr, "gl_InstanceID builtin is not supported by D3D9 HLSL.\n");
  1851. return false;
  1852. }
  1853. }
  1854. preprocessor.writef(
  1855. ") \\\n"
  1856. "{ \\\n"
  1857. "\tOutput _varying_;"
  1858. );
  1859. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1860. {
  1861. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1862. if (varyingIt != varyingMap.end() )
  1863. {
  1864. const Varying& var = varyingIt->second;
  1865. preprocessor.writef(" \\\n\t%s", var.m_name.c_str() );
  1866. if (!var.m_init.empty() )
  1867. {
  1868. preprocessor.writef(" = %s", var.m_init.c_str() );
  1869. }
  1870. preprocessor.writef(";");
  1871. }
  1872. }
  1873. preprocessor.writef(
  1874. "\n#define __RETURN__ \\\n"
  1875. "\t} \\\n"
  1876. );
  1877. preprocessor.writef(
  1878. "\treturn _varying_"
  1879. );
  1880. }
  1881. }
  1882. if (preprocessor.run(input) )
  1883. {
  1884. if (_options.preprocessOnly)
  1885. {
  1886. bx::write(
  1887. _shaderWriter
  1888. , preprocessor.m_preprocessed.c_str()
  1889. , (int32_t)preprocessor.m_preprocessed.size()
  1890. , &err
  1891. );
  1892. return true;
  1893. }
  1894. {
  1895. std::string code;
  1896. if ('f' == _options.shaderType)
  1897. {
  1898. bx::write(_shaderWriter, BGFX_CHUNK_MAGIC_FSH, &err);
  1899. bx::write(_shaderWriter, inputHash, &err);
  1900. bx::write(_shaderWriter, uint32_t(0), &err);
  1901. }
  1902. else if ('v' == _options.shaderType)
  1903. {
  1904. bx::write(_shaderWriter, BGFX_CHUNK_MAGIC_VSH, &err);
  1905. bx::write(_shaderWriter, uint32_t(0), &err);
  1906. bx::write(_shaderWriter, outputHash, &err);
  1907. }
  1908. else
  1909. {
  1910. bx::write(_shaderWriter, BGFX_CHUNK_MAGIC_CSH, &err);
  1911. bx::write(_shaderWriter, uint32_t(0), &err);
  1912. bx::write(_shaderWriter, outputHash, &err);
  1913. }
  1914. if (profile->lang == ShadingLang::GLSL
  1915. || profile->lang == ShadingLang::ESSL)
  1916. {
  1917. const bx::StringView preprocessedInput(preprocessor.m_preprocessed.c_str() );
  1918. uint32_t glsl_profile = profile->id;
  1919. const bool usesBitsToEncoders = true
  1920. && _options.shaderType == 'f'
  1921. && !bx::findIdentifierMatch(preprocessedInput, s_bitsToEncoders).isEmpty()
  1922. ;
  1923. if (!bx::strFind(preprocessedInput, "layout(std430").isEmpty()
  1924. || !bx::strFind(preprocessedInput, "image2D").isEmpty()
  1925. || usesBitsToEncoders)
  1926. {
  1927. if (profile->lang == ShadingLang::GLSL
  1928. && glsl_profile < 430)
  1929. {
  1930. glsl_profile = 430;
  1931. }
  1932. else if (glsl_profile < 310)
  1933. {
  1934. glsl_profile = 310;
  1935. }
  1936. }
  1937. if (glsl_profile < 400)
  1938. {
  1939. const bool usesTextureLod = false
  1940. || !bx::findIdentifierMatch(input, s_ARB_shader_texture_lod).isEmpty()
  1941. || !bx::findIdentifierMatch(input, s_EXT_shader_texture_lod).isEmpty()
  1942. ;
  1943. const bool usesGpuShader5 = true
  1944. && _options.shaderType != 'f'
  1945. && !bx::findIdentifierMatch(input, s_ARB_gpu_shader5).isEmpty()
  1946. ;
  1947. const bool usesInstanceID = !bx::findIdentifierMatch(input, "gl_InstanceID").isEmpty();
  1948. const bool usesGpuShader4 = !bx::findIdentifierMatch(input, s_EXT_gpu_shader4).isEmpty();
  1949. const bool usesTexelFetch = !bx::findIdentifierMatch(input, s_texelFetch).isEmpty();
  1950. const bool usesTextureMS = !bx::findIdentifierMatch(input, s_ARB_texture_multisample).isEmpty();
  1951. const bool usesTextureArray = !bx::findIdentifierMatch(input, s_textureArray).isEmpty();
  1952. const bool usesPacking = !bx::findIdentifierMatch(input, s_ARB_shading_language_packing).isEmpty();
  1953. const bool usesViewportLayerArray = !bx::findIdentifierMatch(input, s_ARB_shader_viewport_layer_array).isEmpty();
  1954. const bool usesUnsignedVecs = !bx::findIdentifierMatch(preprocessedInput, s_unsignedVecs).isEmpty();
  1955. if (profile->lang != ShadingLang::ESSL)
  1956. {
  1957. const bool need130 = (120 == glsl_profile && (false
  1958. || !bx::findIdentifierMatch(input, s_130).isEmpty()
  1959. || usesInterpolationQualifiers
  1960. || usesTexelFetch
  1961. || usesUnsignedVecs
  1962. ) );
  1963. bx::stringPrintf(code, "#version %d\n", need130 ? 130 : glsl_profile);
  1964. glsl_profile = 130;
  1965. if (need130)
  1966. {
  1967. bx::stringPrintf(code, "#define varying %s\n"
  1968. , 'f' == _options.shaderType ? "in" : "out"
  1969. );
  1970. }
  1971. if (usesInstanceID)
  1972. {
  1973. bx::stringPrintf(code
  1974. , "#extension GL_ARB_draw_instanced : enable\n"
  1975. );
  1976. }
  1977. if (usesViewportLayerArray)
  1978. {
  1979. bx::stringPrintf(code
  1980. , "#extension GL_ARB_shader_viewport_layer_array : enable\n"
  1981. );
  1982. }
  1983. if (usesGpuShader4)
  1984. {
  1985. bx::stringPrintf(code
  1986. , "#extension GL_EXT_gpu_shader4 : enable\n"
  1987. );
  1988. }
  1989. if (usesGpuShader5)
  1990. {
  1991. bx::stringPrintf(code
  1992. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1993. );
  1994. }
  1995. if (usesPacking)
  1996. {
  1997. bx::stringPrintf(code
  1998. , "#extension GL_ARB_shading_language_packing : enable\n"
  1999. );
  2000. }
  2001. bool ARB_shader_texture_lod = false;
  2002. bool EXT_shader_texture_lod = false;
  2003. if (usesTextureLod)
  2004. {
  2005. if ('f' == _options.shaderType)
  2006. {
  2007. ARB_shader_texture_lod = true;
  2008. bx::stringPrintf(code
  2009. , "#extension GL_ARB_shader_texture_lod : enable\n"
  2010. );
  2011. }
  2012. else
  2013. {
  2014. EXT_shader_texture_lod = true;
  2015. bx::stringPrintf(code
  2016. , "#extension GL_EXT_shader_texture_lod : enable\n"
  2017. );
  2018. }
  2019. }
  2020. if (usesTextureMS)
  2021. {
  2022. bx::stringPrintf(code
  2023. , "#extension GL_ARB_texture_multisample : enable\n"
  2024. );
  2025. }
  2026. if (usesTextureArray)
  2027. {
  2028. bx::stringPrintf(code
  2029. , "#extension GL_EXT_texture_array : enable\n"
  2030. );
  2031. }
  2032. if (130 > glsl_profile)
  2033. {
  2034. bx::stringPrintf(code,
  2035. "#define ivec2 vec2\n"
  2036. "#define ivec3 vec3\n"
  2037. "#define ivec4 vec4\n"
  2038. );
  2039. }
  2040. if (ARB_shader_texture_lod)
  2041. {
  2042. bx::stringPrintf(code,
  2043. "#define texture2DProjLod texture2DProjLodARB\n"
  2044. "#define texture2DGrad texture2DGradARB\n"
  2045. "#define texture2DProjGrad texture2DProjGradARB\n"
  2046. "#define textureCubeGrad textureCubeGradARB\n"
  2047. );
  2048. }
  2049. else if (EXT_shader_texture_lod)
  2050. {
  2051. bx::stringPrintf(code,
  2052. "#define texture2DProjLod texture2DProjLodEXT\n"
  2053. "#define texture2DGrad texture2DGradEXT\n"
  2054. "#define texture2DProjGrad texture2DProjGradEXT\n"
  2055. "#define textureCubeGrad textureCubeGradEXT\n"
  2056. );
  2057. }
  2058. if (need130 || (glsl_profile >= 130))
  2059. {
  2060. bx::stringPrintf(code
  2061. , "#define bgfxShadow2D(_sampler, _coord) vec4_splat(texture(_sampler, _coord))\n"
  2062. "#define bgfxShadow2DProj(_sampler, _coord) vec4_splat(textureProj(_sampler, _coord))\n"
  2063. );
  2064. }
  2065. else
  2066. {
  2067. bx::stringPrintf(code
  2068. , "#define bgfxShadow2D shadow2D\n"
  2069. "#define bgfxShadow2DProj shader2DProj\n"
  2070. );
  2071. }
  2072. }
  2073. else
  2074. {
  2075. if ((glsl_profile < 300) && usesUnsignedVecs)
  2076. {
  2077. glsl_profile = 300;
  2078. }
  2079. if (glsl_profile > 100)
  2080. {
  2081. bx::stringPrintf(code, "#version %d es\n", glsl_profile);
  2082. bx::stringPrintf(code, "#define attribute in\n");
  2083. bx::stringPrintf(code, "#define varying %s\n"
  2084. , 'f' == _options.shaderType ? "in" : "out"
  2085. );
  2086. bx::stringPrintf(code, "precision highp float;\n");
  2087. bx::stringPrintf(code, "precision highp int;\n");
  2088. }
  2089. if (glsl_profile >= 300 && usesTextureArray)
  2090. {
  2091. bx::stringPrintf(code, "precision highp sampler2DArray;\n");
  2092. }
  2093. // Pretend that all extensions are available.
  2094. // This will be stripped later.
  2095. if (usesTextureLod)
  2096. {
  2097. bx::stringPrintf(code
  2098. , "#extension GL_EXT_shader_texture_lod : enable\n"
  2099. "#define texture2DLod texture2DLodEXT\n"
  2100. "#define texture2DGrad texture2DGradEXT\n"
  2101. "#define texture2DProjLod texture2DProjLodEXT\n"
  2102. "#define texture2DProjGrad texture2DProjGradEXT\n"
  2103. "#define textureCubeLod textureCubeLodEXT\n"
  2104. "#define textureCubeGrad textureCubeGradEXT\n"
  2105. );
  2106. }
  2107. if (!bx::findIdentifierMatch(input, s_OES_standard_derivatives).isEmpty() )
  2108. {
  2109. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  2110. }
  2111. if (!bx::findIdentifierMatch(input, s_OES_texture_3D).isEmpty() )
  2112. {
  2113. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  2114. }
  2115. if ((glsl_profile < 300) && (!bx::findIdentifierMatch(input, s_EXT_shadow_samplers).isEmpty()))
  2116. {
  2117. bx::stringPrintf(code
  2118. , "#extension GL_EXT_shadow_samplers : enable\n"
  2119. "#define shadow2D shadow2DEXT\n"
  2120. "#define shadow2DProj shadow2DProjEXT\n"
  2121. );
  2122. }
  2123. else
  2124. {
  2125. bx::stringPrintf(code
  2126. , "#define shadow2D(_sampler, _coord) texture(_sampler, _coord)\n"
  2127. "#define shadow2DProj(_sampler, _coord) textureProj(_sampler, _coord)\n"
  2128. );
  2129. }
  2130. if (usesGpuShader5)
  2131. {
  2132. bx::stringPrintf(code
  2133. , "#extension GL_ARB_gpu_shader5 : enable\n"
  2134. );
  2135. }
  2136. if (usesPacking)
  2137. {
  2138. bx::stringPrintf(code
  2139. , "#extension GL_ARB_shading_language_packing : enable\n"
  2140. );
  2141. }
  2142. if ((glsl_profile < 300) && (!bx::findIdentifierMatch(input, "gl_FragDepth").isEmpty() ))
  2143. {
  2144. bx::stringPrintf(code
  2145. , "#extension GL_EXT_frag_depth : enable\n"
  2146. "#define gl_FragDepth gl_FragDepthEXT\n"
  2147. );
  2148. }
  2149. if (usesTextureArray)
  2150. {
  2151. bx::stringPrintf(code
  2152. , "#extension GL_EXT_texture_array : enable\n"
  2153. );
  2154. }
  2155. if (glsl_profile == 100)
  2156. {
  2157. code +=
  2158. "mat2 transpose(mat2 _mtx)\n"
  2159. "{\n"
  2160. " vec2 v0 = _mtx[0];\n"
  2161. " vec2 v1 = _mtx[1];\n"
  2162. "\n"
  2163. " return mat2(\n"
  2164. " vec2(v0.x, v1.x)\n"
  2165. " , vec2(v0.y, v1.y)\n"
  2166. " );\n"
  2167. "}\n"
  2168. "\n"
  2169. "mat3 transpose(mat3 _mtx)\n"
  2170. "{\n"
  2171. " vec3 v0 = _mtx[0];\n"
  2172. " vec3 v1 = _mtx[1];\n"
  2173. " vec3 v2 = _mtx[2];\n"
  2174. "\n"
  2175. " return mat3(\n"
  2176. " vec3(v0.x, v1.x, v2.x)\n"
  2177. " , vec3(v0.y, v1.y, v2.y)\n"
  2178. " , vec3(v0.z, v1.z, v2.z)\n"
  2179. " );\n"
  2180. "}\n"
  2181. "\n"
  2182. "mat4 transpose(mat4 _mtx)\n"
  2183. "{\n"
  2184. " vec4 v0 = _mtx[0];\n"
  2185. " vec4 v1 = _mtx[1];\n"
  2186. " vec4 v2 = _mtx[2];\n"
  2187. " vec4 v3 = _mtx[3];\n"
  2188. "\n"
  2189. " return mat4(\n"
  2190. " vec4(v0.x, v1.x, v2.x, v3.x)\n"
  2191. " , vec4(v0.y, v1.y, v2.y, v3.y)\n"
  2192. " , vec4(v0.z, v1.z, v2.z, v3.z)\n"
  2193. " , vec4(v0.w, v1.w, v2.w, v3.w)\n"
  2194. " );\n"
  2195. "}\n"
  2196. ;
  2197. }
  2198. }
  2199. }
  2200. else
  2201. {
  2202. bx::stringPrintf(code, "#version %d\n", glsl_profile);
  2203. if (120 < glsl_profile)
  2204. {
  2205. if (!bx::findIdentifierMatch(input, "gl_FragColor").isEmpty() )
  2206. {
  2207. bx::stringPrintf(code
  2208. , "out vec4 bgfx_FragColor;\n"
  2209. "#define gl_FragColor bgfx_FragColor\n"
  2210. );
  2211. }
  2212. }
  2213. bx::stringPrintf(code
  2214. , "#define texture2D texture\n"
  2215. "#define texture2DLod textureLod\n"
  2216. "#define texture2DGrad textureGrad\n"
  2217. "#define texture2DProjLod textureProjLod\n"
  2218. "#define texture2DProjGrad textureProjGrad\n"
  2219. "#define textureCubeLod textureLod\n"
  2220. "#define textureCubeGrad textureGrad\n"
  2221. "#define texture3D texture\n"
  2222. "#define texture2DLodOffset textureLodOffset\n"
  2223. );
  2224. bx::stringPrintf(code, "#define attribute in\n");
  2225. bx::stringPrintf(code, "#define varying %s\n"
  2226. , 'f' == _options.shaderType ? "in" : "out"
  2227. );
  2228. bx::stringPrintf(code
  2229. , "#define bgfxShadow2D(_sampler, _coord) vec4_splat(texture(_sampler, _coord))\n"
  2230. "#define bgfxShadow2DProj(_sampler, _coord) vec4_splat(textureProj(_sampler, _coord))\n"
  2231. );
  2232. }
  2233. if ( (profile->lang == ShadingLang::GLSL && glsl_profile > 400)
  2234. || (profile->lang == ShadingLang::ESSL && glsl_profile > 300) )
  2235. {
  2236. code += preprocessor.m_preprocessed;
  2237. bx::write(_shaderWriter, uint16_t(0), &err);
  2238. uint32_t shaderSize = (uint32_t)code.size();
  2239. bx::write(_shaderWriter, shaderSize, &err);
  2240. bx::write(_shaderWriter, code.c_str(), shaderSize, &err);
  2241. bx::write(_shaderWriter, uint8_t(0), &err);
  2242. compiled = true;
  2243. }
  2244. else
  2245. {
  2246. code += _comment;
  2247. code += preprocessor.m_preprocessed;
  2248. if (profile->lang == ShadingLang::ESSL)
  2249. {
  2250. glsl_profile |= 0x80000000;
  2251. }
  2252. compiled = compileGLSLShader(_options, glsl_profile, code, _shaderWriter, _messageWriter);
  2253. }
  2254. }
  2255. else
  2256. {
  2257. code += _comment;
  2258. code += preprocessor.m_preprocessed;
  2259. if (profile->lang == ShadingLang::Metal)
  2260. {
  2261. compiled = compileMetalShader(_options, BX_MAKEFOURCC('M', 'T', 'L', 0), code, _shaderWriter, _messageWriter);
  2262. }
  2263. else if (profile->lang == ShadingLang::SpirV)
  2264. {
  2265. compiled = compileSPIRVShader(_options, profile->id, code, _shaderWriter, _messageWriter);
  2266. }
  2267. else if (profile->lang == ShadingLang::PSSL)
  2268. {
  2269. compiled = compilePSSLShader(_options, 0, code, _shaderWriter, _messageWriter);
  2270. }
  2271. else
  2272. {
  2273. compiled = compileHLSLShader(_options, profile->id, code, _shaderWriter, _messageWriter);
  2274. }
  2275. }
  2276. }
  2277. if (compiled)
  2278. {
  2279. if (_options.depends)
  2280. {
  2281. std::string ofp = _options.outputFilePath + ".d";
  2282. bx::FileWriter writer;
  2283. if (bx::open(&writer, ofp.c_str() ) )
  2284. {
  2285. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  2286. bx::close(&writer);
  2287. }
  2288. }
  2289. }
  2290. }
  2291. }
  2292. }
  2293. delete [] data;
  2294. return compiled;
  2295. }
  2296. int compileShader(int _argc, const char* _argv[])
  2297. {
  2298. bx::CommandLine cmdLine(_argc, _argv);
  2299. if (cmdLine.hasArg('v', "version") )
  2300. {
  2301. bx::printf(
  2302. "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  2303. , BGFX_SHADERC_VERSION_MAJOR
  2304. , BGFX_SHADERC_VERSION_MINOR
  2305. , BGFX_API_VERSION
  2306. );
  2307. return bx::kExitSuccess;
  2308. }
  2309. if (cmdLine.hasArg('h', "help") )
  2310. {
  2311. help();
  2312. return bx::kExitFailure;
  2313. }
  2314. g_verbose = cmdLine.hasArg("verbose");
  2315. const char* filePath = cmdLine.findOption('f');
  2316. if (NULL == filePath)
  2317. {
  2318. help("Shader file name must be specified.");
  2319. return bx::kExitFailure;
  2320. }
  2321. bool consoleOut = cmdLine.hasArg("stdout");
  2322. const char* outFilePath = cmdLine.findOption('o');
  2323. if (NULL == outFilePath && !consoleOut)
  2324. {
  2325. help("Output file name must be specified or use \"--stdout\" to output to stdout.");
  2326. return bx::kExitFailure;
  2327. }
  2328. const char* type = cmdLine.findOption('\0', "type");
  2329. if (NULL == type)
  2330. {
  2331. help("Must specify shader type.");
  2332. return bx::kExitFailure;
  2333. }
  2334. Options options;
  2335. options.inputFilePath = filePath;
  2336. options.outputFilePath = consoleOut ? "" : outFilePath;
  2337. options.shaderType = bx::toLower(type[0]);
  2338. options.disasm = cmdLine.hasArg('\0', "disasm");
  2339. const char* platform = cmdLine.findOption('\0', "platform");
  2340. if (NULL == platform)
  2341. {
  2342. platform = "";
  2343. }
  2344. options.platform = platform;
  2345. options.raw = cmdLine.hasArg('\0', "raw");
  2346. const char* profile = cmdLine.findOption('p', "profile");
  2347. if ( NULL != profile)
  2348. {
  2349. options.profile = profile;
  2350. }
  2351. {
  2352. options.debugInformation = cmdLine.hasArg('\0', "debug");
  2353. options.avoidFlowControl = cmdLine.hasArg('\0', "avoid-flow-control");
  2354. options.noPreshader = cmdLine.hasArg('\0', "no-preshader");
  2355. options.partialPrecision = cmdLine.hasArg('\0', "partial-precision");
  2356. options.preferFlowControl = cmdLine.hasArg('\0', "prefer-flow-control");
  2357. options.backwardsCompatibility = cmdLine.hasArg('\0', "backwards-compatibility");
  2358. options.warningsAreErrors = cmdLine.hasArg('\0', "Werror");
  2359. options.keepIntermediate = cmdLine.hasArg('\0', "keep-intermediate");
  2360. uint32_t optimization = 3;
  2361. if (cmdLine.hasArg(optimization, 'O') )
  2362. {
  2363. options.optimize = true;
  2364. options.optimizationLevel = optimization;
  2365. }
  2366. }
  2367. bx::StringView bin2c;
  2368. if (cmdLine.hasArg("bin2c") )
  2369. {
  2370. const char* bin2cArg = cmdLine.findOption("bin2c");
  2371. if (NULL != bin2cArg)
  2372. {
  2373. bin2c.set(bin2cArg);
  2374. }
  2375. else
  2376. {
  2377. bin2c = baseName(outFilePath);
  2378. if (!bin2c.isEmpty() )
  2379. {
  2380. char* temp = (char*)alloca(bin2c.getLength()+1);
  2381. for (uint32_t ii = 0, num = bin2c.getLength(); ii < num; ++ii)
  2382. {
  2383. char ch = bin2c.getPtr()[ii];
  2384. if (bx::isAlphaNum(ch) )
  2385. {
  2386. temp[ii] = ch;
  2387. }
  2388. else
  2389. {
  2390. temp[ii] = '_';
  2391. }
  2392. }
  2393. temp[bin2c.getLength()] = '\0';
  2394. bin2c = temp;
  2395. }
  2396. }
  2397. }
  2398. options.depends = cmdLine.hasArg("depends");
  2399. options.preprocessOnly = cmdLine.hasArg("preprocess");
  2400. const char* includeDir = cmdLine.findOption('i');
  2401. BX_TRACE("depends: %d", options.depends);
  2402. BX_TRACE("preprocessOnly: %d", options.preprocessOnly);
  2403. BX_TRACE("includeDir: %s", includeDir);
  2404. for (int ii = 1; NULL != includeDir; ++ii)
  2405. {
  2406. options.includeDirs.push_back(includeDir);
  2407. includeDir = cmdLine.findOption(ii, 'i');
  2408. }
  2409. std::string dir;
  2410. {
  2411. bx::FilePath fp(filePath);
  2412. bx::StringView path(fp.getPath() );
  2413. dir.assign(path.getPtr(), path.getTerm() );
  2414. options.includeDirs.push_back(dir);
  2415. }
  2416. const char* defines = cmdLine.findOption("define");
  2417. while (NULL != defines
  2418. && '\0' != *defines)
  2419. {
  2420. defines = bx::strLTrimSpace(defines).getPtr();
  2421. bx::StringView eol = bx::strFind(defines, ';');
  2422. std::string define(defines, eol.getPtr() );
  2423. options.defines.push_back(define.c_str() );
  2424. defines = ';' == *eol.getPtr() ? eol.getPtr()+1 : eol.getPtr();
  2425. }
  2426. std::string commandLineComment = "// shaderc command line:\n//";
  2427. for (int32_t ii = 0, num = cmdLine.getNum(); ii < num; ++ii)
  2428. {
  2429. commandLineComment += " ";
  2430. commandLineComment += cmdLine.get(ii);
  2431. }
  2432. commandLineComment += "\n\n";
  2433. bool compiled = false;
  2434. bx::FileReader reader;
  2435. if (!bx::open(&reader, filePath) )
  2436. {
  2437. bx::printf("Unable to open file '%s'.\n", filePath);
  2438. }
  2439. else
  2440. {
  2441. const char* varying = NULL;
  2442. File attribdef;
  2443. if ('c' != options.shaderType)
  2444. {
  2445. std::string defaultVarying = dir + "varying.def.sc";
  2446. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  2447. attribdef.load(varyingdef);
  2448. varying = attribdef.getData();
  2449. if (NULL != varying
  2450. && *varying != '\0')
  2451. {
  2452. options.dependencies.push_back(varyingdef);
  2453. }
  2454. else
  2455. {
  2456. bx::printf("ERROR: Failed to parse varying def file: \"%s\" No input/output semantics will be generated in the code!\n", varyingdef);
  2457. }
  2458. }
  2459. const size_t padding = 16384;
  2460. uint32_t size = (uint32_t)bx::getSize(&reader);
  2461. char* data = new char[size+padding+1];
  2462. size = (uint32_t)bx::read(&reader, data, size, bx::ErrorAssert{});
  2463. if (data[0] == '\xef'
  2464. && data[1] == '\xbb'
  2465. && data[2] == '\xbf')
  2466. {
  2467. bx::memMove(data, &data[3], size-3);
  2468. size -= 3;
  2469. }
  2470. // Compiler generates "error X3000: syntax error: unexpected end of file"
  2471. // if input doesn't have empty line at EOF.
  2472. data[size] = '\n';
  2473. bx::memSet(&data[size+1], 0, padding);
  2474. bx::close(&reader);
  2475. bx::FileWriter* writer = NULL;
  2476. if (!consoleOut)
  2477. {
  2478. if (!bin2c.isEmpty())
  2479. {
  2480. writer = new Bin2cWriter(bin2c);
  2481. }
  2482. else
  2483. {
  2484. writer = new bx::FileWriter;
  2485. }
  2486. if (!bx::open(writer, outFilePath))
  2487. {
  2488. bx::printf("Unable to open output file '%s'.\n", outFilePath);
  2489. return bx::kExitFailure;
  2490. }
  2491. }
  2492. compiled = compileShader(varying, commandLineComment.c_str(), data, size, options, consoleOut ? bx::getStdOut() : writer, bx::getStdOut());
  2493. if (!consoleOut)
  2494. {
  2495. bx::close(writer);
  2496. delete writer;
  2497. }
  2498. }
  2499. if (compiled)
  2500. {
  2501. return bx::kExitSuccess;
  2502. }
  2503. bx::remove(outFilePath);
  2504. bx::printf("Failed to build shader.\n");
  2505. return bx::kExitFailure;
  2506. }
  2507. } // namespace bgfx
  2508. int main(int _argc, const char* _argv[])
  2509. {
  2510. return bgfx::compileShader(_argc, _argv);
  2511. }