shaderc.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  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 hlslfp = _cmdLine.findOption('o');
  499. hlslfp += ".hlsl";
  500. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  501. hr = D3DXCompileShaderFromFileA(hlslfp.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 disasmfp = _cmdLine.findOption('o');
  613. disasmfp += ".disasm";
  614. writeFile(disasmfp.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. bool debug = _cmdLine.hasArg('\0', "debug");
  646. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  647. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  648. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  649. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
  650. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  651. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  652. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  653. bool werror = _cmdLine.hasArg('\0', "Werror");
  654. if (werror)
  655. {
  656. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  657. }
  658. uint32_t optimization = 3;
  659. if (_cmdLine.hasArg(optimization, 'O') )
  660. {
  661. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx11)-1);
  662. flags |= s_optimizationLevelDx11[optimization];
  663. }
  664. else
  665. {
  666. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  667. }
  668. BX_TRACE("Profile: %s", profile);
  669. BX_TRACE("Flags: 0x%08x", flags);
  670. ID3DBlob* code;
  671. ID3DBlob* errorMsg;
  672. // Output preprocessed shader so that HLSL can be debugged via GPA
  673. // or PIX. Compiling through memory won't embed preprocessed shader
  674. // file path.
  675. std::string hlslfp;
  676. if (debug)
  677. {
  678. hlslfp = _cmdLine.findOption('o');
  679. hlslfp += ".hlsl";
  680. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  681. }
  682. HRESULT hr = D3DCompile(_code.c_str()
  683. , _code.size()
  684. , hlslfp.c_str()
  685. , NULL
  686. , NULL
  687. , "main"
  688. , profile
  689. , flags
  690. , 0
  691. , &code
  692. , &errorMsg
  693. );
  694. if (FAILED(hr)
  695. || (werror && NULL != errorMsg) )
  696. {
  697. printCode(_code.c_str() );
  698. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x %s\n", (uint32_t)hr, (char*)errorMsg->GetBufferPointer() );
  699. errorMsg->Release();
  700. return false;
  701. }
  702. UniformArray uniforms;
  703. ID3D11ShaderReflection* reflect = NULL;
  704. hr = D3DReflect(code->GetBufferPointer()
  705. , code->GetBufferSize()
  706. , IID_ID3D11ShaderReflection
  707. , (void**)&reflect
  708. );
  709. if (FAILED(hr) )
  710. {
  711. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr);
  712. return false;
  713. }
  714. D3D11_SHADER_DESC desc;
  715. hr = reflect->GetDesc(&desc);
  716. if (FAILED(hr) )
  717. {
  718. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr);
  719. return false;
  720. }
  721. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  722. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  723. BX_TRACE("Input:");
  724. uint8_t attrMask[Attrib::Count];
  725. memset(attrMask, 0, sizeof(attrMask) );
  726. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  727. {
  728. D3D11_SIGNATURE_PARAMETER_DESC spd;
  729. reflect->GetInputParameterDesc(ii, &spd);
  730. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  731. , ii
  732. , spd.SemanticName
  733. , spd.SemanticIndex
  734. , spd.SystemValueType
  735. , spd.ComponentType
  736. , spd.Mask
  737. , spd.Register
  738. );
  739. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
  740. if (ris.m_attr != Attrib::Count)
  741. {
  742. attrMask[ris.m_attr] = 0xff;
  743. }
  744. }
  745. bx::write(_writer, attrMask, sizeof(attrMask) );
  746. BX_TRACE("Output:");
  747. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  748. {
  749. D3D11_SIGNATURE_PARAMETER_DESC spd;
  750. reflect->GetOutputParameterDesc(ii, &spd);
  751. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  752. }
  753. uint16_t size = 0;
  754. for (uint32_t ii = 0; ii < bx::uint32_min(1, desc.ConstantBuffers); ++ii)
  755. {
  756. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  757. D3D11_SHADER_BUFFER_DESC bufferDesc;
  758. hr = cbuffer->GetDesc(&bufferDesc);
  759. size = (uint16_t)bufferDesc.Size;
  760. if (SUCCEEDED(hr) )
  761. {
  762. BX_TRACE("%s, %d, vars %d, size %d"
  763. , bufferDesc.Name
  764. , bufferDesc.Type
  765. , bufferDesc.Variables
  766. , bufferDesc.Size
  767. );
  768. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  769. {
  770. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  771. ID3D11ShaderReflectionType* type = var->GetType();
  772. D3D11_SHADER_VARIABLE_DESC varDesc;
  773. hr = var->GetDesc(&varDesc);
  774. if (SUCCEEDED(hr) )
  775. {
  776. D3D11_SHADER_TYPE_DESC constDesc;
  777. hr = type->GetDesc(&constDesc);
  778. if (SUCCEEDED(hr) )
  779. {
  780. ConstantType::Enum type = findConstantTypeDx11(constDesc, varDesc.Size);
  781. if (ConstantType::Count != type
  782. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  783. {
  784. Uniform un;
  785. un.name = varDesc.Name;
  786. un.type = type;
  787. un.num = constDesc.Elements;
  788. un.regIndex = varDesc.StartOffset;
  789. un.regCount = BX_ALIGN_16(varDesc.Size)/16;
  790. uniforms.push_back(un);
  791. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d"
  792. , varDesc.Name
  793. , varDesc.StartOffset
  794. , varDesc.Size
  795. , varDesc.uFlags
  796. , type
  797. );
  798. }
  799. }
  800. }
  801. }
  802. }
  803. }
  804. BX_TRACE("Bound:");
  805. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  806. {
  807. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  808. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  809. if (SUCCEEDED(hr) )
  810. {
  811. // if (bindDesc.Type == D3D_SIT_SAMPLER)
  812. {
  813. BX_TRACE("\t%s, %d, %d, %d"
  814. , bindDesc.Name
  815. , bindDesc.Type
  816. , bindDesc.BindPoint
  817. , bindDesc.BindCount
  818. );
  819. }
  820. }
  821. }
  822. uint16_t count = (uint16_t)uniforms.size();
  823. bx::write(_writer, count);
  824. bx::write(_writer, size);
  825. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  826. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  827. {
  828. const Uniform& un = *it;
  829. uint8_t nameSize = (uint8_t)un.name.size();
  830. bx::write(_writer, nameSize);
  831. bx::write(_writer, un.name.c_str(), nameSize);
  832. uint8_t type = un.type|fragmentBit;
  833. bx::write(_writer, type);
  834. bx::write(_writer, un.num);
  835. bx::write(_writer, un.regIndex);
  836. bx::write(_writer, un.regCount);
  837. BX_TRACE("%s, %s, %d, %d, %d"
  838. , un.name.c_str()
  839. , s_constantTypeName[un.type]
  840. , un.num
  841. , un.regIndex
  842. , un.regCount
  843. );
  844. }
  845. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  846. bx::write(_writer, shaderSize);
  847. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  848. uint8_t nul = 0;
  849. bx::write(_writer, nul);
  850. if (_cmdLine.hasArg('\0', "disasm") )
  851. {
  852. ID3DBlob* disasm;
  853. D3DDisassemble(code->GetBufferPointer()
  854. , code->GetBufferSize()
  855. , 0
  856. , NULL
  857. , &disasm
  858. );
  859. if (NULL != disasm)
  860. {
  861. std::string disasmfp = _cmdLine.findOption('o');
  862. disasmfp += ".disasm";
  863. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  864. disasm->Release();
  865. }
  866. }
  867. if (NULL != reflect)
  868. {
  869. reflect->Release();
  870. }
  871. if (NULL != errorMsg)
  872. {
  873. errorMsg->Release();
  874. }
  875. code->Release();
  876. return true;
  877. #else
  878. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  879. return false;
  880. #endif // BX_PLATFORM_WINDOWS
  881. }
  882. struct Preprocessor
  883. {
  884. Preprocessor(const char* _filePath, const char* _includeDir = NULL)
  885. : m_tagptr(m_tags)
  886. , m_scratchPos(0)
  887. , m_fgetsPos(0)
  888. {
  889. m_tagptr->tag = FPPTAG_USERDATA;
  890. m_tagptr->data = this;
  891. m_tagptr++;
  892. m_tagptr->tag = FPPTAG_DEPENDS;
  893. m_tagptr->data = (void*)fppDepends;
  894. m_tagptr++;
  895. m_tagptr->tag = FPPTAG_INPUT;
  896. m_tagptr->data = (void*)fppInput;
  897. m_tagptr++;
  898. m_tagptr->tag = FPPTAG_OUTPUT;
  899. m_tagptr->data = (void*)fppOutput;
  900. m_tagptr++;
  901. m_tagptr->tag = FPPTAG_ERROR;
  902. m_tagptr->data = (void*)fppError;
  903. m_tagptr++;
  904. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  905. m_tagptr->data = (void*)0;
  906. m_tagptr++;
  907. m_tagptr->tag = FPPTAG_LINE;
  908. m_tagptr->data = (void*)0;
  909. m_tagptr++;
  910. m_tagptr->tag = FPPTAG_INPUT_NAME;
  911. m_tagptr->data = scratch(_filePath);
  912. m_tagptr++;
  913. if (NULL != _includeDir)
  914. {
  915. addInclude(_includeDir);
  916. }
  917. m_default = "#define lowp\n#define mediump\n#define highp\n";
  918. }
  919. void setDefine(const char* _define)
  920. {
  921. m_tagptr->tag = FPPTAG_DEFINE;
  922. m_tagptr->data = scratch(_define);
  923. m_tagptr++;
  924. }
  925. void setDefaultDefine(const char* _name)
  926. {
  927. char temp[1024];
  928. bx::snprintf(temp, BX_COUNTOF(temp)
  929. , "#ifndef %s\n"
  930. "# define %s 0\n"
  931. "#endif // %s\n"
  932. "\n"
  933. , _name
  934. , _name
  935. , _name
  936. );
  937. m_default += temp;
  938. }
  939. void writef(const char* _format, ...)
  940. {
  941. va_list argList;
  942. va_start(argList, _format);
  943. bx::stringPrintfVargs(m_default, _format, argList);
  944. va_end(argList);
  945. }
  946. void addInclude(const char* _includeDir)
  947. {
  948. char* start = scratch(_includeDir);
  949. for (char* split = strchr(start, ';'); NULL != split; split = strchr(start, ';'))
  950. {
  951. *split = '\0';
  952. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  953. m_tagptr->data = start;
  954. m_tagptr++;
  955. start = split + 1;
  956. }
  957. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  958. m_tagptr->data = start;
  959. m_tagptr++;
  960. }
  961. void addDependency(const char* _fileName)
  962. {
  963. m_depends += " \\\n ";
  964. m_depends += _fileName;
  965. }
  966. bool run(const char* _input)
  967. {
  968. m_fgetsPos = 0;
  969. m_input = m_default;
  970. m_input += "\n\n";
  971. size_t len = strlen(_input)+1;
  972. char* temp = new char[len];
  973. bx::eolLF(temp, len, _input);
  974. m_input += temp;
  975. delete [] temp;
  976. fppTag* tagptr = m_tagptr;
  977. tagptr->tag = FPPTAG_END;
  978. tagptr->data = 0;
  979. tagptr++;
  980. int result = fppPreProcess(m_tags);
  981. return 0 == result;
  982. }
  983. char* fgets(char* _buffer, int _size)
  984. {
  985. int ii = 0;
  986. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  987. {
  988. _buffer[ii++] = ch;
  989. if (ch == '\n' || ii == _size)
  990. {
  991. _buffer[ii] = '\0';
  992. m_fgetsPos++;
  993. return _buffer;
  994. }
  995. }
  996. return NULL;
  997. }
  998. static void fppDepends(char* _fileName, void* _userData)
  999. {
  1000. Preprocessor* thisClass = (Preprocessor*)_userData;
  1001. thisClass->addDependency(_fileName);
  1002. }
  1003. static char* fppInput(char* _buffer, int _size, void* _userData)
  1004. {
  1005. Preprocessor* thisClass = (Preprocessor*)_userData;
  1006. return thisClass->fgets(_buffer, _size);
  1007. }
  1008. static void fppOutput(int _ch, void* _userData)
  1009. {
  1010. Preprocessor* thisClass = (Preprocessor*)_userData;
  1011. thisClass->m_preprocessed += _ch;
  1012. }
  1013. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  1014. {
  1015. vfprintf(stderr, _format, _vargs);
  1016. }
  1017. char* scratch(const char* _str)
  1018. {
  1019. char* result = &m_scratch[m_scratchPos];
  1020. strcpy(result, _str);
  1021. m_scratchPos += (uint32_t)strlen(_str)+1;
  1022. return result;
  1023. }
  1024. fppTag m_tags[MAX_TAGS];
  1025. fppTag* m_tagptr;
  1026. std::string m_depends;
  1027. std::string m_default;
  1028. std::string m_input;
  1029. std::string m_preprocessed;
  1030. char m_scratch[16<<10];
  1031. uint32_t m_scratchPos;
  1032. uint32_t m_fgetsPos;
  1033. };
  1034. const char* baseName(const char* _filePath)
  1035. {
  1036. const char* bs = strrchr(_filePath, '\\');
  1037. const char* fs = strrchr(_filePath, '/');
  1038. const char* column = strrchr(_filePath, ':');
  1039. const char* basename = std::max(std::max(bs, fs), column);
  1040. if (NULL != basename)
  1041. {
  1042. return basename+1;
  1043. }
  1044. return _filePath;
  1045. }
  1046. typedef std::vector<std::string> InOut;
  1047. uint32_t parseInOut(InOut& _inout, const char* _str, const char* _eol)
  1048. {
  1049. uint32_t hash = 0;
  1050. _str = bx::strws(_str);
  1051. if (_str < _eol)
  1052. {
  1053. const char* delim;
  1054. do
  1055. {
  1056. delim = strpbrk(_str, " ,");
  1057. if (NULL != delim)
  1058. {
  1059. delim = delim > _eol ? _eol : delim;
  1060. std::string token;
  1061. token.assign(_str, delim-_str);
  1062. _inout.push_back(token);
  1063. _str = bx::strws(delim + 1);
  1064. }
  1065. }
  1066. while (delim < _eol && _str < _eol && NULL != delim);
  1067. std::sort(_inout.begin(), _inout.end() );
  1068. bx::HashMurmur2A murmur;
  1069. murmur.begin();
  1070. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  1071. {
  1072. murmur.add(it->c_str(), (uint32_t)it->size() );
  1073. }
  1074. hash = murmur.end();
  1075. }
  1076. return hash;
  1077. }
  1078. // c - compute
  1079. // d - domain
  1080. // f - fragment
  1081. // g - geometry
  1082. // h - hull
  1083. // v - vertex
  1084. //
  1085. // OpenGL #version Features Direct3D Features Shader Model
  1086. // 2.1 120 vf 9.0 vf 2.0
  1087. // 3.0 130
  1088. // 3.1 140
  1089. // 3.2 150 vgf
  1090. // 3.3 330 10.0 vgf 4.0
  1091. // 4.0 400 vhdgf
  1092. // 4.1 410
  1093. // 4.2 420 11.0 vhdgf+c 5.0
  1094. // 4.3 430 vhdgf+c
  1095. void help(const char* _error = NULL)
  1096. {
  1097. if (NULL != _error)
  1098. {
  1099. fprintf(stderr, "Error:\n%s\n\n", _error);
  1100. }
  1101. fprintf(stderr
  1102. , "shaderc, bgfx shader compiler tool\n"
  1103. "Copyright 2011-2013 Branimir Karadzic. All rights reserved.\n"
  1104. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  1105. );
  1106. fprintf(stderr
  1107. , "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  1108. "\n"
  1109. "Options:\n"
  1110. " -f <file path> Input file path.\n"
  1111. " -i <include path> Include path (for multiple paths use semicolon).\n"
  1112. " -o <file path> Output file path.\n"
  1113. " --bin2c <file path> Generate C header file.\n"
  1114. " --depends <file path> Generate makefile style depends file.\n"
  1115. " --platform <platform> Target platform.\n"
  1116. " android\n"
  1117. " ios\n"
  1118. " linux\n"
  1119. " nacl\n"
  1120. " osx\n"
  1121. " windows\n"
  1122. " --type <type> Shader type (vertex, fragment)\n"
  1123. " --varyingdef <file path> Path to varying.def.sc file.\n"
  1124. "\n"
  1125. "Options (DX9 and DX11 only):\n"
  1126. "\n"
  1127. " --debug Debug information.\n"
  1128. " --disasm Disassemble compiled shader.\n"
  1129. " -p, --profile <profile> Shader model (f.e. ps_3_0).\n"
  1130. " -O <level> Optimization level (0, 1, 2, 3).\n"
  1131. " --Werror Treat warnings as errors.\n"
  1132. "\n"
  1133. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  1134. );
  1135. }
  1136. int main(int _argc, const char* _argv[])
  1137. {
  1138. bx::CommandLine cmdLine(_argc, _argv);
  1139. if (cmdLine.hasArg('h', "help") )
  1140. {
  1141. help();
  1142. return EXIT_FAILURE;
  1143. }
  1144. const char* filePath = cmdLine.findOption('f');
  1145. if (NULL == filePath)
  1146. {
  1147. help("Shader file name must be specified.");
  1148. return EXIT_FAILURE;
  1149. }
  1150. const char* outFilePath = cmdLine.findOption('o');
  1151. if (NULL == outFilePath)
  1152. {
  1153. help("Output file name must be specified.");
  1154. return EXIT_FAILURE;
  1155. }
  1156. const char* type = cmdLine.findOption('\0', "type");
  1157. if (NULL == type)
  1158. {
  1159. help("Must specify shader type.");
  1160. return EXIT_FAILURE;
  1161. }
  1162. const char* platform = cmdLine.findOption('\0', "platform");
  1163. if (NULL == platform)
  1164. {
  1165. help("Must specify platform.");
  1166. return EXIT_FAILURE;
  1167. }
  1168. uint32_t hlsl = 2;
  1169. const char* profile = cmdLine.findOption('p', "profile");
  1170. if (NULL != profile)
  1171. {
  1172. if (0 == strncmp(&profile[1], "s_3", 3) )
  1173. {
  1174. hlsl = 3;
  1175. }
  1176. else if (0 == strncmp(&profile[1], "s_4", 3) )
  1177. {
  1178. hlsl = 4;
  1179. }
  1180. else if (0 == strncmp(&profile[1], "s_5", 3) )
  1181. {
  1182. hlsl = 5;
  1183. }
  1184. }
  1185. const char* bin2c = NULL;
  1186. if (cmdLine.hasArg("bin2c") )
  1187. {
  1188. bin2c = cmdLine.findOption("bin2c");
  1189. if (NULL == bin2c)
  1190. {
  1191. bin2c = baseName(outFilePath);
  1192. uint32_t len = (uint32_t)strlen(bin2c);
  1193. char* temp = (char*)alloca(len+1);
  1194. for (char *out = temp; *bin2c != '\0';)
  1195. {
  1196. char ch = *bin2c++;
  1197. if (isalnum(ch) )
  1198. {
  1199. *out++ = ch;
  1200. }
  1201. else
  1202. {
  1203. *out++ = '_';
  1204. }
  1205. }
  1206. temp[len] = '\0';
  1207. bin2c = temp;
  1208. }
  1209. }
  1210. bool depends = cmdLine.hasArg("depends");
  1211. bool preprocessOnly = cmdLine.hasArg("preprocess");
  1212. const char* includeDir = cmdLine.findOption('i');
  1213. Preprocessor preprocessor(filePath, includeDir);
  1214. std::string dir;
  1215. {
  1216. const char* base = baseName(filePath);
  1217. if (base != filePath)
  1218. {
  1219. dir.assign(filePath, base-filePath);
  1220. preprocessor.addInclude(dir.c_str() );
  1221. }
  1222. }
  1223. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  1224. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  1225. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  1226. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  1227. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  1228. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  1229. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  1230. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  1231. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  1232. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  1233. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  1234. bool glsl = false;
  1235. if (0 == bx::stricmp(platform, "android") )
  1236. {
  1237. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  1238. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1239. glsl = true;
  1240. }
  1241. else if (0 == bx::stricmp(platform, "ios") )
  1242. {
  1243. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1244. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1245. glsl = true;
  1246. }
  1247. else if (0 == bx::stricmp(platform, "linux") )
  1248. {
  1249. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  1250. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1251. glsl = true;
  1252. }
  1253. else if (0 == bx::stricmp(platform, "nacl") )
  1254. {
  1255. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  1256. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1257. glsl = true;
  1258. }
  1259. else if (0 == bx::stricmp(platform, "osx") )
  1260. {
  1261. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  1262. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1263. glsl = true;
  1264. }
  1265. else if (0 == bx::stricmp(platform, "windows") )
  1266. {
  1267. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  1268. char temp[256];
  1269. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  1270. preprocessor.setDefine(temp);
  1271. }
  1272. else if (0 == bx::stricmp(platform, "xbox360") )
  1273. {
  1274. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  1275. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=3");
  1276. }
  1277. else
  1278. {
  1279. fprintf(stderr, "Unknown platform %s?!", platform);
  1280. return EXIT_FAILURE;
  1281. }
  1282. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  1283. bool fragment = false;
  1284. switch (tolower(type[0]) )
  1285. {
  1286. case 'f':
  1287. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1288. fragment = true;
  1289. break;
  1290. case 'v':
  1291. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1292. break;
  1293. default:
  1294. fprintf(stderr, "Unknown type: %s?!", type);
  1295. return EXIT_FAILURE;
  1296. }
  1297. FILE* file = fopen(filePath, "r");
  1298. if (NULL != file)
  1299. {
  1300. VaryingMap varyingMap;
  1301. std::string defaultVarying = dir + "varying.def.sc";
  1302. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  1303. File attribdef(varyingdef);
  1304. const char* parse = attribdef.getData();
  1305. if (NULL != parse
  1306. && *parse != '\0')
  1307. {
  1308. preprocessor.addDependency(varyingdef);
  1309. }
  1310. while (NULL != parse
  1311. && *parse != '\0')
  1312. {
  1313. parse = bx::strws(parse);
  1314. const char* eol = strchr(parse, ';');
  1315. if (NULL != eol)
  1316. {
  1317. const char* type = parse;
  1318. const char* name = parse = bx::strws(bx::strword(parse) );
  1319. const char* column = parse = bx::strws(bx::strword(parse) );
  1320. const char* semantics = parse = bx::strws(bx::strnws(parse) );
  1321. const char* assign = parse = bx::strws(bx::strword(parse) );
  1322. const char* init = parse = bx::strws(bx::strnws(parse) );
  1323. if (type < eol
  1324. && name < eol
  1325. && column < eol
  1326. && ':' == *column
  1327. && semantics < eol)
  1328. {
  1329. Varying var;
  1330. var.m_type.assign(type, bx::strword(type)-type);
  1331. var.m_name.assign(name, bx::strword(name)-name);
  1332. var.m_semantics.assign(semantics, bx::strword(semantics)-semantics);
  1333. if (assign < eol
  1334. && '=' == *assign
  1335. && init < eol)
  1336. {
  1337. var.m_init.assign(init, eol-init);
  1338. }
  1339. varyingMap.insert(std::make_pair(var.m_name, var) );
  1340. }
  1341. parse = bx::strnl(eol);
  1342. }
  1343. }
  1344. const size_t padding = 16;
  1345. uint32_t size = (uint32_t)fsize(file);
  1346. char* data = new char[size+padding+1];
  1347. size = (uint32_t)fread(data, 1, size, file);
  1348. // Compiler generates "error X3000: syntax error: unexpected end of file"
  1349. // if input doesn't have empty line at EOF.
  1350. data[size] = '\n';
  1351. memset(&data[size+1], 0, padding);
  1352. fclose(file);
  1353. char* entry = strstr(data, "void main()");
  1354. if (NULL == entry)
  1355. {
  1356. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1357. }
  1358. else
  1359. {
  1360. InOut shaderInputs;
  1361. InOut shaderOutputs;
  1362. uint32_t inputHash = 0;
  1363. uint32_t outputHash = 0;
  1364. const char* input = data;
  1365. while (input[0] == '$')
  1366. {
  1367. const char* str = input+1;
  1368. const char* eol = bx::streol(str);
  1369. const char* nl = bx::strnl(eol);
  1370. input = nl;
  1371. if (0 == strncmp(str, "input", 5) )
  1372. {
  1373. str += 5;
  1374. const char* comment = strstr(str, "//");
  1375. eol = NULL != comment && comment < eol ? comment : eol;
  1376. inputHash = parseInOut(shaderInputs, str, eol);
  1377. }
  1378. else if (0 == strncmp(str, "output", 6) )
  1379. {
  1380. str += 6;
  1381. const char* comment = strstr(str, "//");
  1382. eol = NULL != comment && comment < eol ? comment : eol;
  1383. outputHash = parseInOut(shaderOutputs, str, eol);
  1384. }
  1385. }
  1386. if (glsl)
  1387. {
  1388. preprocessor.writef(
  1389. "#define ivec2 vec2\n"
  1390. "#define ivec3 vec3\n"
  1391. "#define ivec4 vec4\n"
  1392. );
  1393. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1394. {
  1395. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1396. if (varyingIt != varyingMap.end() )
  1397. {
  1398. const Varying& var = varyingIt->second;
  1399. const char* name = var.m_name.c_str();
  1400. if (0 == strncmp(name, "a_", 2)
  1401. || 0 == strncmp(name, "i_", 2) )
  1402. {
  1403. preprocessor.writef("attribute %s %s;\n", var.m_type.c_str(), name);
  1404. }
  1405. else
  1406. {
  1407. preprocessor.writef("varying %s %s;\n", var.m_type.c_str(), name);
  1408. }
  1409. }
  1410. }
  1411. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.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("varying %s %s;\n", var.m_type.c_str(), var.m_name.c_str() );
  1418. }
  1419. }
  1420. }
  1421. else
  1422. {
  1423. preprocessor.writef(
  1424. "#define lowp\n"
  1425. "#define mediump\n"
  1426. "#define highp\n"
  1427. "#define ivec2 int2\n"
  1428. "#define ivec3 int3\n"
  1429. "#define ivec4 int4\n"
  1430. "#define vec2 float2\n"
  1431. "#define vec3 float3\n"
  1432. "#define vec4 float4\n"
  1433. "#define mat2 float2x2\n"
  1434. "#define mat3 float3x3\n"
  1435. "#define mat4 float4x4\n"
  1436. );
  1437. entry[4] = '_';
  1438. if (fragment)
  1439. {
  1440. bool hasFragCoord = NULL != strstr(data, "gl_FragCoord") || hlsl > 3;
  1441. bool hasFragDepth = NULL != strstr(data, "gl_FragDepth");
  1442. bool hasFrontFacing = NULL != strstr(data, "gl_FrontFacing");
  1443. preprocessor.writef("#define void_main()");
  1444. preprocessor.writef(" \\\n\tvoid main(");
  1445. uint32_t arg = 0;
  1446. if (hasFragCoord)
  1447. {
  1448. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1449. ++arg;
  1450. }
  1451. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1452. {
  1453. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1454. if (varyingIt != varyingMap.end() )
  1455. {
  1456. const Varying& var = varyingIt->second;
  1457. preprocessor.writef(" \\\n\t%s%s %s : %s", arg++ > 0 ? ", " : " ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1458. }
  1459. }
  1460. preprocessor.writef(
  1461. " \\\n\t%sout vec4 gl_FragColor : SV_TARGET"
  1462. , arg++ > 0 ? ", " : " "
  1463. );
  1464. if (hasFragDepth)
  1465. {
  1466. preprocessor.writef(
  1467. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1468. , arg++ > 0 ? ", " : " "
  1469. );
  1470. }
  1471. if (hasFrontFacing)
  1472. {
  1473. preprocessor.writef(
  1474. " \\\n\t%sfloat __vface : VFACE"
  1475. , arg++ > 0 ? ", " : " "
  1476. );
  1477. }
  1478. preprocessor.writef(
  1479. " \\\n\t)\n"
  1480. );
  1481. if (hasFrontFacing)
  1482. {
  1483. preprocessor.writef(
  1484. "#define gl_FrontFacing (__vface <= 0.0)\n"
  1485. );
  1486. }
  1487. }
  1488. else
  1489. {
  1490. const char* brace = strstr(entry, "{");
  1491. if (NULL != brace)
  1492. {
  1493. const char* end = bx::strmb(brace, '{', '}');
  1494. if (NULL != end)
  1495. {
  1496. strins(const_cast<char*>(end), "__RETURN__;\n");
  1497. }
  1498. }
  1499. preprocessor.writef(
  1500. "struct Output\n"
  1501. "{\n"
  1502. "\tvec4 gl_Position : SV_POSITION;\n"
  1503. "#define gl_Position _varying_.gl_Position\n"
  1504. );
  1505. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1506. {
  1507. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1508. if (varyingIt != varyingMap.end() )
  1509. {
  1510. const Varying& var = varyingIt->second;
  1511. preprocessor.writef("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1512. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  1513. }
  1514. }
  1515. preprocessor.writef(
  1516. "};\n"
  1517. );
  1518. preprocessor.writef("#define void_main() \\\n");
  1519. preprocessor.writef("Output main(");
  1520. bool first = true;
  1521. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1522. {
  1523. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1524. if (varyingIt != varyingMap.end() )
  1525. {
  1526. const Varying& var = varyingIt->second;
  1527. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  1528. first = false;
  1529. }
  1530. }
  1531. preprocessor.writef(
  1532. ") \\\n"
  1533. "{ \\\n"
  1534. "\tOutput _varying_;"
  1535. );
  1536. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1537. {
  1538. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1539. if (varyingIt != varyingMap.end() )
  1540. {
  1541. const Varying& var = varyingIt->second;
  1542. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  1543. }
  1544. }
  1545. preprocessor.writef(
  1546. "\n#define __RETURN__ \\\n"
  1547. "\t} \\\n"
  1548. "\treturn _varying_"
  1549. );
  1550. }
  1551. }
  1552. if (preprocessor.run(input) )
  1553. {
  1554. BX_TRACE("Input file: %s", filePath);
  1555. BX_TRACE("Output file: %s", outFilePath);
  1556. if (preprocessOnly)
  1557. {
  1558. bx::CrtFileWriter writer;
  1559. if (0 != writer.open(outFilePath) )
  1560. {
  1561. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1562. return EXIT_FAILURE;
  1563. }
  1564. if (glsl)
  1565. {
  1566. const char* profile = cmdLine.findOption('p', "profile");
  1567. if (NULL == profile)
  1568. {
  1569. writef(&writer, "#ifdef GL_ES\n");
  1570. writef(&writer, "precision highp float;\n");
  1571. writef(&writer, "#endif // GL_ES\n\n");
  1572. }
  1573. else
  1574. {
  1575. writef(&writer, "#version %s\n\n", profile);
  1576. }
  1577. }
  1578. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1579. writer.close();
  1580. return EXIT_SUCCESS;
  1581. }
  1582. bool compiled = false;
  1583. {
  1584. bx::CrtFileWriter* writer = NULL;
  1585. if (NULL != bin2c)
  1586. {
  1587. writer = new Bin2cWriter(bin2c);
  1588. }
  1589. else
  1590. {
  1591. writer = new bx::CrtFileWriter;
  1592. }
  1593. if (0 != writer->open(outFilePath) )
  1594. {
  1595. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1596. return EXIT_FAILURE;
  1597. }
  1598. if (fragment)
  1599. {
  1600. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  1601. bx::write(writer, inputHash);
  1602. }
  1603. else
  1604. {
  1605. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  1606. bx::write(writer, outputHash);
  1607. }
  1608. if (glsl)
  1609. {
  1610. compiled = compileGLSLShader(cmdLine, preprocessor.m_preprocessed, writer);
  1611. }
  1612. else
  1613. {
  1614. if (hlsl > 3)
  1615. {
  1616. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1617. }
  1618. else
  1619. {
  1620. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1621. }
  1622. }
  1623. writer->close();
  1624. delete writer;
  1625. }
  1626. if (compiled)
  1627. {
  1628. if (depends)
  1629. {
  1630. std::string ofp = outFilePath;
  1631. ofp += ".d";
  1632. bx::CrtFileWriter writer;
  1633. if (0 == writer.open(ofp.c_str() ) )
  1634. {
  1635. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1636. writer.close();
  1637. }
  1638. }
  1639. return EXIT_SUCCESS;
  1640. }
  1641. }
  1642. }
  1643. delete [] data;
  1644. }
  1645. remove(outFilePath);
  1646. fprintf(stderr, "Failed to build shader.\n");
  1647. return EXIT_FAILURE;
  1648. }