shaderc.cpp 75 KB

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