shaderc.cpp 62 KB

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