shaderc.cpp 40 KB

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