shaderc.cpp 43 KB

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