shaderc.cpp 71 KB

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