shaderc.cpp 75 KB

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