shaderc.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  1. /*
  2. * Copyright 2011-2014 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #ifndef SHADERC_DEBUG
  6. # define SHADERC_DEBUG 0
  7. #endif // SHADERC_DEBUG
  8. #define _BX_TRACE(_format, ...) \
  9. do { \
  10. fprintf(stderr, BX_FILE_LINE_LITERAL "" _format "\n", ##__VA_ARGS__); \
  11. } while(0)
  12. #define _BX_WARN(_condition, _format, ...) \
  13. do { \
  14. if (!(_condition) ) \
  15. { \
  16. BX_TRACE("WARN " _format, ##__VA_ARGS__); \
  17. } \
  18. } while(0)
  19. #define _BX_CHECK(_condition, _format, ...) \
  20. do { \
  21. if (!(_condition) ) \
  22. { \
  23. BX_TRACE("CHECK " _format, ##__VA_ARGS__); \
  24. bx::debugBreak(); \
  25. } \
  26. } while(0)
  27. #if SHADERC_DEBUG
  28. # define BX_TRACE _BX_TRACE
  29. # define BX_WARN _BX_WARN
  30. # define BX_CHECK _BX_CHECK
  31. #endif // DEBUG
  32. #include <bx/bx.h>
  33. #include <bx/debug.h>
  34. #define NOMINMAX
  35. #include <alloca.h>
  36. #include <stdio.h>
  37. #include <stdint.h>
  38. #include <stdlib.h>
  39. #include <string.h>
  40. #include <algorithm>
  41. #include <string>
  42. #include <vector>
  43. #include <unordered_map>
  44. #define MAX_TAGS 256
  45. extern "C"
  46. {
  47. #include <fpp.h>
  48. } // extern "C"
  49. #define BGFX_CHUNK_MAGIC_VSH BX_MAKEFOURCC('V', 'S', 'H', 0x1)
  50. #define BGFX_CHUNK_MAGIC_FSH BX_MAKEFOURCC('F', 'S', 'H', 0x1)
  51. #include <bx/commandline.h>
  52. #include <bx/endian.h>
  53. #include <bx/uint32_t.h>
  54. #include <bx/readerwriter.h>
  55. #include <bx/string.h>
  56. #include <bx/hash.h>
  57. #include "glsl_optimizer.h"
  58. #if BX_PLATFORM_WINDOWS
  59. # include <sal.h>
  60. # define __D3DX9MATH_INL__ // not used and MinGW complains about type-punning
  61. # include <d3dx9.h>
  62. # include <d3dcompiler.h>
  63. #endif // BX_PLATFORM_WINDOWS
  64. long int fsize(FILE* _file)
  65. {
  66. long int pos = ftell(_file);
  67. fseek(_file, 0L, SEEK_END);
  68. long int size = ftell(_file);
  69. fseek(_file, pos, SEEK_SET);
  70. return size;
  71. }
  72. struct Attrib
  73. {
  74. enum Enum
  75. {
  76. Position = 0,
  77. Normal,
  78. Tangent,
  79. Color0,
  80. Color1,
  81. Indices,
  82. Weight,
  83. TexCoord0,
  84. TexCoord1,
  85. TexCoord2,
  86. TexCoord3,
  87. TexCoord4,
  88. TexCoord5,
  89. TexCoord6,
  90. TexCoord7,
  91. Count,
  92. };
  93. };
  94. static const char* s_ARB_shader_texture_lod[] =
  95. {
  96. "texture2DLod",
  97. "texture2DProjLod",
  98. "texture3DLod",
  99. "texture3DProjLod",
  100. "textureCubeLod",
  101. "shadow2DLod",
  102. "shadow2DProjLod",
  103. NULL
  104. // "texture1DLod",
  105. // "texture1DProjLod",
  106. // "shadow1DLod",
  107. // "shadow1DProjLod",
  108. };
  109. static const char* s_EXT_shadow_samplers[] =
  110. {
  111. "shadow2D",
  112. "shadow2DProj",
  113. NULL
  114. };
  115. static const char* s_OES_standard_derivatives[] =
  116. {
  117. "dFdx",
  118. "dFdy",
  119. "fwidth",
  120. NULL
  121. };
  122. static const char* s_OES_texture_3D[] =
  123. {
  124. "texture3D",
  125. "texture3DProj",
  126. "texture3DLod",
  127. "texture3DProjLod",
  128. NULL
  129. };
  130. struct RemapInputSemantic
  131. {
  132. Attrib::Enum m_attr;
  133. const char* m_name;
  134. uint8_t m_index;
  135. };
  136. static const RemapInputSemantic s_remapInputSemantic[Attrib::Count+1] =
  137. {
  138. { Attrib::Position, "POSITION", 0 },
  139. { Attrib::Normal, "NORMAL", 0 },
  140. { Attrib::Tangent, "TANGENT", 0 },
  141. { Attrib::Color0, "COLOR", 0 },
  142. { Attrib::Color1, "COLOR", 1 },
  143. { Attrib::Indices, "BLENDINDICES", 0 },
  144. { Attrib::Weight, "BLENDWEIGHT", 0 },
  145. { Attrib::TexCoord0, "TEXCOORD", 0 },
  146. { Attrib::TexCoord1, "TEXCOORD", 1 },
  147. { Attrib::TexCoord2, "TEXCOORD", 2 },
  148. { Attrib::TexCoord3, "TEXCOORD", 3 },
  149. { Attrib::TexCoord4, "TEXCOORD", 4 },
  150. { Attrib::TexCoord5, "TEXCOORD", 5 },
  151. { Attrib::TexCoord6, "TEXCOORD", 6 },
  152. { Attrib::TexCoord7, "TEXCOORD", 7 },
  153. { Attrib::Count, "", 0 },
  154. };
  155. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  156. {
  157. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  158. {
  159. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  160. if (0 == strcmp(ris.m_name, _name)
  161. && ris.m_index == _index)
  162. {
  163. return ris;
  164. }
  165. }
  166. return s_remapInputSemantic[Attrib::Count];
  167. }
  168. struct ConstantType
  169. {
  170. enum Enum
  171. {
  172. Uniform1i,
  173. Uniform1f,
  174. End,
  175. Uniform1iv,
  176. Uniform1fv,
  177. Uniform2fv,
  178. Uniform3fv,
  179. Uniform4fv,
  180. Uniform3x3fv,
  181. Uniform4x4fv,
  182. Count,
  183. };
  184. };
  185. #define BGFX_UNIFORM_FRAGMENTBIT UINT8_C(0x10)
  186. const char* s_constantTypeName[ConstantType::Count] =
  187. {
  188. "int",
  189. "float",
  190. NULL,
  191. "int",
  192. "float",
  193. "float2",
  194. "float3",
  195. "float4",
  196. "float3x3",
  197. "float4x4",
  198. };
  199. struct Uniform
  200. {
  201. std::string name;
  202. ConstantType::Enum type;
  203. uint8_t num;
  204. uint16_t regIndex;
  205. uint16_t regCount;
  206. };
  207. typedef std::vector<Uniform> UniformArray;
  208. #if BX_PLATFORM_WINDOWS
  209. struct ConstRemapDx9
  210. {
  211. ConstantType::Enum id;
  212. D3DXPARAMETER_CLASS paramClass;
  213. D3DXPARAMETER_TYPE paramType;
  214. uint32_t paramBytes;
  215. };
  216. static const ConstRemapDx9 s_constRemapDx9[7] =
  217. {
  218. { ConstantType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 4 },
  219. { ConstantType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 4 },
  220. { ConstantType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 8 },
  221. { ConstantType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 12 },
  222. { ConstantType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 16 },
  223. { ConstantType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 36 },
  224. { ConstantType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 64 },
  225. };
  226. ConstantType::Enum findConstantTypeDx9(const D3DXCONSTANT_DESC& constDesc)
  227. {
  228. uint32_t count = sizeof(s_constRemapDx9)/sizeof(ConstRemapDx9);
  229. for (uint32_t ii = 0; ii < count; ++ii)
  230. {
  231. const ConstRemapDx9& remap = s_constRemapDx9[ii];
  232. if (remap.paramClass == constDesc.Class
  233. && remap.paramType == constDesc.Type
  234. && (constDesc.Bytes%remap.paramBytes) == 0)
  235. {
  236. return remap.id;
  237. }
  238. }
  239. return ConstantType::Count;
  240. }
  241. static uint32_t s_optimizationLevelDx9[4] =
  242. {
  243. D3DXSHADER_OPTIMIZATION_LEVEL0,
  244. D3DXSHADER_OPTIMIZATION_LEVEL1,
  245. D3DXSHADER_OPTIMIZATION_LEVEL2,
  246. D3DXSHADER_OPTIMIZATION_LEVEL3,
  247. };
  248. struct ConstRemapDx11
  249. {
  250. ConstantType::Enum id;
  251. D3D_SHADER_VARIABLE_CLASS paramClass;
  252. D3D_SHADER_VARIABLE_TYPE paramType;
  253. uint32_t paramBytes;
  254. };
  255. static const ConstRemapDx11 s_constRemapDx11[7] =
  256. {
  257. { ConstantType::Uniform1iv, D3D_SVC_SCALAR, D3D_SVT_INT, 4 },
  258. { ConstantType::Uniform1fv, D3D_SVC_SCALAR, D3D_SVT_FLOAT, 4 },
  259. { ConstantType::Uniform2fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 8 },
  260. { ConstantType::Uniform3fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 12 },
  261. { ConstantType::Uniform4fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 16 },
  262. { ConstantType::Uniform3x3fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 36 },
  263. { ConstantType::Uniform4x4fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 64 },
  264. };
  265. ConstantType::Enum findConstantTypeDx11(const D3D11_SHADER_TYPE_DESC& constDesc, uint32_t _size)
  266. {
  267. uint32_t count = sizeof(s_constRemapDx11)/sizeof(ConstRemapDx9);
  268. for (uint32_t ii = 0; ii < count; ++ii)
  269. {
  270. const ConstRemapDx11& remap = s_constRemapDx11[ii];
  271. if (remap.paramClass == constDesc.Class
  272. && remap.paramType == constDesc.Type
  273. && (_size%remap.paramBytes) == 0)
  274. {
  275. return remap.id;
  276. }
  277. }
  278. return ConstantType::Count;
  279. }
  280. static uint32_t s_optimizationLevelDx11[4] =
  281. {
  282. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  283. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  284. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  285. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  286. };
  287. #endif // BX_PLATFORM_WINDOWS
  288. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  289. {
  290. va_list argList;
  291. va_start(argList, _format);
  292. char temp[2048];
  293. char* out = temp;
  294. int32_t max = sizeof(temp);
  295. int32_t len = bx::vsnprintf(out, max, _format, argList);
  296. if (len > max)
  297. {
  298. out = (char*)alloca(len);
  299. len = bx::vsnprintf(out, len, _format, argList);
  300. }
  301. len = bx::write(_writer, out, len);
  302. va_end(argList);
  303. return len;
  304. }
  305. class Bin2cWriter : public bx::CrtFileWriter
  306. {
  307. public:
  308. Bin2cWriter(const char* _name)
  309. : m_name(_name)
  310. {
  311. }
  312. virtual ~Bin2cWriter()
  313. {
  314. }
  315. virtual int32_t close() BX_OVERRIDE
  316. {
  317. generate();
  318. return bx::CrtFileWriter::close();
  319. }
  320. virtual int32_t write(const void* _data, int32_t _size) BX_OVERRIDE
  321. {
  322. const char* data = (const char*)_data;
  323. m_buffer.insert(m_buffer.end(), data, data+_size);
  324. return _size;
  325. }
  326. private:
  327. void generate()
  328. {
  329. #define HEX_DUMP_WIDTH 16
  330. #define HEX_DUMP_SPACE_WIDTH 96
  331. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  332. const uint8_t* data = &m_buffer[0];
  333. uint32_t size = (uint32_t)m_buffer.size();
  334. outf("static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size);
  335. if (NULL != data)
  336. {
  337. char hex[HEX_DUMP_SPACE_WIDTH+1];
  338. char ascii[HEX_DUMP_WIDTH+1];
  339. uint32_t hexPos = 0;
  340. uint32_t asciiPos = 0;
  341. for (uint32_t ii = 0; ii < size; ++ii)
  342. {
  343. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  344. hexPos += 6;
  345. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
  346. asciiPos++;
  347. if (HEX_DUMP_WIDTH == asciiPos)
  348. {
  349. ascii[asciiPos] = '\0';
  350. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  351. data += asciiPos;
  352. hexPos = 0;
  353. asciiPos = 0;
  354. }
  355. }
  356. if (0 != asciiPos)
  357. {
  358. ascii[asciiPos] = '\0';
  359. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  360. }
  361. }
  362. outf("};\n");
  363. #undef HEX_DUMP_WIDTH
  364. #undef HEX_DUMP_SPACE_WIDTH
  365. #undef HEX_DUMP_FORMAT
  366. }
  367. int32_t outf(const char* _format, ...)
  368. {
  369. va_list argList;
  370. va_start(argList, _format);
  371. char temp[2048];
  372. char* out = temp;
  373. int32_t max = sizeof(temp);
  374. int32_t len = bx::vsnprintf(out, max, _format, argList);
  375. if (len > max)
  376. {
  377. out = (char*)alloca(len);
  378. len = bx::vsnprintf(out, len, _format, argList);
  379. }
  380. int32_t size = bx::CrtFileWriter::write(out, len);
  381. va_end(argList);
  382. return size;
  383. }
  384. std::string m_filePath;
  385. std::string m_name;
  386. typedef std::vector<uint8_t> Buffer;
  387. Buffer m_buffer;
  388. };
  389. struct Varying
  390. {
  391. std::string m_precision;
  392. std::string m_name;
  393. std::string m_type;
  394. std::string m_init;
  395. std::string m_semantics;
  396. };
  397. typedef std::unordered_map<std::string, Varying> VaryingMap;
  398. class File
  399. {
  400. public:
  401. File(const char* _filePath)
  402. : m_data(NULL)
  403. {
  404. FILE* file = fopen(_filePath, "r");
  405. if (NULL != file)
  406. {
  407. m_size = fsize(file);
  408. m_data = new char[m_size+1];
  409. m_size = (uint32_t)fread(m_data, 1, m_size, file);
  410. m_data[m_size] = '\0';
  411. fclose(file);
  412. }
  413. }
  414. ~File()
  415. {
  416. delete [] m_data;
  417. }
  418. const char* getData() const
  419. {
  420. return m_data;
  421. }
  422. uint32_t getSize() const
  423. {
  424. return m_size;
  425. }
  426. private:
  427. char* m_data;
  428. uint32_t m_size;
  429. };
  430. void strins(char* _str, const char* _insert)
  431. {
  432. size_t len = strlen(_insert);
  433. memmove(&_str[len], _str, strlen(_str) );
  434. memcpy(_str, _insert, len);
  435. }
  436. void strreplace(char* _str, const char* _find, const char* _replace)
  437. {
  438. const size_t len = strlen(_find);
  439. char* replace = (char*)alloca(len+1);
  440. bx::strlcpy(replace, _replace, len+1);
  441. for (uint32_t ii = strlen(replace); ii < len; ++ii)
  442. {
  443. replace[ii] = ' ';
  444. }
  445. replace[len] = '\0';
  446. BX_CHECK(len >= strlen(_replace), "");
  447. for (char* ptr = strstr(_str, _find); NULL != ptr; ptr = strstr(ptr + len, _find) )
  448. {
  449. memcpy(ptr, replace, len);
  450. }
  451. }
  452. class LineReader
  453. {
  454. public:
  455. LineReader(const char* _str)
  456. : m_str(_str)
  457. , m_pos(0)
  458. , m_size( (uint32_t)strlen(_str) )
  459. {
  460. }
  461. std::string getLine()
  462. {
  463. const char* str = &m_str[m_pos];
  464. skipLine();
  465. const char* eol = &m_str[m_pos];
  466. std::string tmp;
  467. tmp.assign(str, eol-str);
  468. return tmp;
  469. }
  470. bool isEof() const
  471. {
  472. return m_str[m_pos] == '\0';
  473. }
  474. void skipLine()
  475. {
  476. const char* str = &m_str[m_pos];
  477. const char* nl = bx::strnl(str);
  478. m_pos += (uint32_t)(nl - str);
  479. }
  480. const char* m_str;
  481. uint32_t m_pos;
  482. uint32_t m_size;
  483. };
  484. void printCode(const char* _code, int32_t _line = 0, int32_t _start = 0, int32_t _end = INT32_MAX)
  485. {
  486. fprintf(stderr, "Code:\n---\n");
  487. LineReader lr(_code);
  488. for (int32_t line = 1; !lr.isEof() && line < _end; ++line)
  489. {
  490. if (line >= _start)
  491. {
  492. fprintf(stderr, "%s%3d: %s", _line == line ? ">>> " : " ", line, lr.getLine().c_str() );
  493. }
  494. else
  495. {
  496. lr.skipLine();
  497. }
  498. }
  499. fprintf(stderr, "---\n");
  500. }
  501. void writeFile(const char* _filePath, const void* _data, int32_t _size)
  502. {
  503. bx::CrtFileWriter out;
  504. if (0 == out.open(_filePath) )
  505. {
  506. out.write(_data, _size);
  507. out.close();
  508. }
  509. }
  510. bool compileGLSLShader(bx::CommandLine& _cmdLine, uint32_t _gles, const std::string& _code, bx::WriterI* _writer)
  511. {
  512. const glslopt_shader_type type = tolower(_cmdLine.findOption('\0', "type")[0]) == 'f' ? kGlslOptShaderFragment : kGlslOptShaderVertex;
  513. glslopt_target target = kGlslTargetOpenGL;
  514. switch (_gles)
  515. {
  516. case 2:
  517. target = kGlslTargetOpenGLES20;
  518. break;
  519. case 3:
  520. target = kGlslTargetOpenGLES30;
  521. break;
  522. default:
  523. target = kGlslTargetOpenGL;
  524. break;
  525. }
  526. glslopt_ctx* ctx = glslopt_initialize(target);
  527. glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
  528. if (!glslopt_get_status(shader) )
  529. {
  530. const char* log = glslopt_get_log(shader);
  531. int32_t source = 0;
  532. int32_t line = 0;
  533. int32_t column = 0;
  534. int32_t start = 0;
  535. int32_t end = INT32_MAX;
  536. if (3 == sscanf(log, "%u:%u(%u):", &source, &line, &column)
  537. && 0 != line)
  538. {
  539. start = bx::uint32_imax(1, line-10);
  540. end = start + 20;
  541. }
  542. printCode(_code.c_str(), line, start, end);
  543. fprintf(stderr, "Error: %s\n", log);
  544. glslopt_cleanup(ctx);
  545. return false;
  546. }
  547. const char* optimizedShader = glslopt_get_output(shader);
  548. // Trim all directives.
  549. while ('#' == *optimizedShader)
  550. {
  551. optimizedShader = bx::strnl(optimizedShader);
  552. }
  553. if (0 != _gles)
  554. {
  555. char* shader = const_cast<char*>(optimizedShader);
  556. strreplace(shader, "gl_FragDepthEXT", "gl_FragDepth");
  557. strreplace(shader, "texture2DLodEXT", "texture2DLod");
  558. strreplace(shader, "texture2DProjLodEXT", "texture2DProjLod");
  559. strreplace(shader, "textureCubeLodEXT", "textureCubeLod");
  560. strreplace(shader, "texture2DGradEXT", "texture2DGrad");
  561. strreplace(shader, "texture2DProjGradEXT", "texture2DProjGrad");
  562. strreplace(shader, "textureCubeGradEXT", "textureCubeGrad");
  563. strreplace(shader, "shadow2DEXT", "shadow2D");
  564. strreplace(shader, "shadow2DProjEXT", "shadow2DProj");
  565. }
  566. bx::write(_writer, optimizedShader, (int32_t)strlen(optimizedShader) );
  567. uint8_t nul = 0;
  568. bx::write(_writer, nul);
  569. glslopt_cleanup(ctx);
  570. return true;
  571. }
  572. bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  573. {
  574. #if BX_PLATFORM_WINDOWS
  575. const char* profile = _cmdLine.findOption('p', "profile");
  576. if (NULL == profile)
  577. {
  578. fprintf(stderr, "Shader profile must be specified.\n");
  579. return false;
  580. }
  581. bool debug = _cmdLine.hasArg('\0', "debug");
  582. uint32_t flags = 0;
  583. flags |= debug ? D3DXSHADER_DEBUG : 0;
  584. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
  585. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
  586. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
  587. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
  588. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  589. bool werror = _cmdLine.hasArg('\0', "Werror");
  590. uint32_t optimization = 3;
  591. if (_cmdLine.hasArg(optimization, 'O') )
  592. {
  593. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx9)-1);
  594. flags |= s_optimizationLevelDx9[optimization];
  595. }
  596. else
  597. {
  598. flags |= D3DXSHADER_SKIPOPTIMIZATION;
  599. }
  600. BX_TRACE("Profile: %s", profile);
  601. BX_TRACE("Flags: 0x%08x", flags);
  602. LPD3DXBUFFER code;
  603. LPD3DXBUFFER errorMsg;
  604. LPD3DXCONSTANTTABLE constantTable;
  605. HRESULT hr;
  606. // Output preprocessed shader so that HLSL can be debugged via GPA
  607. // or PIX. Compiling through memory won't embed preprocessed shader
  608. // file path.
  609. if (debug)
  610. {
  611. std::string hlslfp = _cmdLine.findOption('o');
  612. hlslfp += ".hlsl";
  613. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  614. hr = D3DXCompileShaderFromFileA(hlslfp.c_str()
  615. , NULL
  616. , NULL
  617. , "main"
  618. , profile
  619. , flags
  620. , &code
  621. , &errorMsg
  622. , &constantTable
  623. );
  624. }
  625. else
  626. {
  627. hr = D3DXCompileShader(_code.c_str()
  628. , (uint32_t)_code.size()
  629. , NULL
  630. , NULL
  631. , "main"
  632. , profile
  633. , flags
  634. , &code
  635. , &errorMsg
  636. , &constantTable
  637. );
  638. }
  639. if (FAILED(hr)
  640. || (werror && NULL != errorMsg) )
  641. {
  642. const char* log = (const char*)errorMsg->GetBufferPointer();
  643. char source[1024];
  644. int32_t line = 0;
  645. int32_t column = 0;
  646. int32_t start = 0;
  647. int32_t end = INT32_MAX;
  648. if (3 == sscanf(log, "%[^(](%u,%u):", source, &line, &column)
  649. && 0 != line)
  650. {
  651. start = bx::uint32_imax(1, line-10);
  652. end = start + 20;
  653. }
  654. printCode(_code.c_str(), line, start, end);
  655. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  656. errorMsg->Release();
  657. return false;
  658. }
  659. D3DXCONSTANTTABLE_DESC desc;
  660. hr = constantTable->GetDesc(&desc);
  661. if (FAILED(hr) )
  662. {
  663. fprintf(stderr, "Error 0x%08x\n", (uint32_t)hr);
  664. return false;
  665. }
  666. BX_TRACE("Creator: %s 0x%08x", desc.Creator, (uint32_t /*mingw warning*/)desc.Version);
  667. BX_TRACE("Num constants: %d", desc.Constants);
  668. BX_TRACE("# cl ty RxC S By Name");
  669. UniformArray uniforms;
  670. for (uint32_t ii = 0; ii < desc.Constants; ++ii)
  671. {
  672. D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
  673. D3DXCONSTANT_DESC constDesc;
  674. uint32_t count;
  675. constantTable->GetConstantDesc(handle, &constDesc, &count);
  676. BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
  677. , ii
  678. , constDesc.Class
  679. , constDesc.Type
  680. , constDesc.Rows
  681. , constDesc.Columns
  682. , constDesc.StructMembers
  683. , constDesc.Bytes
  684. , constDesc.Name
  685. , constDesc.Elements
  686. , constDesc.RegisterIndex
  687. , constDesc.RegisterCount
  688. );
  689. ConstantType::Enum type = findConstantTypeDx9(constDesc);
  690. if (ConstantType::Count != type)
  691. {
  692. Uniform un;
  693. un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
  694. un.type = type;
  695. un.num = constDesc.Elements;
  696. un.regIndex = constDesc.RegisterIndex;
  697. un.regCount = constDesc.RegisterCount;
  698. uniforms.push_back(un);
  699. }
  700. }
  701. uint16_t count = (uint16_t)uniforms.size();
  702. bx::write(_writer, count);
  703. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  704. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  705. {
  706. const Uniform& un = *it;
  707. uint8_t nameSize = (uint8_t)un.name.size();
  708. bx::write(_writer, nameSize);
  709. bx::write(_writer, un.name.c_str(), nameSize);
  710. uint8_t type = un.type|fragmentBit;
  711. bx::write(_writer, type);
  712. bx::write(_writer, un.num);
  713. bx::write(_writer, un.regIndex);
  714. bx::write(_writer, un.regCount);
  715. BX_TRACE("%s, %s, %d, %d, %d"
  716. , un.name.c_str()
  717. , s_constantTypeName[un.type]
  718. , un.num
  719. , un.regIndex
  720. , un.regCount
  721. );
  722. }
  723. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  724. bx::write(_writer, shaderSize);
  725. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  726. uint8_t nul = 0;
  727. bx::write(_writer, nul);
  728. if (_cmdLine.hasArg('\0', "disasm") )
  729. {
  730. LPD3DXBUFFER disasm;
  731. D3DXDisassembleShader( (const DWORD*)code->GetBufferPointer()
  732. , false
  733. , NULL
  734. , &disasm
  735. );
  736. if (NULL != disasm)
  737. {
  738. std::string disasmfp = _cmdLine.findOption('o');
  739. disasmfp += ".disasm";
  740. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), disasm->GetBufferSize() );
  741. disasm->Release();
  742. }
  743. }
  744. if (NULL != code)
  745. {
  746. code->Release();
  747. }
  748. if (NULL != errorMsg)
  749. {
  750. errorMsg->Release();
  751. }
  752. if (NULL != constantTable)
  753. {
  754. constantTable->Release();
  755. }
  756. return true;
  757. #else
  758. BX_UNUSED(_cmdLine, _code, _writer);
  759. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  760. return false;
  761. #endif // BX_PLATFORM_WINDOWS
  762. }
  763. bool compileHLSLShaderDx11(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  764. {
  765. #if BX_PLATFORM_WINDOWS
  766. const char* profile = _cmdLine.findOption('p', "profile");
  767. if (NULL == profile)
  768. {
  769. fprintf(stderr, "Shader profile must be specified.\n");
  770. return false;
  771. }
  772. bool debug = _cmdLine.hasArg('\0', "debug");
  773. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  774. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  775. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  776. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
  777. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  778. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  779. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  780. bool werror = _cmdLine.hasArg('\0', "Werror");
  781. if (werror)
  782. {
  783. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  784. }
  785. uint32_t optimization = 3;
  786. if (_cmdLine.hasArg(optimization, 'O') )
  787. {
  788. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx11)-1);
  789. flags |= s_optimizationLevelDx11[optimization];
  790. }
  791. else
  792. {
  793. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  794. }
  795. BX_TRACE("Profile: %s", profile);
  796. BX_TRACE("Flags: 0x%08x", flags);
  797. ID3DBlob* code;
  798. ID3DBlob* errorMsg;
  799. // Output preprocessed shader so that HLSL can be debugged via GPA
  800. // or PIX. Compiling through memory won't embed preprocessed shader
  801. // file path.
  802. std::string hlslfp;
  803. if (debug)
  804. {
  805. hlslfp = _cmdLine.findOption('o');
  806. hlslfp += ".hlsl";
  807. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  808. }
  809. HRESULT hr = D3DCompile(_code.c_str()
  810. , _code.size()
  811. , hlslfp.c_str()
  812. , NULL
  813. , NULL
  814. , "main"
  815. , profile
  816. , flags
  817. , 0
  818. , &code
  819. , &errorMsg
  820. );
  821. if (FAILED(hr)
  822. || (werror && NULL != errorMsg) )
  823. {
  824. const char* log = (char*)errorMsg->GetBufferPointer();
  825. int32_t line = 0;
  826. int32_t column = 0;
  827. int32_t start = 0;
  828. int32_t end = INT32_MAX;
  829. if (2 == sscanf(log, "(%u,%u):", &line, &column)
  830. && 0 != line)
  831. {
  832. start = bx::uint32_imax(1, line-10);
  833. end = start + 20;
  834. }
  835. printCode(_code.c_str(), line, start, end);
  836. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  837. errorMsg->Release();
  838. return false;
  839. }
  840. UniformArray uniforms;
  841. ID3D11ShaderReflection* reflect = NULL;
  842. hr = D3DReflect(code->GetBufferPointer()
  843. , code->GetBufferSize()
  844. , IID_ID3D11ShaderReflection
  845. , (void**)&reflect
  846. );
  847. if (FAILED(hr) )
  848. {
  849. fprintf(stderr, "Error: 0x%08x\n", (uint32_t)hr);
  850. return false;
  851. }
  852. D3D11_SHADER_DESC desc;
  853. hr = reflect->GetDesc(&desc);
  854. if (FAILED(hr) )
  855. {
  856. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr);
  857. return false;
  858. }
  859. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  860. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  861. BX_TRACE("Input:");
  862. uint8_t attrMask[Attrib::Count];
  863. memset(attrMask, 0, sizeof(attrMask) );
  864. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  865. {
  866. D3D11_SIGNATURE_PARAMETER_DESC spd;
  867. reflect->GetInputParameterDesc(ii, &spd);
  868. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  869. , ii
  870. , spd.SemanticName
  871. , spd.SemanticIndex
  872. , spd.SystemValueType
  873. , spd.ComponentType
  874. , spd.Mask
  875. , spd.Register
  876. );
  877. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
  878. if (ris.m_attr != Attrib::Count)
  879. {
  880. attrMask[ris.m_attr] = 0xff;
  881. }
  882. }
  883. bx::write(_writer, attrMask, sizeof(attrMask) );
  884. BX_TRACE("Output:");
  885. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  886. {
  887. D3D11_SIGNATURE_PARAMETER_DESC spd;
  888. reflect->GetOutputParameterDesc(ii, &spd);
  889. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  890. }
  891. uint16_t size = 0;
  892. for (uint32_t ii = 0; ii < bx::uint32_min(1, desc.ConstantBuffers); ++ii)
  893. {
  894. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  895. D3D11_SHADER_BUFFER_DESC bufferDesc;
  896. hr = cbuffer->GetDesc(&bufferDesc);
  897. size = (uint16_t)bufferDesc.Size;
  898. if (SUCCEEDED(hr) )
  899. {
  900. BX_TRACE("%s, %d, vars %d, size %d"
  901. , bufferDesc.Name
  902. , bufferDesc.Type
  903. , bufferDesc.Variables
  904. , bufferDesc.Size
  905. );
  906. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  907. {
  908. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  909. ID3D11ShaderReflectionType* type = var->GetType();
  910. D3D11_SHADER_VARIABLE_DESC varDesc;
  911. hr = var->GetDesc(&varDesc);
  912. if (SUCCEEDED(hr) )
  913. {
  914. D3D11_SHADER_TYPE_DESC constDesc;
  915. hr = type->GetDesc(&constDesc);
  916. if (SUCCEEDED(hr) )
  917. {
  918. ConstantType::Enum type = findConstantTypeDx11(constDesc, varDesc.Size);
  919. if (ConstantType::Count != type
  920. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  921. {
  922. Uniform un;
  923. un.name = varDesc.Name;
  924. un.type = type;
  925. un.num = constDesc.Elements;
  926. un.regIndex = varDesc.StartOffset;
  927. un.regCount = BX_ALIGN_16(varDesc.Size)/16;
  928. uniforms.push_back(un);
  929. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d"
  930. , varDesc.Name
  931. , varDesc.StartOffset
  932. , varDesc.Size
  933. , varDesc.uFlags
  934. , type
  935. );
  936. }
  937. }
  938. }
  939. }
  940. }
  941. }
  942. BX_TRACE("Bound:");
  943. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  944. {
  945. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  946. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  947. if (SUCCEEDED(hr) )
  948. {
  949. // if (bindDesc.Type == D3D_SIT_SAMPLER)
  950. {
  951. BX_TRACE("\t%s, %d, %d, %d"
  952. , bindDesc.Name
  953. , bindDesc.Type
  954. , bindDesc.BindPoint
  955. , bindDesc.BindCount
  956. );
  957. }
  958. }
  959. }
  960. uint16_t count = (uint16_t)uniforms.size();
  961. bx::write(_writer, count);
  962. bx::write(_writer, size);
  963. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  964. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  965. {
  966. const Uniform& un = *it;
  967. uint8_t nameSize = (uint8_t)un.name.size();
  968. bx::write(_writer, nameSize);
  969. bx::write(_writer, un.name.c_str(), nameSize);
  970. uint8_t type = un.type|fragmentBit;
  971. bx::write(_writer, type);
  972. bx::write(_writer, un.num);
  973. bx::write(_writer, un.regIndex);
  974. bx::write(_writer, un.regCount);
  975. BX_TRACE("%s, %s, %d, %d, %d"
  976. , un.name.c_str()
  977. , s_constantTypeName[un.type]
  978. , un.num
  979. , un.regIndex
  980. , un.regCount
  981. );
  982. }
  983. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  984. bx::write(_writer, shaderSize);
  985. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  986. uint8_t nul = 0;
  987. bx::write(_writer, nul);
  988. if (_cmdLine.hasArg('\0', "disasm") )
  989. {
  990. ID3DBlob* disasm;
  991. D3DDisassemble(code->GetBufferPointer()
  992. , code->GetBufferSize()
  993. , 0
  994. , NULL
  995. , &disasm
  996. );
  997. if (NULL != disasm)
  998. {
  999. std::string disasmfp = _cmdLine.findOption('o');
  1000. disasmfp += ".disasm";
  1001. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  1002. disasm->Release();
  1003. }
  1004. }
  1005. if (NULL != reflect)
  1006. {
  1007. reflect->Release();
  1008. }
  1009. if (NULL != errorMsg)
  1010. {
  1011. errorMsg->Release();
  1012. }
  1013. code->Release();
  1014. return true;
  1015. #else
  1016. BX_UNUSED(_cmdLine, _code, _writer);
  1017. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  1018. return false;
  1019. #endif // BX_PLATFORM_WINDOWS
  1020. }
  1021. struct Preprocessor
  1022. {
  1023. Preprocessor(const char* _filePath, bool _gles, const char* _includeDir = NULL)
  1024. : m_tagptr(m_tags)
  1025. , m_scratchPos(0)
  1026. , m_fgetsPos(0)
  1027. {
  1028. m_tagptr->tag = FPPTAG_USERDATA;
  1029. m_tagptr->data = this;
  1030. m_tagptr++;
  1031. m_tagptr->tag = FPPTAG_DEPENDS;
  1032. m_tagptr->data = (void*)fppDepends;
  1033. m_tagptr++;
  1034. m_tagptr->tag = FPPTAG_INPUT;
  1035. m_tagptr->data = (void*)fppInput;
  1036. m_tagptr++;
  1037. m_tagptr->tag = FPPTAG_OUTPUT;
  1038. m_tagptr->data = (void*)fppOutput;
  1039. m_tagptr++;
  1040. m_tagptr->tag = FPPTAG_ERROR;
  1041. m_tagptr->data = (void*)fppError;
  1042. m_tagptr++;
  1043. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  1044. m_tagptr->data = (void*)0;
  1045. m_tagptr++;
  1046. m_tagptr->tag = FPPTAG_LINE;
  1047. m_tagptr->data = (void*)0;
  1048. m_tagptr++;
  1049. m_tagptr->tag = FPPTAG_INPUT_NAME;
  1050. m_tagptr->data = scratch(_filePath);
  1051. m_tagptr++;
  1052. if (NULL != _includeDir)
  1053. {
  1054. addInclude(_includeDir);
  1055. }
  1056. if (!_gles)
  1057. {
  1058. m_default = "#define lowp\n#define mediump\n#define highp\n";
  1059. }
  1060. }
  1061. void setDefine(const char* _define)
  1062. {
  1063. m_tagptr->tag = FPPTAG_DEFINE;
  1064. m_tagptr->data = scratch(_define);
  1065. m_tagptr++;
  1066. }
  1067. void setDefaultDefine(const char* _name)
  1068. {
  1069. char temp[1024];
  1070. bx::snprintf(temp, BX_COUNTOF(temp)
  1071. , "#ifndef %s\n"
  1072. "# define %s 0\n"
  1073. "#endif // %s\n"
  1074. "\n"
  1075. , _name
  1076. , _name
  1077. , _name
  1078. );
  1079. m_default += temp;
  1080. }
  1081. void writef(const char* _format, ...)
  1082. {
  1083. va_list argList;
  1084. va_start(argList, _format);
  1085. bx::stringPrintfVargs(m_default, _format, argList);
  1086. va_end(argList);
  1087. }
  1088. void addInclude(const char* _includeDir)
  1089. {
  1090. char* start = scratch(_includeDir);
  1091. for (char* split = strchr(start, ';'); NULL != split; split = strchr(start, ';'))
  1092. {
  1093. *split = '\0';
  1094. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1095. m_tagptr->data = start;
  1096. m_tagptr++;
  1097. start = split + 1;
  1098. }
  1099. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1100. m_tagptr->data = start;
  1101. m_tagptr++;
  1102. }
  1103. void addDependency(const char* _fileName)
  1104. {
  1105. m_depends += " \\\n ";
  1106. m_depends += _fileName;
  1107. }
  1108. bool run(const char* _input)
  1109. {
  1110. m_fgetsPos = 0;
  1111. m_preprocessed.clear();
  1112. m_input = m_default;
  1113. m_input += "\n\n";
  1114. size_t len = strlen(_input)+1;
  1115. char* temp = new char[len];
  1116. bx::eolLF(temp, len, _input);
  1117. m_input += temp;
  1118. delete [] temp;
  1119. fppTag* tagptr = m_tagptr;
  1120. tagptr->tag = FPPTAG_END;
  1121. tagptr->data = 0;
  1122. tagptr++;
  1123. int result = fppPreProcess(m_tags);
  1124. return 0 == result;
  1125. }
  1126. char* fgets(char* _buffer, int _size)
  1127. {
  1128. int ii = 0;
  1129. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  1130. {
  1131. _buffer[ii++] = ch;
  1132. if (ch == '\n' || ii == _size)
  1133. {
  1134. _buffer[ii] = '\0';
  1135. m_fgetsPos++;
  1136. return _buffer;
  1137. }
  1138. }
  1139. return NULL;
  1140. }
  1141. static void fppDepends(char* _fileName, void* _userData)
  1142. {
  1143. Preprocessor* thisClass = (Preprocessor*)_userData;
  1144. thisClass->addDependency(_fileName);
  1145. }
  1146. static char* fppInput(char* _buffer, int _size, void* _userData)
  1147. {
  1148. Preprocessor* thisClass = (Preprocessor*)_userData;
  1149. return thisClass->fgets(_buffer, _size);
  1150. }
  1151. static void fppOutput(int _ch, void* _userData)
  1152. {
  1153. Preprocessor* thisClass = (Preprocessor*)_userData;
  1154. thisClass->m_preprocessed += _ch;
  1155. }
  1156. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  1157. {
  1158. vfprintf(stderr, _format, _vargs);
  1159. }
  1160. char* scratch(const char* _str)
  1161. {
  1162. char* result = &m_scratch[m_scratchPos];
  1163. strcpy(result, _str);
  1164. m_scratchPos += (uint32_t)strlen(_str)+1;
  1165. return result;
  1166. }
  1167. fppTag m_tags[MAX_TAGS];
  1168. fppTag* m_tagptr;
  1169. std::string m_depends;
  1170. std::string m_default;
  1171. std::string m_input;
  1172. std::string m_preprocessed;
  1173. char m_scratch[16<<10];
  1174. uint32_t m_scratchPos;
  1175. uint32_t m_fgetsPos;
  1176. };
  1177. const char* baseName(const char* _filePath)
  1178. {
  1179. const char* bs = strrchr(_filePath, '\\');
  1180. const char* fs = strrchr(_filePath, '/');
  1181. const char* column = strrchr(_filePath, ':');
  1182. const char* basename = std::max(std::max(bs, fs), column);
  1183. if (NULL != basename)
  1184. {
  1185. return basename+1;
  1186. }
  1187. return _filePath;
  1188. }
  1189. typedef std::vector<std::string> InOut;
  1190. uint32_t parseInOut(InOut& _inout, const char* _str, const char* _eol)
  1191. {
  1192. uint32_t hash = 0;
  1193. _str = bx::strws(_str);
  1194. if (_str < _eol)
  1195. {
  1196. const char* delim;
  1197. do
  1198. {
  1199. delim = strpbrk(_str, " ,");
  1200. if (NULL != delim)
  1201. {
  1202. delim = delim > _eol ? _eol : delim;
  1203. std::string token;
  1204. token.assign(_str, delim-_str);
  1205. _inout.push_back(token);
  1206. _str = bx::strws(delim + 1);
  1207. }
  1208. }
  1209. while (delim < _eol && _str < _eol && NULL != delim);
  1210. std::sort(_inout.begin(), _inout.end() );
  1211. bx::HashMurmur2A murmur;
  1212. murmur.begin();
  1213. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  1214. {
  1215. murmur.add(it->c_str(), (uint32_t)it->size() );
  1216. }
  1217. hash = murmur.end();
  1218. }
  1219. return hash;
  1220. }
  1221. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  1222. {
  1223. char find[32];
  1224. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  1225. char replace[32];
  1226. bx::snprintf(replace, sizeof(replace), "gl_FragData_%d_", _idx);
  1227. strreplace(_data, find, replace);
  1228. _preprocessor.writef(
  1229. " \\\n\t%sout vec4 gl_FragData_%d_ : SV_TARGET%d"
  1230. , _comma ? ", " : " "
  1231. , _idx
  1232. , _idx
  1233. );
  1234. }
  1235. // c - compute
  1236. // d - domain
  1237. // f - fragment
  1238. // g - geometry
  1239. // h - hull
  1240. // v - vertex
  1241. //
  1242. // OpenGL #version Features Direct3D Features Shader Model
  1243. // 2.1 120 vf 9.0 vf 2.0
  1244. // 3.0 130
  1245. // 3.1 140
  1246. // 3.2 150 vgf
  1247. // 3.3 330 10.0 vgf 4.0
  1248. // 4.0 400 vhdgf
  1249. // 4.1 410
  1250. // 4.2 420 11.0 vhdgf+c 5.0
  1251. // 4.3 430 vhdgf+c
  1252. void help(const char* _error = NULL)
  1253. {
  1254. if (NULL != _error)
  1255. {
  1256. fprintf(stderr, "Error:\n%s\n\n", _error);
  1257. }
  1258. fprintf(stderr
  1259. , "shaderc, bgfx shader compiler tool\n"
  1260. "Copyright 2011-2014 Branimir Karadzic. All rights reserved.\n"
  1261. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  1262. );
  1263. fprintf(stderr
  1264. , "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  1265. "\n"
  1266. "Options:\n"
  1267. " -f <file path> Input file path.\n"
  1268. " -i <include path> Include path (for multiple paths use semicolon).\n"
  1269. " -o <file path> Output file path.\n"
  1270. " --bin2c <file path> Generate C header file.\n"
  1271. " --depends <file path> Generate makefile style depends file.\n"
  1272. " --platform <platform> Target platform.\n"
  1273. " android\n"
  1274. " ios\n"
  1275. " linux\n"
  1276. " nacl\n"
  1277. " osx\n"
  1278. " windows\n"
  1279. " --type <type> Shader type (vertex, fragment)\n"
  1280. " --varyingdef <file path> Path to varying.def.sc file.\n"
  1281. "\n"
  1282. "Options (DX9 and DX11 only):\n"
  1283. "\n"
  1284. " --debug Debug information.\n"
  1285. " --disasm Disassemble compiled shader.\n"
  1286. " -p, --profile <profile> Shader model (f.e. ps_3_0).\n"
  1287. " -O <level> Optimization level (0, 1, 2, 3).\n"
  1288. " --Werror Treat warnings as errors.\n"
  1289. "\n"
  1290. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  1291. );
  1292. }
  1293. int main(int _argc, const char* _argv[])
  1294. {
  1295. bx::CommandLine cmdLine(_argc, _argv);
  1296. if (cmdLine.hasArg('h', "help") )
  1297. {
  1298. help();
  1299. return EXIT_FAILURE;
  1300. }
  1301. const char* filePath = cmdLine.findOption('f');
  1302. if (NULL == filePath)
  1303. {
  1304. help("Shader file name must be specified.");
  1305. return EXIT_FAILURE;
  1306. }
  1307. const char* outFilePath = cmdLine.findOption('o');
  1308. if (NULL == outFilePath)
  1309. {
  1310. help("Output file name must be specified.");
  1311. return EXIT_FAILURE;
  1312. }
  1313. const char* type = cmdLine.findOption('\0', "type");
  1314. if (NULL == type)
  1315. {
  1316. help("Must specify shader type.");
  1317. return EXIT_FAILURE;
  1318. }
  1319. const char* platform = cmdLine.findOption('\0', "platform");
  1320. if (NULL == platform)
  1321. {
  1322. help("Must specify platform.");
  1323. return EXIT_FAILURE;
  1324. }
  1325. uint32_t gles = 0;
  1326. uint32_t hlsl = 2;
  1327. const char* profile = cmdLine.findOption('p', "profile");
  1328. if (NULL != profile)
  1329. {
  1330. if (0 == strncmp(&profile[1], "s_3", 3) )
  1331. {
  1332. hlsl = 3;
  1333. }
  1334. else if (0 == strncmp(&profile[1], "s_4", 3) )
  1335. {
  1336. hlsl = 4;
  1337. }
  1338. else if (0 == strncmp(&profile[1], "s_5", 3) )
  1339. {
  1340. hlsl = 5;
  1341. }
  1342. }
  1343. else
  1344. {
  1345. gles = 2;
  1346. }
  1347. const char* bin2c = NULL;
  1348. if (cmdLine.hasArg("bin2c") )
  1349. {
  1350. bin2c = cmdLine.findOption("bin2c");
  1351. if (NULL == bin2c)
  1352. {
  1353. bin2c = baseName(outFilePath);
  1354. uint32_t len = (uint32_t)strlen(bin2c);
  1355. char* temp = (char*)alloca(len+1);
  1356. for (char *out = temp; *bin2c != '\0';)
  1357. {
  1358. char ch = *bin2c++;
  1359. if (isalnum(ch) )
  1360. {
  1361. *out++ = ch;
  1362. }
  1363. else
  1364. {
  1365. *out++ = '_';
  1366. }
  1367. }
  1368. temp[len] = '\0';
  1369. bin2c = temp;
  1370. }
  1371. }
  1372. bool depends = cmdLine.hasArg("depends");
  1373. bool preprocessOnly = cmdLine.hasArg("preprocess");
  1374. const char* includeDir = cmdLine.findOption('i');
  1375. Preprocessor preprocessor(filePath, 0 != gles, includeDir);
  1376. std::string dir;
  1377. {
  1378. const char* base = baseName(filePath);
  1379. if (base != filePath)
  1380. {
  1381. dir.assign(filePath, base-filePath);
  1382. preprocessor.addInclude(dir.c_str() );
  1383. }
  1384. }
  1385. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  1386. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  1387. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  1388. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  1389. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  1390. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  1391. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  1392. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  1393. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  1394. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  1395. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  1396. bool glsl = false;
  1397. if (0 == bx::stricmp(platform, "android") )
  1398. {
  1399. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  1400. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1401. glsl = true;
  1402. }
  1403. else if (0 == bx::stricmp(platform, "ios") )
  1404. {
  1405. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1406. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1407. glsl = true;
  1408. }
  1409. else if (0 == bx::stricmp(platform, "linux") )
  1410. {
  1411. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  1412. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1413. glsl = true;
  1414. }
  1415. else if (0 == bx::stricmp(platform, "nacl") )
  1416. {
  1417. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  1418. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1419. glsl = true;
  1420. }
  1421. else if (0 == bx::stricmp(platform, "osx") )
  1422. {
  1423. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  1424. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1425. glsl = true;
  1426. }
  1427. else if (0 == bx::stricmp(platform, "windows") )
  1428. {
  1429. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  1430. char temp[256];
  1431. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  1432. preprocessor.setDefine(temp);
  1433. }
  1434. else if (0 == bx::stricmp(platform, "xbox360") )
  1435. {
  1436. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  1437. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=3");
  1438. }
  1439. else
  1440. {
  1441. fprintf(stderr, "Unknown platform %s?!", platform);
  1442. return EXIT_FAILURE;
  1443. }
  1444. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  1445. bool fragment = false;
  1446. switch (tolower(type[0]) )
  1447. {
  1448. case 'f':
  1449. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1450. fragment = true;
  1451. break;
  1452. case 'v':
  1453. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1454. break;
  1455. default:
  1456. fprintf(stderr, "Unknown type: %s?!", type);
  1457. return EXIT_FAILURE;
  1458. }
  1459. FILE* file = fopen(filePath, "r");
  1460. if (NULL != file)
  1461. {
  1462. VaryingMap varyingMap;
  1463. std::string defaultVarying = dir + "varying.def.sc";
  1464. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  1465. File attribdef(varyingdef);
  1466. const char* parse = attribdef.getData();
  1467. if (NULL != parse
  1468. && *parse != '\0')
  1469. {
  1470. preprocessor.addDependency(varyingdef);
  1471. }
  1472. while (NULL != parse
  1473. && *parse != '\0')
  1474. {
  1475. parse = bx::strws(parse);
  1476. const char* eol = strchr(parse, ';');
  1477. if (NULL != eol)
  1478. {
  1479. const char* precision = NULL;
  1480. const char* type = parse;
  1481. if (0 == strncmp(type, "lowp", 4)
  1482. || 0 == strncmp(type, "mediump", 7)
  1483. || 0 == strncmp(type, "highp", 5) )
  1484. {
  1485. precision = type;
  1486. type = parse = bx::strws(bx::strword(parse) );
  1487. }
  1488. const char* name = parse = bx::strws(bx::strword(parse) );
  1489. const char* column = parse = bx::strws(bx::strword(parse) );
  1490. const char* semantics = parse = bx::strws(bx::strnws(parse) );
  1491. const char* assign = parse = bx::strws(bx::strword(parse) );
  1492. const char* init = parse = bx::strws(bx::strnws(parse) );
  1493. if (type < eol
  1494. && name < eol
  1495. && column < eol
  1496. && ':' == *column
  1497. && semantics < eol)
  1498. {
  1499. Varying var;
  1500. if (NULL != precision)
  1501. {
  1502. var.m_precision.assign(precision, bx::strword(precision)-precision);
  1503. }
  1504. var.m_type.assign(type, bx::strword(type)-type);
  1505. var.m_name.assign(name, bx::strword(name)-name);
  1506. var.m_semantics.assign(semantics, bx::strword(semantics)-semantics);
  1507. if (assign < eol
  1508. && '=' == *assign
  1509. && init < eol)
  1510. {
  1511. var.m_init.assign(init, eol-init);
  1512. }
  1513. varyingMap.insert(std::make_pair(var.m_name, var) );
  1514. }
  1515. parse = bx::strnl(eol);
  1516. }
  1517. }
  1518. char* data;
  1519. {
  1520. const size_t padding = 16;
  1521. uint32_t size = (uint32_t)fsize(file);
  1522. data = new char[size+padding+1];
  1523. size = (uint32_t)fread(data, 1, size, file);
  1524. // Compiler generates "error X3000: syntax error: unexpected end of file"
  1525. // if input doesn't have empty line at EOF.
  1526. data[size] = '\n';
  1527. memset(&data[size+1], 0, padding);
  1528. fclose(file);
  1529. // To avoid commented code being recognized as used feature,
  1530. // first preprocess pass is used to strip all comments before
  1531. // substituting code.
  1532. preprocessor.run(data);
  1533. delete [] data;
  1534. size = preprocessor.m_preprocessed.size();
  1535. data = new char[size+padding+1];
  1536. memcpy(data, preprocessor.m_preprocessed.c_str(), size);
  1537. memset(&data[size], 0, padding+1);
  1538. }
  1539. char* entry = strstr(data, "void main()");
  1540. if (NULL == entry)
  1541. {
  1542. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1543. }
  1544. else
  1545. {
  1546. InOut shaderInputs;
  1547. InOut shaderOutputs;
  1548. uint32_t inputHash = 0;
  1549. uint32_t outputHash = 0;
  1550. const char* input = data;
  1551. while (input[0] == '$')
  1552. {
  1553. const char* str = input+1;
  1554. const char* eol = bx::streol(str);
  1555. const char* nl = bx::strnl(eol);
  1556. input = nl;
  1557. if (0 == strncmp(str, "input", 5) )
  1558. {
  1559. str += 5;
  1560. const char* comment = strstr(str, "//");
  1561. eol = NULL != comment && comment < eol ? comment : eol;
  1562. inputHash = parseInOut(shaderInputs, str, eol);
  1563. }
  1564. else if (0 == strncmp(str, "output", 6) )
  1565. {
  1566. str += 6;
  1567. const char* comment = strstr(str, "//");
  1568. eol = NULL != comment && comment < eol ? comment : eol;
  1569. outputHash = parseInOut(shaderOutputs, str, eol);
  1570. }
  1571. }
  1572. if (glsl)
  1573. {
  1574. preprocessor.writef(
  1575. "#define ivec2 vec2\n"
  1576. "#define ivec3 vec3\n"
  1577. "#define ivec4 vec4\n"
  1578. );
  1579. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1580. {
  1581. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1582. if (varyingIt != varyingMap.end() )
  1583. {
  1584. const Varying& var = varyingIt->second;
  1585. const char* name = var.m_name.c_str();
  1586. if (0 == strncmp(name, "a_", 2)
  1587. || 0 == strncmp(name, "i_", 2) )
  1588. {
  1589. preprocessor.writef("attribute %s %s %s;\n"
  1590. , var.m_precision.c_str()
  1591. , var.m_type.c_str()
  1592. , name
  1593. );
  1594. }
  1595. else
  1596. {
  1597. preprocessor.writef("varying %s %s %s;\n"
  1598. , var.m_precision.c_str()
  1599. , var.m_type.c_str()
  1600. , name
  1601. );
  1602. }
  1603. }
  1604. }
  1605. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1606. {
  1607. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1608. if (varyingIt != varyingMap.end() )
  1609. {
  1610. const Varying& var = varyingIt->second;
  1611. preprocessor.writef("varying %s %s;\n", var.m_type.c_str(), var.m_name.c_str() );
  1612. }
  1613. }
  1614. }
  1615. else
  1616. {
  1617. preprocessor.writef(
  1618. "#define lowp\n"
  1619. "#define mediump\n"
  1620. "#define highp\n"
  1621. "#define ivec2 int2\n"
  1622. "#define ivec3 int3\n"
  1623. "#define ivec4 int4\n"
  1624. "#define vec2 float2\n"
  1625. "#define vec3 float3\n"
  1626. "#define vec4 float4\n"
  1627. "#define mat2 float2x2\n"
  1628. "#define mat3 float3x3\n"
  1629. "#define mat4 float4x4\n"
  1630. );
  1631. entry[4] = '_';
  1632. if (fragment)
  1633. {
  1634. const bool hasFragCoord = NULL != strstr(data, "gl_FragCoord") || hlsl > 3;
  1635. const bool hasFragDepth = NULL != strstr(data, "gl_FragDepth");
  1636. const bool hasFrontFacing = NULL != strstr(data, "gl_FrontFacing");
  1637. const bool hasFragData0 = NULL != strstr(data, "gl_FragData[0]");
  1638. const bool hasFragData1 = NULL != strstr(data, "gl_FragData[1]");
  1639. const bool hasFragData2 = NULL != strstr(data, "gl_FragData[2]");
  1640. const bool hasFragData3 = NULL != strstr(data, "gl_FragData[3]");
  1641. if (!hasFragData0
  1642. && !hasFragData1
  1643. && !hasFragData2
  1644. && !hasFragData3)
  1645. {
  1646. // GL errors when both gl_FragColor and gl_FragData is used.
  1647. // This will trigger the same error with HLSL compiler too.
  1648. preprocessor.writef("#define gl_FragColor gl_FragData_0_\n");
  1649. }
  1650. preprocessor.writef("#define void_main()");
  1651. preprocessor.writef(" \\\n\tvoid main(");
  1652. uint32_t arg = 0;
  1653. if (hasFragCoord)
  1654. {
  1655. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1656. ++arg;
  1657. }
  1658. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1659. {
  1660. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1661. if (varyingIt != varyingMap.end() )
  1662. {
  1663. const Varying& var = varyingIt->second;
  1664. preprocessor.writef(" \\\n\t%s%s %s : %s", arg++ > 0 ? ", " : " ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1665. }
  1666. }
  1667. addFragData(preprocessor, data, 0, arg++ > 0);
  1668. if (hasFragData1)
  1669. {
  1670. addFragData(preprocessor, data, 1, arg++ > 0);
  1671. }
  1672. if (hasFragData2)
  1673. {
  1674. addFragData(preprocessor, data, 2, arg++ > 0);
  1675. }
  1676. if (hasFragData3)
  1677. {
  1678. addFragData(preprocessor, data, 3, arg++ > 0);
  1679. }
  1680. if (hasFragDepth)
  1681. {
  1682. preprocessor.writef(
  1683. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1684. , arg++ > 0 ? ", " : " "
  1685. );
  1686. }
  1687. if (hasFrontFacing)
  1688. {
  1689. preprocessor.writef(
  1690. " \\\n\t%sfloat __vface : VFACE"
  1691. , arg++ > 0 ? ", " : " "
  1692. );
  1693. }
  1694. preprocessor.writef(
  1695. " \\\n\t)\n"
  1696. );
  1697. if (hasFrontFacing)
  1698. {
  1699. preprocessor.writef(
  1700. "#define gl_FrontFacing (__vface <= 0.0)\n"
  1701. );
  1702. }
  1703. }
  1704. else
  1705. {
  1706. const char* brace = strstr(entry, "{");
  1707. if (NULL != brace)
  1708. {
  1709. const char* end = bx::strmb(brace, '{', '}');
  1710. if (NULL != end)
  1711. {
  1712. strins(const_cast<char*>(end), "__RETURN__;\n");
  1713. }
  1714. }
  1715. preprocessor.writef(
  1716. "struct Output\n"
  1717. "{\n"
  1718. "\tvec4 gl_Position : SV_POSITION;\n"
  1719. "#define gl_Position _varying_.gl_Position\n"
  1720. );
  1721. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1722. {
  1723. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1724. if (varyingIt != varyingMap.end() )
  1725. {
  1726. const Varying& var = varyingIt->second;
  1727. preprocessor.writef("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1728. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  1729. }
  1730. }
  1731. preprocessor.writef(
  1732. "};\n"
  1733. );
  1734. preprocessor.writef("#define void_main() \\\n");
  1735. preprocessor.writef("Output main(");
  1736. bool first = true;
  1737. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1738. {
  1739. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1740. if (varyingIt != varyingMap.end() )
  1741. {
  1742. const Varying& var = varyingIt->second;
  1743. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1744. first = false;
  1745. }
  1746. }
  1747. preprocessor.writef(
  1748. ") \\\n"
  1749. "{ \\\n"
  1750. "\tOutput _varying_;"
  1751. );
  1752. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1753. {
  1754. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1755. if (varyingIt != varyingMap.end() )
  1756. {
  1757. const Varying& var = varyingIt->second;
  1758. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  1759. }
  1760. }
  1761. preprocessor.writef(
  1762. "\n#define __RETURN__ \\\n"
  1763. "\t} \\\n"
  1764. "\treturn _varying_"
  1765. );
  1766. }
  1767. }
  1768. if (preprocessor.run(input) )
  1769. {
  1770. BX_TRACE("Input file: %s", filePath);
  1771. BX_TRACE("Output file: %s", outFilePath);
  1772. if (preprocessOnly)
  1773. {
  1774. bx::CrtFileWriter writer;
  1775. if (0 != writer.open(outFilePath) )
  1776. {
  1777. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1778. return EXIT_FAILURE;
  1779. }
  1780. if (glsl)
  1781. {
  1782. const char* profile = cmdLine.findOption('p', "profile");
  1783. if (NULL == profile)
  1784. {
  1785. writef(&writer
  1786. , "#ifdef GL_ES\n"
  1787. "precision highp float;\n"
  1788. "#endif // GL_ES\n\n"
  1789. );
  1790. }
  1791. }
  1792. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1793. writer.close();
  1794. return EXIT_SUCCESS;
  1795. }
  1796. bool compiled = false;
  1797. {
  1798. bx::CrtFileWriter* writer = NULL;
  1799. if (NULL != bin2c)
  1800. {
  1801. writer = new Bin2cWriter(bin2c);
  1802. }
  1803. else
  1804. {
  1805. writer = new bx::CrtFileWriter;
  1806. }
  1807. if (0 != writer->open(outFilePath) )
  1808. {
  1809. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1810. return EXIT_FAILURE;
  1811. }
  1812. if (fragment)
  1813. {
  1814. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  1815. bx::write(writer, inputHash);
  1816. }
  1817. else
  1818. {
  1819. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  1820. bx::write(writer, outputHash);
  1821. }
  1822. if (glsl)
  1823. {
  1824. std::string code;
  1825. bool hasTextureLod = NULL != bx::findIdentifierMatch(data, s_ARB_shader_texture_lod /*EXT_shader_texture_lod*/);
  1826. if (0 == gles)
  1827. {
  1828. bx::stringPrintf(code, "#version %s\n", profile);
  1829. int32_t version = atoi(profile);
  1830. if (hasTextureLod
  1831. && 130 > version)
  1832. {
  1833. bx::stringPrintf(code
  1834. , "#extension GL_ARB_shader_texture_lod : enable\n"
  1835. );
  1836. }
  1837. }
  1838. else
  1839. {
  1840. // Pretend that all extensions are available.
  1841. // This will be stripped later.
  1842. if (hasTextureLod)
  1843. {
  1844. bx::stringPrintf(code
  1845. , "#extension GL_EXT_shader_texture_lod : enable\n"
  1846. "#define texture2DLod texture2DLodEXT\n"
  1847. "#define texture2DProjLod texture2DProjLodEXT\n"
  1848. "#define textureCubeLod textureCubeLodEXT\n"
  1849. // "#define texture2DGrad texture2DGradEXT\n"
  1850. // "#define texture2DProjGrad texture2DProjGradEXT\n"
  1851. // "#define textureCubeGrad textureCubeGradEXT\n"
  1852. );
  1853. }
  1854. if (NULL != bx::findIdentifierMatch(data, s_OES_standard_derivatives) )
  1855. {
  1856. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  1857. }
  1858. if (NULL != bx::findIdentifierMatch(data, s_OES_texture_3D) )
  1859. {
  1860. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  1861. }
  1862. if (NULL != bx::findIdentifierMatch(data, s_EXT_shadow_samplers) )
  1863. {
  1864. bx::stringPrintf(code
  1865. , "#extension GL_EXT_shadow_samplers : enable\n"
  1866. "#define shadow2D shadow2DEXT\n"
  1867. "#define shadow2DProj shadow2DProjEXT\n"
  1868. );
  1869. }
  1870. if (NULL != bx::findIdentifierMatch(data, "gl_FragDepth") )
  1871. {
  1872. bx::stringPrintf(code
  1873. , "#extension GL_EXT_frag_depth : enable\n"
  1874. "#define gl_FragDepth gl_FragDepthEXT\n"
  1875. );
  1876. }
  1877. }
  1878. code += preprocessor.m_preprocessed;
  1879. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  1880. }
  1881. else
  1882. {
  1883. if (hlsl > 3)
  1884. {
  1885. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1886. }
  1887. else
  1888. {
  1889. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1890. }
  1891. }
  1892. writer->close();
  1893. delete writer;
  1894. }
  1895. if (compiled)
  1896. {
  1897. if (depends)
  1898. {
  1899. std::string ofp = outFilePath;
  1900. ofp += ".d";
  1901. bx::CrtFileWriter writer;
  1902. if (0 == writer.open(ofp.c_str() ) )
  1903. {
  1904. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1905. writer.close();
  1906. }
  1907. }
  1908. return EXIT_SUCCESS;
  1909. }
  1910. }
  1911. }
  1912. delete [] data;
  1913. }
  1914. remove(outFilePath);
  1915. fprintf(stderr, "Failed to build shader.\n");
  1916. return EXIT_FAILURE;
  1917. }