shaderc.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  1. /*
  2. * Copyright 2011-2012 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #define SHADERC_DEBUG 0
  6. #define NOMINMAX
  7. #include <stdio.h>
  8. #include <stdint.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <string>
  12. #include <vector>
  13. #include <unordered_map>
  14. namespace std { namespace tr1 {} using namespace tr1; } // namespace std
  15. #include "glsl_optimizer.h"
  16. #define MAX_TAGS 256
  17. extern "C"
  18. {
  19. #include <fpp.h>
  20. } // extern "C"
  21. #if SHADERC_DEBUG
  22. # define BX_TRACE(_format, ...) fprintf(stderr, "" _format "\n", ##__VA_ARGS__)
  23. #endif // DEBUG
  24. #define BX_NAMESPACE 1
  25. #include <bx/bx.h>
  26. #if BX_PLATFORM_LINUX
  27. # include <stdarg.h>
  28. # define _stricmp strcasecmp
  29. # define _snprintf snprintf
  30. #endif // BX_PLATFORM_LINUX
  31. #include <bx/commandline.h>
  32. #include <bx/countof.h>
  33. #include <bx/endian.h>
  34. #include <bx/uint32_t.h>
  35. #if BX_PLATFORM_WINDOWS
  36. # include <d3dx9.h>
  37. # include <d3dcompiler.h>
  38. #endif // BX_PLATFORM_WINDOWS
  39. long int fsize(FILE* _file)
  40. {
  41. long int pos = ftell(_file);
  42. fseek(_file, 0L, SEEK_END);
  43. long int size = ftell(_file);
  44. fseek(_file, pos, SEEK_SET);
  45. return size;
  46. }
  47. struct Attrib
  48. {
  49. enum Enum
  50. {
  51. Position = 0,
  52. Normal,
  53. Color0,
  54. Color1,
  55. Indices,
  56. Weight,
  57. TexCoord0,
  58. TexCoord1,
  59. TexCoord2,
  60. TexCoord3,
  61. TexCoord4,
  62. TexCoord5,
  63. TexCoord6,
  64. TexCoord7,
  65. Count,
  66. };
  67. };
  68. struct RemapInputSemantic
  69. {
  70. Attrib::Enum m_attr;
  71. const char* m_name;
  72. uint8_t m_index;
  73. };
  74. static const RemapInputSemantic s_remapInputSemantic[Attrib::Count+1] =
  75. {
  76. { Attrib::Position, "POSITION", 0 },
  77. { Attrib::Normal, "NORMAL", 0 },
  78. { Attrib::Color0, "COLOR", 0 },
  79. { Attrib::Color1, "COLOR", 1 },
  80. { Attrib::Indices, "BLENDINDICES", 0 },
  81. { Attrib::Weight, "BLENDWEIGHT", 0 },
  82. { Attrib::TexCoord0, "TEXCOORD", 0 },
  83. { Attrib::TexCoord1, "TEXCOORD", 1 },
  84. { Attrib::TexCoord2, "TEXCOORD", 2 },
  85. { Attrib::TexCoord3, "TEXCOORD", 3 },
  86. { Attrib::TexCoord4, "TEXCOORD", 4 },
  87. { Attrib::TexCoord5, "TEXCOORD", 5 },
  88. { Attrib::TexCoord6, "TEXCOORD", 6 },
  89. { Attrib::TexCoord7, "TEXCOORD", 7 },
  90. { Attrib::Count, "", 0 },
  91. };
  92. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  93. {
  94. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  95. {
  96. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  97. if (0 == strcmp(ris.m_name, _name)
  98. && ris.m_index == _index)
  99. {
  100. return ris;
  101. }
  102. }
  103. return s_remapInputSemantic[Attrib::Count];
  104. }
  105. struct ConstantType
  106. {
  107. enum Enum
  108. {
  109. Uniform1i,
  110. Uniform1f,
  111. End,
  112. Uniform1iv,
  113. Uniform1fv,
  114. Uniform2fv,
  115. Uniform3fv,
  116. Uniform4fv,
  117. Uniform3x3fv,
  118. Uniform4x4fv,
  119. Count,
  120. TypeMask = 0x7f,
  121. FragmentBit = 0x80
  122. };
  123. };
  124. static const char* s_constantTypeName[ConstantType::Count] =
  125. {
  126. "int",
  127. "float",
  128. NULL,
  129. "int",
  130. "float",
  131. "float2",
  132. "float3",
  133. "float4",
  134. "float3x3",
  135. "float4x4",
  136. };
  137. struct Uniform
  138. {
  139. std::string name;
  140. ConstantType::Enum type;
  141. uint8_t num;
  142. uint16_t regIndex;
  143. uint16_t regCount;
  144. };
  145. typedef std::vector<Uniform> UniformArray;
  146. #if BX_PLATFORM_WINDOWS
  147. struct ConstRemapDx9
  148. {
  149. ConstantType::Enum id;
  150. D3DXPARAMETER_CLASS paramClass;
  151. D3DXPARAMETER_TYPE paramType;
  152. uint32_t paramBytes;
  153. };
  154. static const ConstRemapDx9 s_constRemapDx9[7] =
  155. {
  156. { ConstantType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 4 },
  157. { ConstantType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 4 },
  158. { ConstantType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 8 },
  159. { ConstantType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 12 },
  160. { ConstantType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 16 },
  161. { ConstantType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 36 },
  162. { ConstantType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 64 },
  163. };
  164. ConstantType::Enum findConstantTypeDx9(const D3DXCONSTANT_DESC& constDesc)
  165. {
  166. uint32_t count = sizeof(s_constRemapDx9)/sizeof(ConstRemapDx9);
  167. for (uint32_t ii = 0; ii < count; ++ii)
  168. {
  169. const ConstRemapDx9& remap = s_constRemapDx9[ii];
  170. if (remap.paramClass == constDesc.Class
  171. && remap.paramType == constDesc.Type
  172. && (constDesc.Bytes%remap.paramBytes) == 0)
  173. {
  174. return remap.id;
  175. }
  176. }
  177. return ConstantType::Count;
  178. }
  179. static uint32_t s_optimizationLevelDx9[4] =
  180. {
  181. D3DXSHADER_OPTIMIZATION_LEVEL0,
  182. D3DXSHADER_OPTIMIZATION_LEVEL1,
  183. D3DXSHADER_OPTIMIZATION_LEVEL2,
  184. D3DXSHADER_OPTIMIZATION_LEVEL3,
  185. };
  186. struct ConstRemapDx11
  187. {
  188. ConstantType::Enum id;
  189. D3D_SHADER_VARIABLE_CLASS paramClass;
  190. D3D_SHADER_VARIABLE_TYPE paramType;
  191. uint32_t paramBytes;
  192. };
  193. static const ConstRemapDx11 s_constRemapDx11[7] =
  194. {
  195. { ConstantType::Uniform1iv, D3D_SVC_SCALAR, D3D_SVT_INT, 4 },
  196. { ConstantType::Uniform1fv, D3D_SVC_SCALAR, D3D_SVT_FLOAT, 4 },
  197. { ConstantType::Uniform2fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 8 },
  198. { ConstantType::Uniform3fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 12 },
  199. { ConstantType::Uniform4fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 16 },
  200. { ConstantType::Uniform3x3fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 36 },
  201. { ConstantType::Uniform4x4fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 64 },
  202. };
  203. ConstantType::Enum findConstantTypeDx11(const D3D11_SHADER_TYPE_DESC& constDesc, uint32_t _size)
  204. {
  205. uint32_t count = sizeof(s_constRemapDx11)/sizeof(ConstRemapDx9);
  206. for (uint32_t ii = 0; ii < count; ++ii)
  207. {
  208. const ConstRemapDx11& remap = s_constRemapDx11[ii];
  209. if (remap.paramClass == constDesc.Class
  210. && remap.paramType == constDesc.Type
  211. && remap.paramBytes == _size)
  212. {
  213. return remap.id;
  214. }
  215. }
  216. return ConstantType::Count;
  217. }
  218. static uint32_t s_optimizationLevelDx11[4] =
  219. {
  220. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  221. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  222. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  223. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  224. };
  225. #endif // BX_PLATFORM_WINDOWS
  226. class IStreamWriter
  227. {
  228. public:
  229. virtual ~IStreamWriter() = 0;
  230. virtual bool open() = 0;
  231. virtual void close() = 0;
  232. virtual void writef(const char* _format, ...) = 0;
  233. virtual void write(const char* _str) = 0;
  234. virtual void write(const void* _data, size_t _size) = 0;
  235. template<typename Ty>
  236. void write(Ty _value)
  237. {
  238. write(&_value, sizeof(Ty) );
  239. }
  240. void writeString(const char* _str)
  241. {
  242. uint16_t len = (uint16_t)strlen(_str);
  243. write(len);
  244. write(_str);
  245. char term = '\0';
  246. write(term);
  247. }
  248. };
  249. IStreamWriter::~IStreamWriter()
  250. {
  251. }
  252. class FileWriter : public IStreamWriter
  253. {
  254. public:
  255. FileWriter(const char* _filePath, bool _bigEndian = false)
  256. : m_filePath(_filePath)
  257. , m_file(NULL)
  258. , m_bigEndian(_bigEndian)
  259. {
  260. }
  261. ~FileWriter()
  262. {
  263. }
  264. bool open()
  265. {
  266. BX_CHECK(NULL == m_file, "Still open!");
  267. m_file = fopen(m_filePath.c_str(), "wb");
  268. return NULL != m_file;
  269. }
  270. void close()
  271. {
  272. if (NULL != m_file)
  273. {
  274. fclose(m_file);
  275. m_file = NULL;
  276. }
  277. }
  278. void writef(const char* _format, ...)
  279. {
  280. if (NULL != m_file)
  281. {
  282. va_list argList;
  283. va_start(argList, _format);
  284. char temp[2048];
  285. int len = vsnprintf(temp, sizeof(temp), _format, argList);
  286. fwrite(temp, len, 1, m_file);
  287. va_end(argList);
  288. }
  289. }
  290. void write(const char* _str)
  291. {
  292. if (NULL != m_file)
  293. {
  294. fwrite(_str, strlen(_str), 1, m_file);
  295. }
  296. }
  297. void write(const void* _data, size_t _size)
  298. {
  299. if (NULL != m_file)
  300. {
  301. fwrite(_data, _size, 1, m_file);
  302. }
  303. }
  304. private:
  305. std::string m_filePath;
  306. FILE* m_file;
  307. bool m_bigEndian;
  308. };
  309. class Bin2cStream : public IStreamWriter
  310. {
  311. public:
  312. Bin2cStream(const char* _filePath, const char* _name)
  313. : m_filePath(_filePath)
  314. , m_name(_name)
  315. , m_file(NULL)
  316. {
  317. }
  318. ~Bin2cStream()
  319. {
  320. }
  321. bool open()
  322. {
  323. BX_CHECK(NULL == m_file, "Still open!");
  324. m_file = fopen(m_filePath.c_str(), "wb");
  325. return NULL != m_file;
  326. }
  327. void close()
  328. {
  329. if (NULL != m_file)
  330. {
  331. #define HEX_DUMP_WIDTH 16
  332. #define HEX_DUMP_SPACE_WIDTH 96
  333. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  334. const uint8_t* data = &m_buffer[0];
  335. uint32_t size = m_buffer.size();
  336. fprintf(m_file, "static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size);
  337. if (NULL != data)
  338. {
  339. char hex[HEX_DUMP_SPACE_WIDTH+1];
  340. char ascii[HEX_DUMP_WIDTH+1];
  341. uint32_t hexPos = 0;
  342. uint32_t asciiPos = 0;
  343. for (uint32_t ii = 0; ii < size; ++ii)
  344. {
  345. _snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  346. hexPos += 6;
  347. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
  348. asciiPos++;
  349. if (HEX_DUMP_WIDTH == asciiPos)
  350. {
  351. ascii[asciiPos] = '\0';
  352. fprintf(m_file, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  353. data += asciiPos;
  354. hexPos = 0;
  355. asciiPos = 0;
  356. }
  357. }
  358. if (0 != asciiPos)
  359. {
  360. ascii[asciiPos] = '\0';
  361. fprintf(m_file, "\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  362. }
  363. }
  364. fprintf(m_file, "};\n");
  365. #undef HEX_DUMP_WIDTH
  366. #undef HEX_DUMP_SPACE_WIDTH
  367. #undef HEX_DUMP_FORMAT
  368. fclose(m_file);
  369. m_file = NULL;
  370. }
  371. }
  372. void writef(const char* _format, ...)
  373. {
  374. va_list argList;
  375. va_start(argList, _format);
  376. char temp[2048];
  377. int len = vsnprintf(temp, sizeof(temp), _format, argList);
  378. m_buffer.insert(m_buffer.end(), temp, temp+len);
  379. va_end(argList);
  380. }
  381. void write(const char* _str)
  382. {
  383. m_buffer.insert(m_buffer.end(), _str, _str+strlen(_str) );
  384. }
  385. void write(const void* _data, size_t _size)
  386. {
  387. const char* data = (const char*)_data;
  388. m_buffer.insert(m_buffer.end(), data, data+_size);
  389. }
  390. private:
  391. std::string m_filePath;
  392. std::string m_name;
  393. typedef std::vector<uint8_t> Buffer;
  394. Buffer m_buffer;
  395. FILE* m_file;
  396. };
  397. struct Varying
  398. {
  399. std::string m_name;
  400. std::string m_type;
  401. std::string m_init;
  402. std::string m_semantics;
  403. };
  404. typedef std::unordered_map<std::string, Varying> VaryingMap;
  405. class File
  406. {
  407. public:
  408. File(const char* _filePath)
  409. : m_data(NULL)
  410. {
  411. FILE* file = fopen(_filePath, "r");
  412. if (NULL != file)
  413. {
  414. m_size = fsize(file);
  415. m_data = new char[m_size+1];
  416. m_size = fread(m_data, 1, m_size, file);
  417. m_data[m_size] = '\0';
  418. fclose(file);
  419. }
  420. }
  421. ~File()
  422. {
  423. delete [] m_data;
  424. }
  425. const char* getData() const
  426. {
  427. return m_data;
  428. }
  429. long int getSize() const
  430. {
  431. return m_size;
  432. }
  433. private:
  434. char* m_data;
  435. long int m_size;
  436. };
  437. const char* strnl(const char* _str)
  438. {
  439. const char* eol = strstr(_str, "\n\r");
  440. if (NULL != eol)
  441. {
  442. return eol + 2;
  443. }
  444. eol = strstr(_str, "\n");
  445. if (NULL != eol)
  446. {
  447. return eol + 1;
  448. }
  449. return eol + strlen(_str);
  450. }
  451. const char* streol(const char* _str)
  452. {
  453. const char* eol = strstr(_str, "\n\r");
  454. if (NULL != eol)
  455. {
  456. return eol;
  457. }
  458. eol = strstr(_str, "\n");
  459. if (NULL != eol)
  460. {
  461. return eol;
  462. }
  463. return eol + strlen(_str);
  464. }
  465. const char* strws(const char* _str)
  466. {
  467. for (; isspace(*_str); ++_str);
  468. return _str;
  469. }
  470. const char* strnws(const char* _str)
  471. {
  472. for (; !isspace(*_str); ++_str);
  473. return _str;
  474. }
  475. const char* strword(const char* _str)
  476. {
  477. for (char ch = *_str++; isalnum(ch) || '_' == ch; ch = *_str++);
  478. return _str-1;
  479. }
  480. const char* strmb(const char* _str, char _open, char _close)
  481. {
  482. int count = 0;
  483. for (char ch = *_str++; ch != '\0' && count >= 0; ch = *_str++)
  484. {
  485. if (ch == _open)
  486. {
  487. count++;
  488. }
  489. else if (ch == _close)
  490. {
  491. count--;
  492. if (0 == count)
  493. {
  494. return _str-1;
  495. }
  496. }
  497. }
  498. return NULL;
  499. }
  500. void strins(char* _str, const char* _insert)
  501. {
  502. size_t len = strlen(_insert);
  503. memmove(&_str[len], _str, strlen(_str) );
  504. memcpy(_str, _insert, len);
  505. }
  506. class LineReader
  507. {
  508. public:
  509. LineReader(const char* _str)
  510. : m_str(_str)
  511. , m_pos(0)
  512. , m_size( (uint32_t)strlen(_str) )
  513. {
  514. }
  515. std::string getLine()
  516. {
  517. const char* str = &m_str[m_pos];
  518. skipLine();
  519. const char* eol = &m_str[m_pos];
  520. std::string tmp;
  521. tmp.assign(str, eol-str);
  522. return tmp;
  523. }
  524. bool isEof() const
  525. {
  526. return m_str[m_pos] == '\0';
  527. }
  528. private:
  529. void skipLine()
  530. {
  531. const char* str = &m_str[m_pos];
  532. const char* nl = strnl(str);
  533. m_pos += (uint32_t)(nl - str);
  534. }
  535. const char* m_str;
  536. uint32_t m_pos;
  537. uint32_t m_size;
  538. };
  539. void printCode(const char* _code)
  540. {
  541. fprintf(stderr, "Code:\n---\n");
  542. LineReader lr(_code);
  543. for (uint32_t line = 1; !lr.isEof(); ++line)
  544. {
  545. fprintf(stderr, "%3d: %s", line, lr.getLine().c_str() );
  546. }
  547. fprintf(stderr, "---\n");
  548. }
  549. bool compileGLSLShader(CommandLine& _cmdLine, const std::string& _code, IStreamWriter& _stream)
  550. {
  551. const glslopt_shader_type type = tolower(_cmdLine.findOption('\0', "type")[0]) == 'f' ? kGlslOptShaderFragment : kGlslOptShaderVertex;
  552. glslopt_ctx* ctx = glslopt_initialize(false);
  553. glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
  554. if( !glslopt_get_status(shader) )
  555. {
  556. printCode(_code.c_str() );
  557. fprintf(stderr, "Error: %s\n", glslopt_get_log(shader) );
  558. glslopt_cleanup(ctx);
  559. return false;
  560. }
  561. const char* optimizedShader = glslopt_get_output(shader);
  562. const char* profile = _cmdLine.findOption('p');
  563. if (NULL == profile)
  564. {
  565. _stream.write("#ifdef GL_ES\n");
  566. _stream.write("precision highp float;\n");
  567. _stream.write("#endif // GL_ES\n\n");
  568. }
  569. else
  570. {
  571. _stream.writef("#version %s\n\n", profile);
  572. }
  573. _stream.write(optimizedShader, strlen(optimizedShader) );
  574. uint8_t nul = 0;
  575. _stream.write(nul);
  576. glslopt_cleanup(ctx);
  577. return true;
  578. }
  579. bool compileHLSLShaderDx9(CommandLine& _cmdLine, const std::string& _code, IStreamWriter& _stream)
  580. {
  581. #if BX_PLATFORM_WINDOWS
  582. const char* profile = _cmdLine.findOption('p');
  583. if (NULL == profile)
  584. {
  585. printf("Shader profile must be specified.\n");
  586. return false;
  587. }
  588. bool bigEndian = _cmdLine.hasArg('\0', "xbox360");
  589. uint32_t flags = 0;
  590. flags |= _cmdLine.hasArg('\0', "debug") ? D3DXSHADER_DEBUG : 0;
  591. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
  592. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
  593. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
  594. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
  595. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  596. bool werror = _cmdLine.hasArg('\0', "Werror");
  597. uint32_t optimization = 3;
  598. if (_cmdLine.hasArg(optimization, 'O') )
  599. {
  600. optimization = bx::uint32_min(optimization, countof(s_optimizationLevelDx9)-1);
  601. flags |= s_optimizationLevelDx9[optimization];
  602. }
  603. else
  604. {
  605. flags |= D3DXSHADER_SKIPOPTIMIZATION;
  606. }
  607. BX_TRACE("Profile: %s", profile);
  608. BX_TRACE("Flags: 0x%08x", flags);
  609. BX_TRACE("Big Endian: %s", bigEndian?"true":"false");
  610. LPD3DXBUFFER code;
  611. LPD3DXBUFFER errorMsg;
  612. LPD3DXCONSTANTTABLE constantTable;
  613. HRESULT hr = D3DXCompileShader(_code.c_str()
  614. , _code.size()
  615. , NULL
  616. , NULL
  617. , "main"
  618. , profile
  619. , flags
  620. , &code
  621. , &errorMsg
  622. , &constantTable
  623. );
  624. if (FAILED(hr)
  625. || werror && NULL != errorMsg)
  626. {
  627. printCode(_code.c_str() );
  628. fprintf(stderr, "Error: 0x%08x %s\n", hr, errorMsg->GetBufferPointer() );
  629. return false;
  630. }
  631. D3DXCONSTANTTABLE_DESC desc;
  632. hr = constantTable->GetDesc(&desc);
  633. if (FAILED(hr) )
  634. {
  635. fprintf(stderr, "Error 0x%08x\n", hr);
  636. return false;
  637. }
  638. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  639. BX_TRACE("Num constants: %d", desc.Constants);
  640. BX_TRACE("# cl ty RxC S By Name");
  641. UniformArray uniforms;
  642. for (uint32_t ii = 0; ii < desc.Constants; ++ii)
  643. {
  644. D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
  645. D3DXCONSTANT_DESC constDesc;
  646. uint32_t count;
  647. constantTable->GetConstantDesc(handle, &constDesc, &count);
  648. BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
  649. , ii
  650. , constDesc.Class
  651. , constDesc.Type
  652. , constDesc.Rows
  653. , constDesc.Columns
  654. , constDesc.StructMembers
  655. , constDesc.Bytes
  656. , constDesc.Name
  657. , constDesc.Elements
  658. , constDesc.RegisterIndex
  659. , constDesc.RegisterCount
  660. );
  661. ConstantType::Enum type = findConstantTypeDx9(constDesc);
  662. if (ConstantType::Count != type)
  663. {
  664. Uniform un;
  665. un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
  666. un.type = type;
  667. un.num = constDesc.Elements;
  668. un.regIndex = constDesc.RegisterIndex;
  669. un.regCount = constDesc.RegisterCount;
  670. uniforms.push_back(un);
  671. }
  672. }
  673. uint16_t count = (uint16_t)uniforms.size();
  674. _stream.write(count);
  675. uint32_t fragmentBit = profile[0] == 'p' ? ConstantType::FragmentBit : 0;
  676. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  677. {
  678. const Uniform& un = *it;
  679. uint8_t nameSize = (uint8_t)un.name.size();
  680. _stream.write(nameSize);
  681. _stream.write(un.name.c_str(), nameSize);
  682. _stream.write<uint8_t>(un.type|fragmentBit);
  683. _stream.write(un.num);
  684. _stream.write(un.regIndex);
  685. _stream.write(un.regCount);
  686. BX_TRACE("%s, %s, %d, %d, %d"
  687. , un.name.c_str()
  688. , s_constantTypeName[un.type]
  689. , un.num
  690. , un.regIndex
  691. , un.regCount
  692. );
  693. }
  694. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  695. _stream.write(shaderSize);
  696. _stream.write(code->GetBufferPointer(), shaderSize);
  697. uint8_t nul = 0;
  698. _stream.write(nul);
  699. if (NULL != code)
  700. {
  701. code->Release();
  702. }
  703. if (NULL != errorMsg)
  704. {
  705. errorMsg->Release();
  706. }
  707. if (NULL != constantTable)
  708. {
  709. constantTable->Release();
  710. }
  711. return true;
  712. #else
  713. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  714. return false;
  715. #endif // BX_PLATFORM_WINDOWS
  716. }
  717. bool compileHLSLShaderDx11(CommandLine& _cmdLine, const std::string& _code, IStreamWriter& _stream)
  718. {
  719. #if BX_PLATFORM_WINDOWS
  720. const char* profile = _cmdLine.findOption('p');
  721. if (NULL == profile)
  722. {
  723. printf("Shader profile must be specified.\n");
  724. return false;
  725. }
  726. bool bigEndian = _cmdLine.hasArg('\0', "xbox360");
  727. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  728. flags |= _cmdLine.hasArg('\0', "debug") ? D3DCOMPILE_DEBUG : 0;
  729. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  730. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
  731. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  732. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  733. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  734. bool werror = _cmdLine.hasArg('\0', "Werror");
  735. if (werror)
  736. {
  737. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  738. }
  739. uint32_t optimization = 3;
  740. if (_cmdLine.hasArg(optimization, 'O') )
  741. {
  742. optimization = bx::uint32_min(optimization, countof(s_optimizationLevelDx11)-1);
  743. flags |= s_optimizationLevelDx11[optimization];
  744. }
  745. else
  746. {
  747. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  748. }
  749. BX_TRACE("Profile: %s", profile);
  750. BX_TRACE("Flags: 0x%08x", flags);
  751. BX_TRACE("Big Endian: %s", bigEndian?"true":"false");
  752. ID3DBlob* code;
  753. ID3DBlob* errorMsg;
  754. HRESULT hr = D3DCompile(_code.c_str()
  755. , _code.size()
  756. , NULL
  757. , NULL
  758. , NULL
  759. , "main"
  760. , profile
  761. , flags
  762. , 0
  763. , &code
  764. , &errorMsg
  765. );
  766. if (FAILED(hr)
  767. || werror && NULL != errorMsg)
  768. {
  769. printCode(_code.c_str() );
  770. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x %s\n", hr, errorMsg->GetBufferPointer() );
  771. return false;
  772. }
  773. UniformArray uniforms;
  774. ID3D11ShaderReflection* reflect = NULL;
  775. hr = D3DReflect(code->GetBufferPointer()
  776. , code->GetBufferSize()
  777. , IID_ID3D11ShaderReflection
  778. , (void**)&reflect
  779. );
  780. if (FAILED(hr) )
  781. {
  782. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", hr);
  783. return false;
  784. }
  785. D3D11_SHADER_DESC desc;
  786. hr = reflect->GetDesc(&desc);
  787. if (FAILED(hr) )
  788. {
  789. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", hr);
  790. return false;
  791. }
  792. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  793. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  794. BX_TRACE("Input:");
  795. uint8_t attrMask[Attrib::Count];
  796. memset(attrMask, 0, sizeof(attrMask) );
  797. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  798. {
  799. D3D11_SIGNATURE_PARAMETER_DESC spd;
  800. reflect->GetInputParameterDesc(ii, &spd);
  801. BX_TRACE("\t%2d: %s%d, %d, %d, %x, %d"
  802. , ii
  803. , spd.SemanticName
  804. , spd.SemanticIndex
  805. , spd.SystemValueType
  806. , spd.ComponentType
  807. , spd.Mask
  808. , spd.Register
  809. );
  810. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
  811. if (ris.m_attr != Attrib::Count)
  812. {
  813. attrMask[ris.m_attr] = 0xff;
  814. }
  815. }
  816. _stream.write(attrMask, sizeof(attrMask) );
  817. BX_TRACE("Output:");
  818. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  819. {
  820. D3D11_SIGNATURE_PARAMETER_DESC spd;
  821. reflect->GetOutputParameterDesc(ii, &spd);
  822. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  823. }
  824. uint16_t size = 0;
  825. for (uint32_t ii = 0; ii < bx::uint32_min(1, desc.ConstantBuffers); ++ii)
  826. {
  827. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  828. D3D11_SHADER_BUFFER_DESC bufferDesc;
  829. hr = cbuffer->GetDesc(&bufferDesc);
  830. size = (uint16_t)bufferDesc.Size;
  831. if (SUCCEEDED(hr) )
  832. {
  833. BX_TRACE("%s, %d, vars %d, size %d"
  834. , bufferDesc.Name
  835. , bufferDesc.Type
  836. , bufferDesc.Variables
  837. , bufferDesc.Size
  838. );
  839. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  840. {
  841. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  842. ID3D11ShaderReflectionType* type = var->GetType();
  843. D3D11_SHADER_VARIABLE_DESC varDesc;
  844. hr = var->GetDesc(&varDesc);
  845. if (SUCCEEDED(hr) )
  846. {
  847. D3D11_SHADER_TYPE_DESC constDesc;
  848. hr = type->GetDesc(&constDesc);
  849. if (SUCCEEDED(hr) )
  850. {
  851. ConstantType::Enum type = findConstantTypeDx11(constDesc, varDesc.Size);
  852. if (ConstantType::Count != type
  853. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  854. {
  855. Uniform un;
  856. un.name = varDesc.Name;
  857. un.type = type;
  858. un.num = constDesc.Elements;
  859. un.regIndex = varDesc.StartOffset;
  860. un.regCount = varDesc.Size;
  861. uniforms.push_back(un);
  862. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d"
  863. , varDesc.Name
  864. , varDesc.StartOffset
  865. , varDesc.Size
  866. , varDesc.uFlags
  867. , type
  868. );
  869. }
  870. }
  871. }
  872. }
  873. }
  874. }
  875. BX_TRACE("Bound:");
  876. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  877. {
  878. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  879. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  880. if (SUCCEEDED(hr) )
  881. {
  882. // if (bindDesc.Type == D3D_SIT_SAMPLER)
  883. {
  884. BX_TRACE("\t%s, %d, %d, %d"
  885. , bindDesc.Name
  886. , bindDesc.Type
  887. , bindDesc.BindPoint
  888. , bindDesc.BindCount
  889. );
  890. }
  891. }
  892. }
  893. uint16_t count = (uint16_t)uniforms.size();
  894. _stream.write(count);
  895. _stream.write(size);
  896. uint32_t fragmentBit = profile[0] == 'p' ? ConstantType::FragmentBit : 0;
  897. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  898. {
  899. const Uniform& un = *it;
  900. uint8_t nameSize = (uint8_t)un.name.size();
  901. _stream.write(nameSize);
  902. _stream.write(un.name.c_str(), nameSize);
  903. _stream.write<uint8_t>(un.type|fragmentBit);
  904. _stream.write(un.num);
  905. _stream.write(un.regIndex);
  906. _stream.write(un.regCount);
  907. BX_TRACE("%s, %s, %d, %d, %d"
  908. , un.name.c_str()
  909. , s_constantTypeName[un.type]
  910. , un.num
  911. , un.regIndex
  912. , un.regCount
  913. );
  914. }
  915. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  916. _stream.write(shaderSize);
  917. _stream.write(code->GetBufferPointer(), shaderSize);
  918. uint8_t nul = 0;
  919. _stream.write(nul);
  920. if (NULL != reflect)
  921. {
  922. reflect->Release();
  923. }
  924. if (NULL != code)
  925. {
  926. code->Release();
  927. }
  928. if (NULL != errorMsg)
  929. {
  930. errorMsg->Release();
  931. }
  932. return true;
  933. #else
  934. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  935. return false;
  936. #endif // BX_PLATFORM_WINDOWS
  937. }
  938. struct Preprocessor
  939. {
  940. Preprocessor(const char* _filePath)
  941. : m_tagptr(m_tags)
  942. , m_scratchPos(0)
  943. , m_fgetsPos(0)
  944. {
  945. m_tagptr->tag = FPPTAG_USERDATA;
  946. m_tagptr->data = this;
  947. m_tagptr++;
  948. m_tagptr->tag = FPPTAG_DEPENDS;
  949. m_tagptr->data = (void*)fppDepends;
  950. m_tagptr++;
  951. m_tagptr->tag = FPPTAG_INPUT;
  952. m_tagptr->data = (void*)fppInput;
  953. m_tagptr++;
  954. m_tagptr->tag = FPPTAG_OUTPUT;
  955. m_tagptr->data = (void*)fppOutput;
  956. m_tagptr++;
  957. m_tagptr->tag = FPPTAG_ERROR;
  958. m_tagptr->data = (void*)fppError;
  959. m_tagptr++;
  960. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  961. m_tagptr->data = (void*)0;
  962. m_tagptr++;
  963. m_tagptr->tag = FPPTAG_LINE;
  964. m_tagptr->data = (void*)0;
  965. m_tagptr++;
  966. m_tagptr->tag = FPPTAG_INPUT_NAME;
  967. m_tagptr->data = scratch(_filePath);
  968. m_tagptr++;
  969. m_default = "#define lowp\n#define mediump\n#define highp\n";
  970. }
  971. void setDefine(const char* _define)
  972. {
  973. m_tagptr->tag = FPPTAG_DEFINE;
  974. m_tagptr->data = scratch(_define);
  975. m_tagptr++;
  976. }
  977. void setDefaultDefine(const char* _name)
  978. {
  979. char temp[1024];
  980. _snprintf(temp, countof(temp)
  981. , "#ifndef %s\n"
  982. "# define %s 0\n"
  983. "#endif // %s\n"
  984. "\n"
  985. , _name
  986. , _name
  987. , _name
  988. );
  989. m_default += temp;
  990. }
  991. void writef(const char* _format, ...)
  992. {
  993. va_list argList;
  994. va_start(argList, _format);
  995. char temp[2048];
  996. int len = vsnprintf(temp, sizeof(temp), _format, argList);
  997. m_default += temp;
  998. va_end(argList);
  999. }
  1000. void addDependency(const char* _fileName)
  1001. {
  1002. m_depends += " \\\n ";
  1003. m_depends += _fileName;
  1004. }
  1005. bool run(const char* _input)
  1006. {
  1007. m_fgetsPos = 0;
  1008. m_input = m_default;
  1009. m_input += _input;
  1010. fppTag* tagptr = m_tagptr;
  1011. tagptr->tag = FPPTAG_END;
  1012. tagptr->data = 0;
  1013. tagptr++;
  1014. int result = fppPreProcess(m_tags);
  1015. return 0 == result;
  1016. }
  1017. char* fgets(char* _buffer, int _size)
  1018. {
  1019. int ii = 0;
  1020. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  1021. {
  1022. _buffer[ii++] = ch;
  1023. if (ch == '\n' || ii == _size)
  1024. {
  1025. _buffer[ii] = '\0';
  1026. m_fgetsPos++;
  1027. return _buffer;
  1028. }
  1029. }
  1030. return NULL;
  1031. }
  1032. static void fppDepends(char* _fileName, void* _userData)
  1033. {
  1034. Preprocessor* thisClass = (Preprocessor*)_userData;
  1035. thisClass->addDependency(_fileName);
  1036. }
  1037. static char* fppInput(char* _buffer, int _size, void* _userData)
  1038. {
  1039. Preprocessor* thisClass = (Preprocessor*)_userData;
  1040. return thisClass->fgets(_buffer, _size);
  1041. }
  1042. static void fppOutput(int _ch, void* _userData)
  1043. {
  1044. Preprocessor* thisClass = (Preprocessor*)_userData;
  1045. thisClass->m_preprocessed += _ch;
  1046. }
  1047. static void fppError(void* _userData, char* _format, va_list _vargs)
  1048. {
  1049. vfprintf(stderr, _format, _vargs);
  1050. }
  1051. char* scratch(const char* _str)
  1052. {
  1053. char* result = &m_scratch[m_scratchPos];
  1054. strcpy(result, _str);
  1055. m_scratchPos += strlen(_str)+1;
  1056. return result;
  1057. }
  1058. fppTag m_tags[MAX_TAGS];
  1059. fppTag* m_tagptr;
  1060. std::string m_depends;
  1061. std::string m_default;
  1062. std::string m_input;
  1063. std::string m_preprocessed;
  1064. char m_scratch[16<<10];
  1065. uint32_t m_scratchPos;
  1066. uint32_t m_fgetsPos;
  1067. };
  1068. const char* baseName(const char* _filePath)
  1069. {
  1070. const char* bs = strrchr(_filePath, '\\');
  1071. const char* fs = strrchr(_filePath, '/');
  1072. const char* column = strrchr(_filePath, ':');
  1073. const char* basename = std::max(std::max(bs, fs), column);
  1074. if (NULL != basename)
  1075. {
  1076. return basename+1;
  1077. }
  1078. return _filePath;
  1079. }
  1080. // OpenGL #version Features Direct3D Features Shader Model
  1081. // 2.1 120 vf 9.0 vf 2.0
  1082. // 3.0 130
  1083. // 3.1 140
  1084. // 3.2 150 vgf
  1085. // 3.3 330 10.0 vgf 4.0
  1086. // 4.0 400 vhdgf
  1087. // 4.1 410
  1088. // 4.2 420 11.0 vhdgf 5.0
  1089. int main(int _argc, const char* _argv[])
  1090. {
  1091. CommandLine cmdLine(_argc, _argv);
  1092. const char* filePath = cmdLine.findOption('f');
  1093. if (NULL == filePath)
  1094. {
  1095. fprintf(stderr, "Shader file name must be specified.\n");
  1096. return EXIT_FAILURE;
  1097. }
  1098. const char* outFilePath = cmdLine.findOption('o');
  1099. if (NULL == outFilePath)
  1100. {
  1101. fprintf(stderr, "Output file name must be specified.\n");
  1102. return EXIT_FAILURE;
  1103. }
  1104. const char* type = cmdLine.findOption('\0', "type");
  1105. if (NULL == type)
  1106. {
  1107. fprintf(stderr, "Must specify shader type.");
  1108. return EXIT_FAILURE;
  1109. }
  1110. const char* platform = cmdLine.findOption('\0', "platform");
  1111. if (NULL == platform)
  1112. {
  1113. fprintf(stderr, "Must specify platform.\n");
  1114. return EXIT_FAILURE;
  1115. }
  1116. uint32_t hlsl = 2;
  1117. const char* profile = cmdLine.findOption('p');
  1118. if (NULL != profile)
  1119. {
  1120. if (0 == strncmp(&profile[1], "s_3", 3) )
  1121. {
  1122. hlsl = 3;
  1123. }
  1124. else if (0 == strncmp(&profile[1], "s_4", 3) )
  1125. {
  1126. hlsl = 4;
  1127. }
  1128. else if (0 == strncmp(&profile[1], "s_5", 3) )
  1129. {
  1130. hlsl = 5;
  1131. }
  1132. }
  1133. const char* bin2c = NULL;
  1134. if (cmdLine.hasArg("bin2c") )
  1135. {
  1136. bin2c = cmdLine.findOption("bin2c");
  1137. if (NULL == bin2c)
  1138. {
  1139. bin2c = baseName(outFilePath);
  1140. uint32_t len = strlen(bin2c);
  1141. char* temp = (char*)alloca(len+1);
  1142. for (char *out = temp; *bin2c != '\0';)
  1143. {
  1144. char ch = *bin2c++;
  1145. if (isalnum(ch) )
  1146. {
  1147. *out++ = ch;
  1148. }
  1149. else
  1150. {
  1151. *out++ = '_';
  1152. }
  1153. }
  1154. temp[len] = '\0';
  1155. bin2c = temp;
  1156. }
  1157. }
  1158. bool depends = cmdLine.hasArg("depends");
  1159. bool preprocessOnly = cmdLine.hasArg("preprocess");
  1160. Preprocessor preprocessor(filePath);
  1161. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  1162. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  1163. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  1164. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  1165. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  1166. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  1167. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  1168. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  1169. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  1170. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  1171. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  1172. bool glsl = false;
  1173. if (0 == _stricmp(platform, "android") )
  1174. {
  1175. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  1176. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1177. glsl = true;
  1178. }
  1179. else if (0 == _stricmp(platform, "ios") )
  1180. {
  1181. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1182. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1183. glsl = true;
  1184. }
  1185. else if (0 == _stricmp(platform, "linux") )
  1186. {
  1187. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1188. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1189. glsl = true;
  1190. }
  1191. else if (0 == _stricmp(platform, "nacl") )
  1192. {
  1193. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  1194. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1195. glsl = true;
  1196. }
  1197. else if (0 == _stricmp(platform, "osx") )
  1198. {
  1199. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  1200. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1201. glsl = true;
  1202. }
  1203. else if (0 == _stricmp(platform, "windows") )
  1204. {
  1205. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  1206. char temp[256];
  1207. _snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  1208. preprocessor.setDefine(temp);
  1209. }
  1210. else if (0 == _stricmp(platform, "xbox360") )
  1211. {
  1212. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  1213. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=3");
  1214. }
  1215. else
  1216. {
  1217. fprintf(stderr, "Unknown platform %s?!", platform);
  1218. return EXIT_FAILURE;
  1219. }
  1220. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  1221. bool fragment = false;
  1222. switch (tolower(type[0]) )
  1223. {
  1224. case 'f':
  1225. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1226. fragment = true;
  1227. break;
  1228. case 'v':
  1229. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1230. break;
  1231. default:
  1232. fprintf(stderr, "Unknown type: %s?!", type);
  1233. return EXIT_FAILURE;
  1234. }
  1235. FILE* file = fopen(filePath, "r");
  1236. if (NULL != file)
  1237. {
  1238. VaryingMap varyingMap;
  1239. File attribdef("varying.def.sc");
  1240. const char* parse = attribdef.getData();
  1241. while (NULL != parse
  1242. && *parse != '\0')
  1243. {
  1244. parse = strws(parse);
  1245. const char* eol = strchr(parse, ';');
  1246. if (NULL != eol)
  1247. {
  1248. const char* type = parse;
  1249. const char* name = parse = strws(strword(parse) );
  1250. const char* column = parse = strws(strword(parse) );
  1251. const char* semantics = parse = strws(strnws(parse) );
  1252. const char* assign = parse = strws(strword(parse) );
  1253. const char* init = parse = strws(strnws(parse) );
  1254. if (type < eol
  1255. && name < eol
  1256. && column < eol
  1257. && ':' == *column
  1258. && semantics < eol)
  1259. {
  1260. Varying var;
  1261. var.m_type.assign(type, strword(type)-type);
  1262. var.m_name.assign(name, strword(name)-name);
  1263. var.m_semantics.assign(semantics, strword(semantics)-semantics);
  1264. if (assign < eol
  1265. && '=' == *assign
  1266. && init < eol)
  1267. {
  1268. var.m_init.assign(init, eol-init);
  1269. }
  1270. varyingMap.insert(std::make_pair(var.m_name, var) );
  1271. }
  1272. parse = eol + 1;
  1273. }
  1274. }
  1275. const size_t padding = 16;
  1276. long int size = fsize(file);
  1277. char* data = new char[size+padding];
  1278. size = fread(data, 1, size, file);
  1279. memset(&data[size], 0, padding);
  1280. fclose(file);
  1281. typedef std::vector<std::string> InOut;
  1282. InOut shaderInputs;
  1283. InOut shaderOutputs;
  1284. const char* input = data;
  1285. while (input[0] == '$')
  1286. {
  1287. const char* str = input+1;
  1288. const char* eol = streol(str);
  1289. const char* nl = strnl(eol);
  1290. input = nl;
  1291. if (0 == strncmp(str, "input", 5) )
  1292. {
  1293. str += 5;
  1294. str = strws(str);
  1295. if (str < eol)
  1296. {
  1297. const char* delim;
  1298. do
  1299. {
  1300. delim = strpbrk(str, " ,");
  1301. if (NULL != delim)
  1302. {
  1303. delim = delim > eol ? eol : delim;
  1304. std::string token;
  1305. token.assign(str, delim-str);
  1306. shaderInputs.push_back(token);
  1307. str = strws(delim + 1);
  1308. }
  1309. }
  1310. while (delim < eol && NULL != delim);
  1311. }
  1312. }
  1313. else if (0 == strncmp(str, "output", 6) )
  1314. {
  1315. str += 6;
  1316. str = strws(str);
  1317. if (str < eol)
  1318. {
  1319. const char* delim;
  1320. do
  1321. {
  1322. delim = strpbrk(str, " ,");
  1323. if (NULL != delim)
  1324. {
  1325. delim = delim > eol ? eol : delim;
  1326. std::string token;
  1327. token.assign(str, delim-str);
  1328. shaderOutputs.push_back(token);
  1329. str = strws(delim + 1);
  1330. }
  1331. }
  1332. while (delim < eol && NULL != delim);
  1333. }
  1334. }
  1335. }
  1336. if (glsl)
  1337. {
  1338. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1339. {
  1340. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1341. if (varyingIt != varyingMap.end() )
  1342. {
  1343. const Varying& var = varyingIt->second;
  1344. const char* name = var.m_name.c_str();
  1345. if (0 == strncmp(name, "a_", 2) )
  1346. {
  1347. preprocessor.writef("attribute %s %s;\n", var.m_type.c_str(), name);
  1348. }
  1349. else
  1350. {
  1351. preprocessor.writef("varying %s %s;\n", var.m_type.c_str(), name);
  1352. }
  1353. }
  1354. }
  1355. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1356. {
  1357. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1358. if (varyingIt != varyingMap.end() )
  1359. {
  1360. const Varying& var = varyingIt->second;
  1361. preprocessor.writef("varying %s %s;\n", var.m_type.c_str(), var.m_name.c_str() );
  1362. }
  1363. }
  1364. }
  1365. else
  1366. {
  1367. preprocessor.writef(
  1368. "#define lowp\n"
  1369. "#define mediump\n"
  1370. "#define highp\n"
  1371. "#define vec2 float2\n"
  1372. "#define vec3 float3\n"
  1373. "#define vec4 float4\n"
  1374. "#define mat2 float2x2\n"
  1375. "#define mat3 float3x3\n"
  1376. "#define mat4 float4x4\n"
  1377. );
  1378. char* entry = strstr(data, "void main()");
  1379. if (NULL != entry)
  1380. {
  1381. entry[4] = '_';
  1382. const char* brace = strstr(entry, "{");
  1383. if (NULL != brace)
  1384. {
  1385. const char* end = strmb(brace, '{', '}');
  1386. if (NULL != end)
  1387. {
  1388. strins(const_cast<char*>(end), "__RETURN__;\n");
  1389. }
  1390. }
  1391. }
  1392. if (fragment)
  1393. {
  1394. preprocessor.writef("#define void_main() \\\n");
  1395. preprocessor.writef("\tvec4 main(vec4 gl_FragCoord : SV_POSITION \\\n");
  1396. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1397. {
  1398. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1399. if (varyingIt != varyingMap.end() )
  1400. {
  1401. const Varying& var = varyingIt->second;
  1402. preprocessor.writef("\t, %s %s : %s \\\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1403. }
  1404. }
  1405. preprocessor.writef(
  1406. ") : SV_TARGET \\\n"
  1407. "{ \\\n"
  1408. "\tvec4 gl_FragColor;\n"
  1409. "#define __RETURN__ \\\n"
  1410. "\t} \\\n"
  1411. "\treturn gl_FragColor"
  1412. );
  1413. }
  1414. else
  1415. {
  1416. preprocessor.writef(
  1417. "struct Output\n"
  1418. "{\n"
  1419. "\tvec4 gl_Position : SV_POSITION;\n"
  1420. "#define gl_Position _varying_.gl_Position\n"
  1421. );
  1422. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1423. {
  1424. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1425. if (varyingIt != varyingMap.end() )
  1426. {
  1427. const Varying& var = varyingIt->second;
  1428. preprocessor.writef("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1429. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  1430. }
  1431. }
  1432. preprocessor.writef(
  1433. "};\n"
  1434. );
  1435. preprocessor.writef("#define void_main() \\\n");
  1436. preprocessor.writef("Output main(");
  1437. bool first = true;
  1438. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1439. {
  1440. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1441. if (varyingIt != varyingMap.end() )
  1442. {
  1443. const Varying& var = varyingIt->second;
  1444. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1445. first = false;
  1446. }
  1447. }
  1448. preprocessor.writef(
  1449. ") \\\n"
  1450. "{ \\\n"
  1451. "\tOutput _varying_;"
  1452. );
  1453. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1454. {
  1455. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1456. if (varyingIt != varyingMap.end() )
  1457. {
  1458. const Varying& var = varyingIt->second;
  1459. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  1460. }
  1461. }
  1462. preprocessor.writef(
  1463. "\n#define __RETURN__ \\\n"
  1464. "\t} \\\n"
  1465. "\treturn _varying_"
  1466. );
  1467. }
  1468. }
  1469. if (preprocessor.run(input) )
  1470. {
  1471. BX_TRACE("Input file: %s", filePath);
  1472. BX_TRACE("Output file: %s", outFilePath);
  1473. if (preprocessOnly)
  1474. {
  1475. FileWriter stream(outFilePath);
  1476. if (!stream.open() )
  1477. {
  1478. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1479. return false;
  1480. }
  1481. if (glsl)
  1482. {
  1483. const char* profile = cmdLine.findOption('p');
  1484. if (NULL == profile)
  1485. {
  1486. stream.write("#ifdef GL_ES\n");
  1487. stream.write("precision highp float;\n");
  1488. stream.write("#endif // GL_ES\n\n");
  1489. }
  1490. else
  1491. {
  1492. stream.writef("#version %s\n\n", profile);
  1493. }
  1494. }
  1495. stream.write(preprocessor.m_preprocessed.c_str(), preprocessor.m_preprocessed.size() );
  1496. stream.close();
  1497. return EXIT_SUCCESS;
  1498. }
  1499. bool compiled = false;
  1500. {
  1501. IStreamWriter* stream = NULL;
  1502. if (NULL != bin2c)
  1503. {
  1504. stream = new Bin2cStream(outFilePath, bin2c);
  1505. }
  1506. else
  1507. {
  1508. stream = new FileWriter(outFilePath);
  1509. }
  1510. if (!stream->open() )
  1511. {
  1512. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1513. return false;
  1514. }
  1515. if (glsl)
  1516. {
  1517. compiled = compileGLSLShader(cmdLine, preprocessor.m_preprocessed, *stream);
  1518. }
  1519. else
  1520. {
  1521. if (hlsl > 3)
  1522. {
  1523. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, *stream);
  1524. }
  1525. else
  1526. {
  1527. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, *stream);
  1528. }
  1529. }
  1530. #if SHADERC_DEBUG
  1531. stream->writeString(filePath);
  1532. #endif // SHADERC_DEBUG
  1533. stream->close();
  1534. delete stream;
  1535. }
  1536. if (compiled)
  1537. {
  1538. if (depends)
  1539. {
  1540. std::string ofp = outFilePath;
  1541. ofp += ".d";
  1542. FileWriter stream(ofp.c_str() );
  1543. if (stream.open() )
  1544. {
  1545. stream.write(outFilePath);
  1546. stream.write(":");
  1547. stream.write(preprocessor.m_depends.c_str() );
  1548. stream.write("\n");
  1549. stream.close();
  1550. }
  1551. }
  1552. return EXIT_SUCCESS;
  1553. }
  1554. }
  1555. delete [] data;
  1556. }
  1557. fprintf(stderr, "Failed to build shader.\n");
  1558. return EXIT_FAILURE;
  1559. }