shaderc.cpp 40 KB

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