shaderc.cpp 40 KB

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