shaderc.cpp 55 KB

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