shaderc.cpp 41 KB

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