shaderc.cpp 73 KB

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