shaderc.cpp 41 KB

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