PageRenderTime 29ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/bgfx/tools/shaderc/shaderc.cpp

https://gitlab.com/JFT/Irrlicht_extended
C++ | 2031 lines | 1732 code | 257 blank | 42 comment | 334 complexity | 535b08197f7229050ad470f4e0e87ef3 MD5 | raw file
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "shaderc.h"
  6. #include <bx/commandline.h>
  7. #include <bx/filepath.h>
  8. #define MAX_TAGS 256
  9. extern "C"
  10. {
  11. #include <fpp.h>
  12. } // extern "C"
  13. #define BGFX_SHADER_BIN_VERSION 6
  14. #define BGFX_CHUNK_MAGIC_CSH BX_MAKEFOURCC('C', 'S', 'H', BGFX_SHADER_BIN_VERSION)
  15. #define BGFX_CHUNK_MAGIC_FSH BX_MAKEFOURCC('F', 'S', 'H', BGFX_SHADER_BIN_VERSION)
  16. #define BGFX_CHUNK_MAGIC_VSH BX_MAKEFOURCC('V', 'S', 'H', BGFX_SHADER_BIN_VERSION)
  17. #define BGFX_SHADERC_VERSION_MAJOR 1
  18. #define BGFX_SHADERC_VERSION_MINOR 16
  19. namespace bgfx
  20. {
  21. bool g_verbose = false;
  22. static const char* s_ARB_shader_texture_lod[] =
  23. {
  24. "texture2DLod",
  25. "texture2DArrayLod", // BK - interacts with ARB_texture_array.
  26. "texture2DProjLod",
  27. "texture2DGrad",
  28. "texture2DProjGrad",
  29. "texture3DLod",
  30. "texture3DProjLod",
  31. "texture3DGrad",
  32. "texture3DProjGrad",
  33. "textureCubeLod",
  34. "textureCubeGrad",
  35. "shadow2DLod",
  36. "shadow2DProjLod",
  37. NULL
  38. // "texture1DLod",
  39. // "texture1DProjLod",
  40. // "shadow1DLod",
  41. // "shadow1DProjLod",
  42. };
  43. static const char* s_EXT_shader_texture_lod[] =
  44. {
  45. "texture2DLod",
  46. "texture2DProjLod",
  47. "textureCubeLod",
  48. "texture2DGrad",
  49. "texture2DProjGrad",
  50. "textureCubeGrad",
  51. NULL
  52. };
  53. static const char* s_EXT_shadow_samplers[] =
  54. {
  55. "shadow2D",
  56. "shadow2DProj",
  57. "sampler2DShadow",
  58. NULL
  59. };
  60. static const char* s_OES_standard_derivatives[] =
  61. {
  62. "dFdx",
  63. "dFdy",
  64. "fwidth",
  65. NULL
  66. };
  67. static const char* s_OES_texture_3D[] =
  68. {
  69. "texture3D",
  70. "texture3DProj",
  71. "texture3DLod",
  72. "texture3DProjLod",
  73. NULL
  74. };
  75. static const char* s_EXT_gpu_shader4[] =
  76. {
  77. "gl_VertexID",
  78. "gl_InstanceID",
  79. NULL
  80. };
  81. static const char* s_ARB_gpu_shader5[] =
  82. {
  83. "bitfieldReverse",
  84. "floatBitsToInt",
  85. "floatBitsToUint",
  86. "intBitsToFloat",
  87. "uintBitsToFloat",
  88. NULL
  89. };
  90. static const char* s_ARB_shading_language_packing[] =
  91. {
  92. "packHalf2x16",
  93. "unpackHalf2x16",
  94. NULL
  95. };
  96. static const char* s_130[] =
  97. {
  98. "uint",
  99. "uint2",
  100. "uint3",
  101. "uint4",
  102. "isampler2D",
  103. "usampler2D",
  104. "isampler3D",
  105. "usampler3D",
  106. "isamplerCube",
  107. "usamplerCube",
  108. NULL
  109. };
  110. static const char* s_textureArray[] =
  111. {
  112. "texture2DArray",
  113. "texture2DArrayLod",
  114. "shadow2DArray",
  115. NULL
  116. };
  117. static const char* s_ARB_texture_multisample[] =
  118. {
  119. "sampler2DMS",
  120. "isampler2DMS",
  121. "usampler2DMS",
  122. NULL
  123. };
  124. static const char* s_texelFetch[] =
  125. {
  126. "texelFetch",
  127. "texelFetchOffset",
  128. NULL
  129. };
  130. const char* s_uniformTypeName[] =
  131. {
  132. "int", "int",
  133. NULL, NULL,
  134. "vec4", "float4",
  135. "mat3", "float3x3",
  136. "mat4", "float4x4",
  137. };
  138. BX_STATIC_ASSERT(BX_COUNTOF(s_uniformTypeName) == UniformType::Count*2);
  139. static const char* s_allowedVertexShaderInputs[] =
  140. {
  141. "a_position",
  142. "a_normal",
  143. "a_tangent",
  144. "a_bitangent",
  145. "a_color0",
  146. "a_color1",
  147. "a_color2",
  148. "a_color3",
  149. "a_indices",
  150. "a_weight",
  151. "a_texcoord0",
  152. "a_texcoord1",
  153. "a_texcoord2",
  154. "a_texcoord3",
  155. "a_texcoord4",
  156. "a_texcoord5",
  157. "a_texcoord6",
  158. "a_texcoord7",
  159. "i_data0",
  160. "i_data1",
  161. "i_data2",
  162. "i_data3",
  163. "i_data4",
  164. NULL
  165. };
  166. Options::Options()
  167. : shaderType(' ')
  168. , disasm(false)
  169. , raw(false)
  170. , preprocessOnly(false)
  171. , depends(false)
  172. , debugInformation(false)
  173. , avoidFlowControl(false)
  174. , noPreshader(false)
  175. , partialPrecision(false)
  176. , preferFlowControl(false)
  177. , backwardsCompatibility(false)
  178. , warningsAreErrors(false)
  179. , keepIntermediate(false)
  180. , optimize(false)
  181. , optimizationLevel(3)
  182. {
  183. }
  184. void Options::dump()
  185. {
  186. BX_TRACE("Options:\n"
  187. "\t shaderType: %c\n"
  188. "\t platform: %s\n"
  189. "\t profile: %s\n"
  190. "\t inputFile: %s\n"
  191. "\t outputFile: %s\n"
  192. "\t disasm: %s\n"
  193. "\t raw: %s\n"
  194. "\t preprocessOnly: %s\n"
  195. "\t depends: %s\n"
  196. "\t debugInformation: %s\n"
  197. "\t avoidFlowControl: %s\n"
  198. "\t noPreshader: %s\n"
  199. "\t partialPrecision: %s\n"
  200. "\t preferFlowControl: %s\n"
  201. "\t backwardsCompatibility: %s\n"
  202. "\t warningsAreErrors: %s\n"
  203. "\t keepIntermediate: %s\n"
  204. "\t optimize: %s\n"
  205. "\t optimizationLevel: %d\n"
  206. , shaderType
  207. , platform.c_str()
  208. , profile.c_str()
  209. , inputFilePath.c_str()
  210. , outputFilePath.c_str()
  211. , disasm ? "true" : "false"
  212. , raw ? "true" : "false"
  213. , preprocessOnly ? "true" : "false"
  214. , depends ? "true" : "false"
  215. , debugInformation ? "true" : "false"
  216. , avoidFlowControl ? "true" : "false"
  217. , noPreshader ? "true" : "false"
  218. , partialPrecision ? "true" : "false"
  219. , preferFlowControl ? "true" : "false"
  220. , backwardsCompatibility ? "true" : "false"
  221. , warningsAreErrors ? "true" : "false"
  222. , keepIntermediate ? "true" : "false"
  223. , optimize ? "true" : "false"
  224. , optimizationLevel
  225. );
  226. for (size_t ii = 0; ii < includeDirs.size(); ++ii)
  227. {
  228. BX_TRACE("\t include :%s\n", includeDirs[ii].c_str());
  229. }
  230. for (size_t ii = 0; ii < defines.size(); ++ii)
  231. {
  232. BX_TRACE("\t define :%s\n", defines[ii].c_str());
  233. }
  234. for (size_t ii = 0; ii < dependencies.size(); ++ii)
  235. {
  236. BX_TRACE("\t dependency :%s\n", dependencies[ii].c_str());
  237. }
  238. }
  239. const char* interpolationDx11(const char* _glsl)
  240. {
  241. if (0 == bx::strCmp(_glsl, "smooth") )
  242. {
  243. return "linear";
  244. }
  245. else if (0 == bx::strCmp(_glsl, "flat") )
  246. {
  247. return "nointerpolation";
  248. }
  249. return _glsl; // centroid, noperspective
  250. }
  251. const char* getUniformTypeName(UniformType::Enum _enum)
  252. {
  253. uint32_t idx = _enum & ~(BGFX_UNIFORM_FRAGMENTBIT|BGFX_UNIFORM_SAMPLERBIT);
  254. if (idx < UniformType::Count)
  255. {
  256. return s_uniformTypeName[idx];
  257. }
  258. return "Unknown uniform type?!";
  259. }
  260. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  261. {
  262. for (uint32_t ii = 0; ii < UniformType::Count*2; ++ii)
  263. {
  264. if (NULL != s_uniformTypeName[ii]
  265. && 0 == bx::strCmp(_name, s_uniformTypeName[ii]) )
  266. {
  267. return UniformType::Enum(ii/2);
  268. }
  269. }
  270. return UniformType::Count;
  271. }
  272. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  273. {
  274. va_list argList;
  275. va_start(argList, _format);
  276. char temp[2048];
  277. char* out = temp;
  278. int32_t max = sizeof(temp);
  279. int32_t len = bx::vsnprintf(out, max, _format, argList);
  280. if (len > max)
  281. {
  282. out = (char*)alloca(len);
  283. len = bx::vsnprintf(out, len, _format, argList);
  284. }
  285. len = bx::write(_writer, out, len);
  286. va_end(argList);
  287. return len;
  288. }
  289. class Bin2cWriter : public bx::FileWriter
  290. {
  291. public:
  292. Bin2cWriter(const bx::StringView& _name)
  293. : m_name(_name)
  294. {
  295. }
  296. virtual ~Bin2cWriter()
  297. {
  298. }
  299. virtual void close() override
  300. {
  301. generate();
  302. return bx::FileWriter::close();
  303. }
  304. virtual int32_t write(const void* _data, int32_t _size, bx::Error*) override
  305. {
  306. const char* data = (const char*)_data;
  307. m_buffer.insert(m_buffer.end(), data, data+_size);
  308. return _size;
  309. }
  310. private:
  311. void generate()
  312. {
  313. #define HEX_DUMP_WIDTH 16
  314. #define HEX_DUMP_SPACE_WIDTH 96
  315. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  316. const uint8_t* data = &m_buffer[0];
  317. uint32_t size = (uint32_t)m_buffer.size();
  318. outf("static const uint8_t %.*s[%d] =\n{\n", m_name.getLength(), m_name.getPtr(), size);
  319. if (NULL != data)
  320. {
  321. char hex[HEX_DUMP_SPACE_WIDTH+1];
  322. char ascii[HEX_DUMP_WIDTH+1];
  323. uint32_t hexPos = 0;
  324. uint32_t asciiPos = 0;
  325. for (uint32_t ii = 0; ii < size; ++ii)
  326. {
  327. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  328. hexPos += 6;
  329. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' && data[asciiPos] != '\t' ? data[asciiPos] : '.';
  330. asciiPos++;
  331. if (HEX_DUMP_WIDTH == asciiPos)
  332. {
  333. ascii[asciiPos] = '\0';
  334. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  335. data += asciiPos;
  336. hexPos = 0;
  337. asciiPos = 0;
  338. }
  339. }
  340. if (0 != asciiPos)
  341. {
  342. ascii[asciiPos] = '\0';
  343. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  344. }
  345. }
  346. outf("};\n");
  347. #undef HEX_DUMP_WIDTH
  348. #undef HEX_DUMP_SPACE_WIDTH
  349. #undef HEX_DUMP_FORMAT
  350. }
  351. int32_t outf(const char* _format, ...)
  352. {
  353. va_list argList;
  354. va_start(argList, _format);
  355. char temp[2048];
  356. char* out = temp;
  357. int32_t max = sizeof(temp);
  358. int32_t len = bx::vsnprintf(out, max, _format, argList);
  359. if (len > max)
  360. {
  361. out = (char*)alloca(len);
  362. len = bx::vsnprintf(out, len, _format, argList);
  363. }
  364. bx::Error err;
  365. int32_t size = bx::FileWriter::write(out, len, &err);
  366. va_end(argList);
  367. return size;
  368. }
  369. bx::StringView m_name;
  370. typedef std::vector<uint8_t> Buffer;
  371. Buffer m_buffer;
  372. };
  373. struct Varying
  374. {
  375. std::string m_precision;
  376. std::string m_interpolation;
  377. std::string m_name;
  378. std::string m_type;
  379. std::string m_init;
  380. std::string m_semantics;
  381. };
  382. typedef std::unordered_map<std::string, Varying> VaryingMap;
  383. class File
  384. {
  385. public:
  386. File()
  387. : m_data(NULL)
  388. , m_size(0)
  389. {
  390. }
  391. ~File()
  392. {
  393. delete [] m_data;
  394. }
  395. void load(const bx::FilePath& _filePath)
  396. {
  397. bx::FileReader reader;
  398. if (bx::open(&reader, _filePath) )
  399. {
  400. m_size = (uint32_t)bx::getSize(&reader);
  401. m_data = new char[m_size+1];
  402. m_size = (uint32_t)bx::read(&reader, m_data, m_size);
  403. bx::close(&reader);
  404. if (m_data[0] == '\xef'
  405. && m_data[1] == '\xbb'
  406. && m_data[2] == '\xbf')
  407. {
  408. bx::memMove(m_data, &m_data[3], m_size-3);
  409. m_size -= 3;
  410. }
  411. m_data[m_size] = '\0';
  412. }
  413. }
  414. const char* getData() const
  415. {
  416. return m_data;
  417. }
  418. uint32_t getSize() const
  419. {
  420. return m_size;
  421. }
  422. private:
  423. char* m_data;
  424. uint32_t m_size;
  425. };
  426. char* strInsert(char* _str, const char* _insert)
  427. {
  428. uint32_t len = bx::strLen(_insert);
  429. bx::memMove(&_str[len], _str, bx::strLen(_str) );
  430. bx::memCopy(_str, _insert, len);
  431. return _str + len;
  432. }
  433. void strReplace(char* _str, const char* _find, const char* _replace)
  434. {
  435. const int32_t len = bx::strLen(_find);
  436. char* replace = (char*)alloca(len+1);
  437. bx::strCopy(replace, len+1, _replace);
  438. for (int32_t ii = bx::strLen(replace); ii < len; ++ii)
  439. {
  440. replace[ii] = ' ';
  441. }
  442. replace[len] = '\0';
  443. BX_CHECK(len >= bx::strLen(_replace), "");
  444. for (bx::StringView ptr = bx::strFind(_str, _find)
  445. ; !ptr.isEmpty()
  446. ; ptr = bx::strFind(ptr.getPtr() + len, _find)
  447. )
  448. {
  449. bx::memCopy(const_cast<char*>(ptr.getPtr() ), replace, len);
  450. }
  451. }
  452. void strNormalizeEol(char* _str)
  453. {
  454. strReplace(_str, "\r\n", "\n");
  455. strReplace(_str, "\r", "\n");
  456. }
  457. void printCode(const char* _code, int32_t _line, int32_t _start, int32_t _end, int32_t _column)
  458. {
  459. bx::printf("Code:\n---\n");
  460. bx::Error err;
  461. LineReader reader(_code);
  462. for (int32_t line = 1; err.isOk() && line < _end; ++line)
  463. {
  464. char str[4096];
  465. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  466. if (err.isOk()
  467. && line >= _start)
  468. {
  469. bx::StringView strLine(str, len);
  470. if (_line == line)
  471. {
  472. bx::printf("\n");
  473. bx::printf(">>> %3d: %.*s", line, strLine.getLength(), strLine.getPtr() );
  474. if (-1 != _column)
  475. {
  476. bx::printf(">>> %3d: %*s\n", _column, _column, "^");
  477. }
  478. bx::printf("\n");
  479. }
  480. else
  481. {
  482. bx::printf(" %3d: %.*s", line, strLine.getLength(), strLine.getPtr() );
  483. }
  484. }
  485. }
  486. bx::printf("---\n");
  487. }
  488. void writeFile(const char* _filePath, const void* _data, int32_t _size)
  489. {
  490. bx::FileWriter out;
  491. if (bx::open(&out, _filePath) )
  492. {
  493. bx::write(&out, _data, _size);
  494. bx::close(&out);
  495. }
  496. }
  497. struct Preprocessor
  498. {
  499. Preprocessor(const char* _filePath, bool _essl)
  500. : m_tagptr(m_tags)
  501. , m_scratchPos(0)
  502. , m_fgetsPos(0)
  503. {
  504. m_tagptr->tag = FPPTAG_USERDATA;
  505. m_tagptr->data = this;
  506. m_tagptr++;
  507. m_tagptr->tag = FPPTAG_DEPENDS;
  508. m_tagptr->data = (void*)fppDepends;
  509. m_tagptr++;
  510. m_tagptr->tag = FPPTAG_INPUT;
  511. m_tagptr->data = (void*)fppInput;
  512. m_tagptr++;
  513. m_tagptr->tag = FPPTAG_OUTPUT;
  514. m_tagptr->data = (void*)fppOutput;
  515. m_tagptr++;
  516. m_tagptr->tag = FPPTAG_ERROR;
  517. m_tagptr->data = (void*)fppError;
  518. m_tagptr++;
  519. m_tagptr->tag = FPPTAG_SHOWVERSION;
  520. m_tagptr->data = (void*)0;
  521. m_tagptr++;
  522. m_tagptr->tag = FPPTAG_LINE;
  523. m_tagptr->data = (void*)0;
  524. m_tagptr++;
  525. m_tagptr->tag = FPPTAG_INPUT_NAME;
  526. m_tagptr->data = scratch(_filePath);
  527. m_tagptr++;
  528. if (!_essl)
  529. {
  530. m_default = "#define lowp\n#define mediump\n#define highp\n";
  531. }
  532. }
  533. void setDefine(const char* _define)
  534. {
  535. m_tagptr->tag = FPPTAG_DEFINE;
  536. m_tagptr->data = scratch(_define);
  537. m_tagptr++;
  538. }
  539. void setDefaultDefine(const char* _name)
  540. {
  541. char temp[1024];
  542. bx::snprintf(temp, BX_COUNTOF(temp)
  543. , "#ifndef %s\n"
  544. "# define %s 0\n"
  545. "#endif // %s\n"
  546. "\n"
  547. , _name
  548. , _name
  549. , _name
  550. );
  551. m_default += temp;
  552. }
  553. void writef(const char* _format, ...)
  554. {
  555. va_list argList;
  556. va_start(argList, _format);
  557. bx::stringPrintfVargs(m_default, _format, argList);
  558. va_end(argList);
  559. }
  560. void addInclude(const char* _includeDir)
  561. {
  562. char* start = scratch(_includeDir);
  563. for (bx::StringView split = bx::strFind(start, ';')
  564. ; !split.isEmpty()
  565. ; split = bx::strFind(start, ';')
  566. )
  567. {
  568. *const_cast<char*>(split.getPtr() ) = '\0';
  569. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  570. m_tagptr->data = start;
  571. m_tagptr++;
  572. start = const_cast<char*>(split.getPtr() ) + 1;
  573. }
  574. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  575. m_tagptr->data = start;
  576. m_tagptr++;
  577. }
  578. void addDependency(const char* _fileName)
  579. {
  580. m_depends += " \\\n ";
  581. m_depends += _fileName;
  582. }
  583. bool run(const char* _input)
  584. {
  585. m_fgetsPos = 0;
  586. m_preprocessed.clear();
  587. m_input = m_default;
  588. m_input += "\n\n";
  589. int32_t len = bx::strLen(_input)+1;
  590. char* temp = new char[len];
  591. bx::StringView normalized = bx::normalizeEolLf(temp, len, _input);
  592. std::string str;
  593. str.assign(normalized.getPtr(), normalized.getTerm() );
  594. m_input += str;
  595. delete [] temp;
  596. fppTag* tagptr = m_tagptr;
  597. tagptr->tag = FPPTAG_END;
  598. tagptr->data = 0;
  599. tagptr++;
  600. int result = fppPreProcess(m_tags);
  601. return 0 == result;
  602. }
  603. char* fgets(char* _buffer, int _size)
  604. {
  605. int ii = 0;
  606. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  607. {
  608. _buffer[ii++] = ch;
  609. if (ch == '\n' || ii == _size)
  610. {
  611. _buffer[ii] = '\0';
  612. m_fgetsPos++;
  613. return _buffer;
  614. }
  615. }
  616. return NULL;
  617. }
  618. static void fppDepends(char* _fileName, void* _userData)
  619. {
  620. Preprocessor* thisClass = (Preprocessor*)_userData;
  621. thisClass->addDependency(_fileName);
  622. }
  623. static char* fppInput(char* _buffer, int _size, void* _userData)
  624. {
  625. Preprocessor* thisClass = (Preprocessor*)_userData;
  626. return thisClass->fgets(_buffer, _size);
  627. }
  628. static void fppOutput(int _ch, void* _userData)
  629. {
  630. Preprocessor* thisClass = (Preprocessor*)_userData;
  631. thisClass->m_preprocessed += char(_ch);
  632. }
  633. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  634. {
  635. bx::vprintf(_format, _vargs);
  636. }
  637. char* scratch(const char* _str)
  638. {
  639. char* result = &m_scratch[m_scratchPos];
  640. bx::strCopy(result, uint32_t(sizeof(m_scratch)-m_scratchPos), _str);
  641. m_scratchPos += (uint32_t)bx::strLen(_str)+1;
  642. return result;
  643. }
  644. fppTag m_tags[MAX_TAGS];
  645. fppTag* m_tagptr;
  646. std::string m_depends;
  647. std::string m_default;
  648. std::string m_input;
  649. std::string m_preprocessed;
  650. char m_scratch[16<<10];
  651. uint32_t m_scratchPos;
  652. uint32_t m_fgetsPos;
  653. };
  654. typedef std::vector<std::string> InOut;
  655. uint32_t parseInOut(InOut& _inout, const bx::StringView& _str)
  656. {
  657. uint32_t hash = 0;
  658. bx::StringView str = bx::strLTrimSpace(_str);
  659. if (!str.isEmpty() )
  660. {
  661. bx::StringView delim;
  662. do
  663. {
  664. delim = bx::strFind(str, ',');
  665. if (delim.isEmpty() )
  666. {
  667. delim = bx::strFind(str, ' ');
  668. }
  669. const bx::StringView token(bx::strRTrim(bx::StringView(str.getPtr(), delim.getPtr() ), " ") );
  670. if (!token.isEmpty() )
  671. {
  672. _inout.push_back(std::string(token.getPtr(), token.getTerm() ) );
  673. str = bx::strLTrimSpace(bx::StringView(delim.getPtr() + 1, str.getTerm() ) );
  674. }
  675. }
  676. while (!delim.isEmpty() );
  677. std::sort(_inout.begin(), _inout.end() );
  678. bx::HashMurmur2A murmur;
  679. murmur.begin();
  680. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  681. {
  682. murmur.add(it->c_str(), (uint32_t)it->size() );
  683. }
  684. hash = murmur.end();
  685. }
  686. return hash;
  687. }
  688. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  689. {
  690. char find[32];
  691. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  692. char replace[32];
  693. bx::snprintf(replace, sizeof(replace), "bgfx_FragData%d", _idx);
  694. strReplace(_data, find, replace);
  695. _preprocessor.writef(
  696. " \\\n\t%sout vec4 bgfx_FragData%d : SV_TARGET%d"
  697. , _comma ? ", " : " "
  698. , _idx
  699. , _idx
  700. );
  701. }
  702. void voidFragData(char* _data, uint32_t _idx)
  703. {
  704. char find[32];
  705. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  706. strReplace(_data, find, "bgfx_VoidFrag");
  707. }
  708. bx::StringView baseName(const bx::StringView& _filePath)
  709. {
  710. bx::FilePath fp(_filePath);
  711. return bx::strFind(_filePath, fp.getBaseName() );
  712. }
  713. // c - compute
  714. // d - domain
  715. // f - fragment
  716. // g - geometry
  717. // h - hull
  718. // v - vertex
  719. //
  720. // OpenGL #version Features Direct3D Features Shader Model
  721. // 2.1 120 vf 9.0 vf 2.0
  722. // 3.0 130
  723. // 3.1 140
  724. // 3.2 150 vgf
  725. // 3.3 330 10.0 vgf 4.0
  726. // 4.0 400 vhdgf
  727. // 4.1 410
  728. // 4.2 420 11.0 vhdgf+c 5.0
  729. // 4.3 430 vhdgf+c
  730. // 4.4 440
  731. void help(const char* _error = NULL)
  732. {
  733. if (NULL != _error)
  734. {
  735. bx::printf("Error:\n%s\n\n", _error);
  736. }
  737. bx::printf(
  738. "shaderc, bgfx shader compiler tool, version %d.%d.%d.\n"
  739. "Copyright 2011-2019 Branimir Karadzic. All rights reserved.\n"
  740. "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n\n"
  741. , BGFX_SHADERC_VERSION_MAJOR
  742. , BGFX_SHADERC_VERSION_MINOR
  743. , BGFX_API_VERSION
  744. );
  745. bx::printf(
  746. "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  747. "\n"
  748. "Options:\n"
  749. " -h, --help Help.\n"
  750. " -v, --version Version information only.\n"
  751. " -f <file path> Input file path.\n"
  752. " -i <include path> Include path (for multiple paths use -i multiple times).\n"
  753. " -o <file path> Output file path.\n"
  754. " --bin2c [array name] Generate C header file. If array name is not specified base file name will be used as name.\n"
  755. " --depends Generate makefile style depends file.\n"
  756. " --platform <platform> Target platform.\n"
  757. " android\n"
  758. " asm.js\n"
  759. " ios\n"
  760. " linux\n"
  761. " orbis\n"
  762. " osx\n"
  763. " windows\n"
  764. " -p, --profile <profile> Shader model (default GLSL).\n"
  765. " s_3\n"
  766. " s_4\n"
  767. " s_4_0_level\n"
  768. " s_5\n"
  769. " metal\n"
  770. " pssl\n"
  771. " spirv\n"
  772. " --preprocess Preprocess only.\n"
  773. " --define <defines> Add defines to preprocessor (semicolon separated).\n"
  774. " --raw Do not process shader. No preprocessor, and no glsl-optimizer (GLSL only).\n"
  775. " --type <type> Shader type (vertex, fragment)\n"
  776. " --varyingdef <file path> Path to varying.def.sc file.\n"
  777. " --verbose Verbose.\n"
  778. "\n"
  779. "Options (DX9 and DX11 only):\n"
  780. "\n"
  781. " --debug Debug information.\n"
  782. " --disasm Disassemble compiled shader.\n"
  783. " -O <level> Optimization level (0, 1, 2, 3).\n"
  784. " --Werror Treat warnings as errors.\n"
  785. "\n"
  786. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  787. );
  788. }
  789. bx::StringView nextWord(bx::StringView& _parse)
  790. {
  791. bx::StringView word = bx::strWord(bx::strLTrimSpace(_parse) );
  792. _parse = bx::strLTrimSpace(bx::StringView(word.getTerm(), _parse.getTerm() ) );
  793. return word;
  794. }
  795. bool compileShader(const char* _varying, const char* _comment, char* _shader, uint32_t _shaderLen, Options& _options, bx::FileWriter* _writer)
  796. {
  797. uint32_t glsl = 0;
  798. uint32_t essl = 0;
  799. uint32_t hlsl = 0;
  800. uint32_t d3d = 11;
  801. uint32_t metal = 0;
  802. uint32_t pssl = 0;
  803. uint32_t spirv = 0;
  804. const char* profile = _options.profile.c_str();
  805. if ('\0' != profile[0])
  806. {
  807. if (0 == bx::strCmp(&profile[1], "s_4_0_level", 11) )
  808. {
  809. hlsl = 2;
  810. }
  811. else if (0 == bx::strCmp(&profile[1], "s_3", 3) )
  812. {
  813. hlsl = 3;
  814. d3d = 9;
  815. }
  816. else if (0 == bx::strCmp(&profile[1], "s_4", 3) )
  817. {
  818. hlsl = 4;
  819. }
  820. else if (0 == bx::strCmp(&profile[1], "s_5", 3) )
  821. {
  822. hlsl = 5;
  823. }
  824. else if (0 == bx::strCmp(profile, "metal") )
  825. {
  826. metal = 1;
  827. }
  828. else if (0 == bx::strCmp(profile, "pssl") )
  829. {
  830. pssl = 1;
  831. }
  832. else if (0 == bx::strCmp(profile, "spirv") )
  833. {
  834. spirv = 1;
  835. }
  836. else
  837. {
  838. bx::fromString(&glsl, profile);
  839. }
  840. }
  841. else
  842. {
  843. essl = 2;
  844. }
  845. Preprocessor preprocessor(_options.inputFilePath.c_str(), 0 != essl);
  846. for (size_t ii = 0; ii < _options.includeDirs.size(); ++ii)
  847. {
  848. preprocessor.addInclude(_options.includeDirs[ii].c_str() );
  849. }
  850. for (size_t ii = 0; ii < _options.defines.size(); ++ii)
  851. {
  852. preprocessor.setDefine(_options.defines[ii].c_str() );
  853. }
  854. for (size_t ii = 0; ii < _options.dependencies.size(); ++ii)
  855. {
  856. preprocessor.addDependency(_options.dependencies[ii].c_str() );
  857. }
  858. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  859. preprocessor.setDefaultDefine("BX_PLATFORM_EMSCRIPTEN");
  860. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  861. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  862. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  863. preprocessor.setDefaultDefine("BX_PLATFORM_PS4");
  864. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  865. preprocessor.setDefaultDefine("BX_PLATFORM_XBOXONE");
  866. // preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_ESSL");
  867. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  868. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  869. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_METAL");
  870. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_PSSL");
  871. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_SPIRV");
  872. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_COMPUTE");
  873. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  874. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  875. char glslDefine[128];
  876. bx::snprintf(glslDefine, BX_COUNTOF(glslDefine)
  877. , "BGFX_SHADER_LANGUAGE_GLSL=%d"
  878. , essl ? 1 : glsl
  879. );
  880. const char* platform = _options.platform.c_str();
  881. if (0 == bx::strCmpI(platform, "android") )
  882. {
  883. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  884. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  885. }
  886. else if (0 == bx::strCmpI(platform, "asm.js") )
  887. {
  888. preprocessor.setDefine("BX_PLATFORM_EMSCRIPTEN=1");
  889. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  890. }
  891. else if (0 == bx::strCmpI(platform, "ios") )
  892. {
  893. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  894. if (metal)
  895. {
  896. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_METAL=1");
  897. }
  898. else
  899. {
  900. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  901. }
  902. }
  903. else if (0 == bx::strCmpI(platform, "linux") )
  904. {
  905. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  906. if (0 != spirv)
  907. {
  908. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_SPIRV=1");
  909. }
  910. else
  911. {
  912. preprocessor.setDefine(glslDefine);
  913. }
  914. }
  915. else if (0 == bx::strCmpI(platform, "osx") )
  916. {
  917. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  918. if (!metal)
  919. {
  920. preprocessor.setDefine(glslDefine);
  921. }
  922. char temp[256];
  923. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_METAL=%d", metal);
  924. preprocessor.setDefine(temp);
  925. }
  926. else if (0 == bx::strCmpI(platform, "windows") )
  927. {
  928. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  929. char temp[256];
  930. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  931. preprocessor.setDefine(temp);
  932. }
  933. else if (0 == bx::strCmpI(platform, "orbis") )
  934. {
  935. preprocessor.setDefine("BX_PLATFORM_PS4=1");
  936. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_PSSL=1");
  937. preprocessor.setDefine("lit=lit_reserved");
  938. }
  939. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  940. switch (_options.shaderType)
  941. {
  942. case 'c':
  943. preprocessor.setDefine("BGFX_SHADER_TYPE_COMPUTE=1");
  944. break;
  945. case 'f':
  946. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  947. break;
  948. case 'v':
  949. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  950. break;
  951. default:
  952. bx::printf("Unknown type: %c?!", _options.shaderType);
  953. return false;
  954. }
  955. bool compiled = false;
  956. VaryingMap varyingMap;
  957. bx::StringView parse(_varying);
  958. bx::StringView term(parse);
  959. bool usesInterpolationQualifiers = false;
  960. while (!parse.isEmpty() )
  961. {
  962. parse = bx::strLTrimSpace(parse);
  963. bx::StringView eol = bx::strFind(parse, ';');
  964. if (eol.isEmpty() )
  965. {
  966. eol = bx::strFindEol(parse);
  967. }
  968. if (!eol.isEmpty() )
  969. {
  970. eol.set(eol.getPtr() + 1, parse.getTerm() );
  971. bx::StringView precision;
  972. bx::StringView interpolation;
  973. bx::StringView typen = nextWord(parse);
  974. if (0 == bx::strCmp(typen, "lowp", 4)
  975. || 0 == bx::strCmp(typen, "mediump", 7)
  976. || 0 == bx::strCmp(typen, "highp", 5) )
  977. {
  978. precision = typen;
  979. typen = nextWord(parse);
  980. }
  981. if (0 == bx::strCmp(typen, "flat", 4)
  982. || 0 == bx::strCmp(typen, "smooth", 6)
  983. || 0 == bx::strCmp(typen, "noperspective", 13)
  984. || 0 == bx::strCmp(typen, "centroid", 8) )
  985. {
  986. if ('f' == _options.shaderType
  987. || 0 != glsl
  988. || 0 != essl)
  989. {
  990. interpolation = typen;
  991. usesInterpolationQualifiers = true;
  992. }
  993. typen = nextWord(parse);
  994. }
  995. bx::StringView name = nextWord(parse);
  996. bx::StringView column = bx::strSubstr(parse, 0, 1);
  997. bx::StringView semantics;
  998. if (0 == bx::strCmp(column, ":", 1) )
  999. {
  1000. parse = bx::strLTrimSpace(bx::StringView(parse.getPtr() + 1, parse.getTerm() ) );
  1001. semantics = nextWord(parse);
  1002. }
  1003. bx::StringView assign = bx::strSubstr(parse, 0, 1);
  1004. bx::StringView init;
  1005. if (0 == bx::strCmp(assign, "=", 1))
  1006. {
  1007. parse = bx::strLTrimSpace(bx::StringView(parse.getPtr() + 1, parse.getTerm() ) );
  1008. init.set(parse.getPtr(), eol.getPtr() );
  1009. }
  1010. if (!typen.isEmpty()
  1011. && !name.isEmpty()
  1012. && !semantics.isEmpty() )
  1013. {
  1014. Varying var;
  1015. if (!precision.isEmpty() )
  1016. {
  1017. var.m_precision.assign(precision.getPtr(), precision.getTerm() );
  1018. }
  1019. if (!interpolation.isEmpty() )
  1020. {
  1021. var.m_interpolation.assign(interpolation.getPtr(), interpolation.getTerm() );
  1022. }
  1023. var.m_type.assign(typen.getPtr(), typen.getTerm() );
  1024. var.m_name.assign(name.getPtr(), name.getTerm() );
  1025. var.m_semantics.assign(semantics.getPtr(), semantics.getTerm() );
  1026. if (d3d == 9
  1027. && var.m_semantics == "BITANGENT")
  1028. {
  1029. var.m_semantics = "BINORMAL";
  1030. }
  1031. if (!init.isEmpty() )
  1032. {
  1033. var.m_init.assign(init.getPtr(), init.getTerm() );
  1034. }
  1035. varyingMap.insert(std::make_pair(var.m_name, var) );
  1036. }
  1037. parse = bx::strLTrimSpace(bx::strFindNl(bx::StringView(eol.getPtr(), term.getTerm() ) ) );
  1038. }
  1039. }
  1040. bool raw = _options.raw;
  1041. InOut shaderInputs;
  1042. InOut shaderOutputs;
  1043. uint32_t inputHash = 0;
  1044. uint32_t outputHash = 0;
  1045. char* data;
  1046. char* input;
  1047. {
  1048. data = _shader;
  1049. uint32_t size = _shaderLen;
  1050. const size_t padding = 16384;
  1051. if (!raw)
  1052. {
  1053. // To avoid commented code being recognized as used feature,
  1054. // first preprocess pass is used to strip all comments before
  1055. // substituting code.
  1056. bool ok = preprocessor.run(data);
  1057. delete [] data;
  1058. if (!ok)
  1059. {
  1060. return false;
  1061. }
  1062. size = (uint32_t)preprocessor.m_preprocessed.size();
  1063. data = new char[size+padding+1];
  1064. bx::memCopy(data, preprocessor.m_preprocessed.c_str(), size);
  1065. bx::memSet(&data[size], 0, padding+1);
  1066. }
  1067. strNormalizeEol(data);
  1068. input = const_cast<char*>(bx::strLTrimSpace(data).getPtr() );
  1069. while (input[0] == '$')
  1070. {
  1071. bx::StringView str = bx::strLTrimSpace(input+1);
  1072. bx::StringView eol = bx::strFindEol(str);
  1073. bx::StringView nl = bx::strFindNl(eol);
  1074. input = const_cast<char*>(nl.getPtr() );
  1075. if (0 == bx::strCmp(str, "input", 5) )
  1076. {
  1077. str = bx::StringView(str.getPtr() + 5, str.getTerm() );
  1078. bx::StringView comment = bx::strFind(str, "//");
  1079. eol = !comment.isEmpty() && comment.getPtr() < eol.getPtr() ? comment.getPtr() : eol;
  1080. inputHash = parseInOut(shaderInputs, bx::StringView(str.getPtr(), eol.getPtr() ) );
  1081. }
  1082. else if (0 == bx::strCmp(str, "output", 6) )
  1083. {
  1084. str = bx::StringView(str.getPtr() + 6, str.getTerm() );
  1085. bx::StringView comment = bx::strFind(str, "//");
  1086. eol = !comment.isEmpty() && comment.getPtr() < eol.getPtr() ? comment.getPtr() : eol;
  1087. outputHash = parseInOut(shaderOutputs, bx::StringView(str.getPtr(), eol.getPtr() ) );
  1088. }
  1089. else if (0 == bx::strCmp(str, "raw", 3) )
  1090. {
  1091. raw = true;
  1092. str = bx::StringView(str.getPtr() + 3, str.getTerm() );
  1093. }
  1094. input = const_cast<char*>(bx::strLTrimSpace(input).getPtr() );
  1095. }
  1096. }
  1097. bool invalidShaderAttribute = false;
  1098. if ('v' == _options.shaderType)
  1099. {
  1100. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1101. {
  1102. if (bx::findIdentifierMatch(it->c_str(), s_allowedVertexShaderInputs).isEmpty() )
  1103. {
  1104. invalidShaderAttribute = true;
  1105. bx::printf(
  1106. "Invalid vertex shader input attribute '%s'.\n"
  1107. "\n"
  1108. "Valid input attributes:\n"
  1109. " a_position, a_normal, a_tangent, a_bitangent, a_color0, a_color1, a_color2, a_color3, a_indices, a_weight,\n"
  1110. " a_texcoord0, a_texcoord1, a_texcoord2, a_texcoord3, a_texcoord4, a_texcoord5, a_texcoord6, a_texcoord7,\n"
  1111. " i_data0, i_data1, i_data2, i_data3, i_data4.\n"
  1112. "\n"
  1113. , it->c_str() );
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. if (invalidShaderAttribute)
  1119. {
  1120. }
  1121. else if (raw)
  1122. {
  1123. if ('f' == _options.shaderType)
  1124. {
  1125. bx::write(_writer, BGFX_CHUNK_MAGIC_FSH);
  1126. bx::write(_writer, inputHash);
  1127. bx::write(_writer, uint32_t(0) );
  1128. }
  1129. else if ('v' == _options.shaderType)
  1130. {
  1131. bx::write(_writer, BGFX_CHUNK_MAGIC_VSH);
  1132. bx::write(_writer, uint32_t(0) );
  1133. bx::write(_writer, outputHash);
  1134. }
  1135. else
  1136. {
  1137. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1138. bx::write(_writer, uint32_t(0) );
  1139. bx::write(_writer, outputHash);
  1140. }
  1141. if (0 != glsl)
  1142. {
  1143. bx::write(_writer, uint16_t(0) );
  1144. uint32_t shaderSize = (uint32_t)bx::strLen(input);
  1145. bx::write(_writer, shaderSize);
  1146. bx::write(_writer, input, shaderSize);
  1147. bx::write(_writer, uint8_t(0) );
  1148. compiled = true;
  1149. }
  1150. else if (0 != pssl)
  1151. {
  1152. compiled = compilePSSLShader(_options, 0, input, _writer);
  1153. }
  1154. else
  1155. {
  1156. compiled = compileHLSLShader(_options, d3d, input, _writer);
  1157. }
  1158. }
  1159. else if ('c' == _options.shaderType) // Compute
  1160. {
  1161. bx::StringView entry = bx::strFind(input, "void main()");
  1162. if (entry.isEmpty() )
  1163. {
  1164. bx::printf("Shader entry point 'void main()' is not found.\n");
  1165. }
  1166. else
  1167. {
  1168. if (0 != glsl
  1169. || 0 != essl)
  1170. {
  1171. }
  1172. else
  1173. {
  1174. if (0 != pssl)
  1175. {
  1176. preprocessor.writef(getPsslPreamble() );
  1177. }
  1178. preprocessor.writef(
  1179. "#define lowp\n"
  1180. "#define mediump\n"
  1181. "#define highp\n"
  1182. "#define ivec2 int2\n"
  1183. "#define ivec3 int3\n"
  1184. "#define ivec4 int4\n"
  1185. "#define uvec2 uint2\n"
  1186. "#define uvec3 uint3\n"
  1187. "#define uvec4 uint4\n"
  1188. "#define vec2 float2\n"
  1189. "#define vec3 float3\n"
  1190. "#define vec4 float4\n"
  1191. "#define mat2 float2x2\n"
  1192. "#define mat3 float3x3\n"
  1193. "#define mat4 float4x4\n"
  1194. );
  1195. *const_cast<char*>(entry.getPtr() + 4) = '_';
  1196. preprocessor.writef("#define void_main()");
  1197. preprocessor.writef(" \\\n\tvoid main(");
  1198. uint32_t arg = 0;
  1199. const bool hasLocalInvocationID = !bx::strFind(input, "gl_LocalInvocationID").isEmpty();
  1200. const bool hasLocalInvocationIndex = !bx::strFind(input, "gl_LocalInvocationIndex").isEmpty();
  1201. const bool hasGlobalInvocationID = !bx::strFind(input, "gl_GlobalInvocationID").isEmpty();
  1202. const bool hasWorkGroupID = !bx::strFind(input, "gl_WorkGroupID").isEmpty();
  1203. if (hasLocalInvocationID)
  1204. {
  1205. preprocessor.writef(
  1206. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1207. , arg++ > 0 ? ", " : " "
  1208. );
  1209. }
  1210. if (hasLocalInvocationIndex)
  1211. {
  1212. preprocessor.writef(
  1213. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1214. , arg++ > 0 ? ", " : " "
  1215. );
  1216. }
  1217. if (hasGlobalInvocationID)
  1218. {
  1219. preprocessor.writef(
  1220. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1221. , arg++ > 0 ? ", " : " "
  1222. );
  1223. }
  1224. if (hasWorkGroupID)
  1225. {
  1226. preprocessor.writef(
  1227. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1228. , arg++ > 0 ? ", " : " "
  1229. );
  1230. }
  1231. preprocessor.writef(
  1232. " \\\n\t)\n"
  1233. );
  1234. }
  1235. if (preprocessor.run(input) )
  1236. {
  1237. if (_options.preprocessOnly)
  1238. {
  1239. bx::write(_writer, preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1240. return true;
  1241. }
  1242. {
  1243. std::string code;
  1244. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1245. bx::write(_writer, uint32_t(0) );
  1246. bx::write(_writer, outputHash);
  1247. if (0 != glsl
  1248. || 0 != essl)
  1249. {
  1250. if (essl)
  1251. {
  1252. bx::stringPrintf(code, "#version 310 es\n");
  1253. }
  1254. else
  1255. {
  1256. bx::stringPrintf(code, "#version %d\n", glsl == 0 ? 430 : glsl);
  1257. }
  1258. #if 1
  1259. code += preprocessor.m_preprocessed;
  1260. bx::write(_writer, uint16_t(0) );
  1261. uint32_t shaderSize = (uint32_t)code.size();
  1262. bx::write(_writer, shaderSize);
  1263. bx::write(_writer, code.c_str(), shaderSize);
  1264. bx::write(_writer, uint8_t(0) );
  1265. compiled = true;
  1266. #else
  1267. code += _comment;
  1268. code += preprocessor.m_preprocessed;
  1269. compiled = compileGLSLShader(cmdLine, essl, code, writer);
  1270. #endif // 0
  1271. }
  1272. else
  1273. {
  1274. code += _comment;
  1275. code += preprocessor.m_preprocessed;
  1276. if (0 != metal)
  1277. {
  1278. compiled = compileMetalShader(_options, BX_MAKEFOURCC('M', 'T', 'L', 0), code, _writer);
  1279. }
  1280. else if (0 != spirv)
  1281. {
  1282. compiled = compileSPIRVShader(_options, 0, code, _writer);
  1283. }
  1284. else if (0 != pssl)
  1285. {
  1286. compiled = compilePSSLShader(_options, 0, code, _writer);
  1287. }
  1288. else
  1289. {
  1290. compiled = compileHLSLShader(_options, d3d, code, _writer);
  1291. }
  1292. }
  1293. }
  1294. if (compiled)
  1295. {
  1296. if (_options.depends)
  1297. {
  1298. std::string ofp = _options.outputFilePath;
  1299. ofp += ".d";
  1300. bx::FileWriter writer;
  1301. if (bx::open(&writer, ofp.c_str() ) )
  1302. {
  1303. writef(&writer, "%s : %s\n", _options.outputFilePath.c_str(), preprocessor.m_depends.c_str() );
  1304. bx::close(&writer);
  1305. }
  1306. }
  1307. }
  1308. }
  1309. }
  1310. }
  1311. else // Vertex/Fragment
  1312. {
  1313. bx::StringView shader(input);
  1314. bx::StringView entry = bx::strFind(shader, "void main()");
  1315. if (entry.isEmpty() )
  1316. {
  1317. bx::printf("Shader entry point 'void main()' is not found.\n");
  1318. }
  1319. else
  1320. {
  1321. if (0 != glsl
  1322. || 0 != essl)
  1323. {
  1324. if (0 == essl)
  1325. {
  1326. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1327. // not as GLSL language 1.2 specs shadow2D/Proj.
  1328. preprocessor.writef(
  1329. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1330. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1331. );
  1332. }
  1333. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1334. {
  1335. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1336. if (varyingIt != varyingMap.end() )
  1337. {
  1338. const Varying& var = varyingIt->second;
  1339. const char* name = var.m_name.c_str();
  1340. if (0 == bx::strCmp(name, "a_", 2)
  1341. || 0 == bx::strCmp(name, "i_", 2) )
  1342. {
  1343. preprocessor.writef(
  1344. "attribute %s %s %s %s;\n"
  1345. , var.m_precision.c_str()
  1346. , var.m_interpolation.c_str()
  1347. , var.m_type.c_str()
  1348. , name
  1349. );
  1350. }
  1351. else
  1352. {
  1353. preprocessor.writef(
  1354. "%s varying %s %s %s;\n"
  1355. , var.m_interpolation.c_str()
  1356. , var.m_precision.c_str()
  1357. , var.m_type.c_str()
  1358. , name
  1359. );
  1360. }
  1361. }
  1362. }
  1363. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1364. {
  1365. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1366. if (varyingIt != varyingMap.end() )
  1367. {
  1368. const Varying& var = varyingIt->second;
  1369. preprocessor.writef("%s varying %s %s;\n"
  1370. , var.m_interpolation.c_str()
  1371. , var.m_type.c_str()
  1372. , var.m_name.c_str()
  1373. );
  1374. }
  1375. }
  1376. }
  1377. else
  1378. {
  1379. if (0 != pssl)
  1380. {
  1381. preprocessor.writef(getPsslPreamble() );
  1382. }
  1383. preprocessor.writef(
  1384. "#define lowp\n"
  1385. "#define mediump\n"
  1386. "#define highp\n"
  1387. "#define ivec2 int2\n"
  1388. "#define ivec3 int3\n"
  1389. "#define ivec4 int4\n"
  1390. "#define uvec2 uint2\n"
  1391. "#define uvec3 uint3\n"
  1392. "#define uvec4 uint4\n"
  1393. "#define vec2 float2\n"
  1394. "#define vec3 float3\n"
  1395. "#define vec4 float4\n"
  1396. "#define mat2 float2x2\n"
  1397. "#define mat3 float3x3\n"
  1398. "#define mat4 float4x4\n"
  1399. );
  1400. if (hlsl != 0
  1401. && hlsl < 4)
  1402. {
  1403. preprocessor.writef(
  1404. "#define centroid\n"
  1405. "#define flat\n"
  1406. "#define noperspective\n"
  1407. "#define smooth\n"
  1408. );
  1409. }
  1410. *const_cast<char*>(entry.getPtr() + 4) = '_';
  1411. if ('f' == _options.shaderType)
  1412. {
  1413. bx::StringView insert = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1414. if (!insert.isEmpty() )
  1415. {
  1416. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\nvec4 bgfx_VoidFrag = vec4_splat(0.0);\n");
  1417. }
  1418. const bool hasFragColor = !bx::strFind(input, "gl_FragColor").isEmpty();
  1419. const bool hasFragCoord = !bx::strFind(input, "gl_FragCoord").isEmpty() || hlsl > 3 || hlsl == 2;
  1420. const bool hasFragDepth = !bx::strFind(input, "gl_FragDepth").isEmpty();
  1421. const bool hasFrontFacing = !bx::strFind(input, "gl_FrontFacing").isEmpty();
  1422. const bool hasPrimitiveId = !bx::strFind(input, "gl_PrimitiveID").isEmpty();
  1423. bool hasFragData[8] = {};
  1424. uint32_t numFragData = 0;
  1425. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1426. {
  1427. char temp[32];
  1428. bx::snprintf(temp, BX_COUNTOF(temp), "gl_FragData[%d]", ii);
  1429. hasFragData[ii] = !bx::strFind(input, temp).isEmpty();
  1430. numFragData += hasFragData[ii];
  1431. }
  1432. if (0 == numFragData)
  1433. {
  1434. // GL errors when both gl_FragColor and gl_FragData is used.
  1435. // This will trigger the same error with HLSL compiler too.
  1436. preprocessor.writef("#define gl_FragColor bgfx_FragData0\n");
  1437. // If it has gl_FragData or gl_FragColor, color target at
  1438. // index 0 exists, otherwise shader is not modifying color
  1439. // targets.
  1440. hasFragData[0] |= hasFragColor || d3d < 11;
  1441. if (!insert.isEmpty()
  1442. && d3d < 11
  1443. && !hasFragColor)
  1444. {
  1445. insert = strInsert(const_cast<char*>(insert.getPtr()+1), "\ngl_FragColor = bgfx_VoidFrag;\n");
  1446. }
  1447. }
  1448. preprocessor.writef("#define void_main()");
  1449. preprocessor.writef(" \\\n\tvoid main(");
  1450. uint32_t arg = 0;
  1451. if (hasFragCoord)
  1452. {
  1453. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  1454. ++arg;
  1455. }
  1456. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1457. {
  1458. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1459. if (varyingIt != varyingMap.end() )
  1460. {
  1461. const Varying& var = varyingIt->second;
  1462. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  1463. , arg++ > 0 ? ", " : " "
  1464. , interpolationDx11(var.m_interpolation.c_str() )
  1465. , var.m_type.c_str()
  1466. , var.m_name.c_str()
  1467. , var.m_semantics.c_str()
  1468. );
  1469. }
  1470. }
  1471. const uint32_t maxRT = d3d > 9 ? BX_COUNTOF(hasFragData) : 4;
  1472. for (uint32_t ii = 0; ii < BX_COUNTOF(hasFragData); ++ii)
  1473. {
  1474. if (ii < maxRT)
  1475. {
  1476. if (hasFragData[ii])
  1477. {
  1478. addFragData(preprocessor, input, ii, arg++ > 0);
  1479. }
  1480. }
  1481. else
  1482. {
  1483. voidFragData(input, ii);
  1484. }
  1485. }
  1486. if (hasFragDepth)
  1487. {
  1488. preprocessor.writef(
  1489. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  1490. , arg++ > 0 ? ", " : " "
  1491. );
  1492. }
  1493. if (hasFrontFacing)
  1494. {
  1495. if (hlsl == 3)
  1496. {
  1497. preprocessor.writef(
  1498. " \\\n\t%sfloat __vface : VFACE"
  1499. , arg++ > 0 ? ", " : " "
  1500. );
  1501. }
  1502. else
  1503. {
  1504. preprocessor.writef(
  1505. " \\\n\t%sbool gl_FrontFacing : SV_IsFrontFace"
  1506. , arg++ > 0 ? ", " : " "
  1507. );
  1508. }
  1509. }
  1510. if (hasPrimitiveId)
  1511. {
  1512. if (hlsl > 3)
  1513. {
  1514. preprocessor.writef(
  1515. " \\\n\t%suint gl_PrimitiveID : SV_PrimitiveID"
  1516. , arg++ > 0 ? ", " : " "
  1517. );
  1518. }
  1519. else
  1520. {
  1521. bx::printf("gl_PrimitiveID builtin is not supported by this D3D9 HLSL.\n");
  1522. return false;
  1523. }
  1524. }
  1525. preprocessor.writef(
  1526. " \\\n\t)\n"
  1527. );
  1528. if (hasFrontFacing)
  1529. {
  1530. if (hlsl == 3)
  1531. {
  1532. preprocessor.writef(
  1533. "#define gl_FrontFacing (__vface >= 0.0)\n"
  1534. );
  1535. }
  1536. }
  1537. }
  1538. else if ('v' == _options.shaderType)
  1539. {
  1540. const bool hasVertexId = !bx::strFind(input, "gl_VertexID").isEmpty();
  1541. const bool hasInstanceId = !bx::strFind(input, "gl_InstanceID").isEmpty();
  1542. bx::StringView brace = bx::strFind(bx::StringView(entry.getPtr(), shader.getTerm() ), "{");
  1543. if (!brace.isEmpty() )
  1544. {
  1545. bx::StringView block = bx::strFindBlock(bx::StringView(brace.getPtr(), shader.getTerm() ), '{', '}');
  1546. if (!block.isEmpty() )
  1547. {
  1548. strInsert(const_cast<char*>(block.getTerm()-1), "__RETURN__;\n");
  1549. }
  1550. }
  1551. preprocessor.writef(
  1552. "struct Output\n"
  1553. "{\n"
  1554. "\tvec4 gl_Position : SV_POSITION;\n"
  1555. "#define gl_Position _varying_.gl_Position\n"
  1556. );
  1557. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1558. {
  1559. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1560. if (varyingIt != varyingMap.end() )
  1561. {
  1562. const Varying& var = varyingIt->second;
  1563. preprocessor.writef(
  1564. "\t%s %s %s : %s;\n"
  1565. , interpolationDx11(var.m_interpolation.c_str() )
  1566. , var.m_type.c_str()
  1567. , var.m_name.c_str()
  1568. , var.m_semantics.c_str()
  1569. );
  1570. preprocessor.writef(
  1571. "#define %s _varying_.%s\n"
  1572. , var.m_name.c_str()
  1573. , var.m_name.c_str()
  1574. );
  1575. }
  1576. }
  1577. preprocessor.writef(
  1578. "};\n"
  1579. );
  1580. preprocessor.writef("#define void_main() \\\n");
  1581. preprocessor.writef("Output main(");
  1582. uint32_t arg = 0;
  1583. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1584. {
  1585. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1586. if (varyingIt != varyingMap.end() )
  1587. {
  1588. const Varying& var = varyingIt->second;
  1589. preprocessor.writef(
  1590. " \\\n\t%s%s %s : %s"
  1591. , arg++ > 0 ? ", " : ""
  1592. , var.m_type.c_str()
  1593. , var.m_name.c_str()
  1594. , var.m_semantics.c_str()
  1595. );
  1596. }
  1597. }
  1598. if (hasVertexId)
  1599. {
  1600. if (d3d > 9)
  1601. {
  1602. preprocessor.writef(
  1603. " \\\n\t%suint gl_VertexID : SV_VertexID"
  1604. , arg++ > 0 ? ", " : " "
  1605. );
  1606. }
  1607. else
  1608. {
  1609. bx::printf("gl_VertexID builtin is not supported by this D3D9 HLSL.\n");
  1610. return false;
  1611. }
  1612. }
  1613. if (hasInstanceId)
  1614. {
  1615. if (d3d > 9)
  1616. {
  1617. preprocessor.writef(
  1618. " \\\n\t%suint gl_InstanceID : SV_InstanceID"
  1619. , arg++ > 0 ? ", " : " "
  1620. );
  1621. }
  1622. else
  1623. {
  1624. bx::printf("gl_InstanceID builtin is not supported by this D3D9 HLSL.\n");
  1625. return false;
  1626. }
  1627. }
  1628. preprocessor.writef(
  1629. ") \\\n"
  1630. "{ \\\n"
  1631. "\tOutput _varying_;"
  1632. );
  1633. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  1634. {
  1635. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1636. if (varyingIt != varyingMap.end() )
  1637. {
  1638. const Varying& var = varyingIt->second;
  1639. preprocessor.writef(" \\\n\t%s", var.m_name.c_str() );
  1640. if (!var.m_init.empty() )
  1641. {
  1642. preprocessor.writef(" = %s", var.m_init.c_str() );
  1643. }
  1644. preprocessor.writef(";");
  1645. }
  1646. }
  1647. preprocessor.writef(
  1648. "\n#define __RETURN__ \\\n"
  1649. "\t} \\\n"
  1650. );
  1651. if (hlsl != 0
  1652. && hlsl <= 3)
  1653. {
  1654. // preprocessor.writef(
  1655. // "\tgl_Position.xy += u_viewTexel.xy * gl_Position.w; \\\n"
  1656. // );
  1657. }
  1658. if (0 != spirv)
  1659. {
  1660. preprocessor.writef(
  1661. "\tgl_Position.y = -gl_Position.y; \\\n"
  1662. );
  1663. }
  1664. preprocessor.writef(
  1665. "\treturn _varying_"
  1666. );
  1667. }
  1668. }
  1669. if (preprocessor.run(input) )
  1670. {
  1671. //BX_TRACE("Input file: %s", filePath);
  1672. //BX_TRACE("Output file: %s", outFilePath);
  1673. if (_options.preprocessOnly)
  1674. {
  1675. if (0 != glsl)
  1676. {
  1677. if (essl != 0)
  1678. {
  1679. writef(_writer
  1680. , "#ifdef GL_ES\n"
  1681. "precision highp float;\n"
  1682. "#endif // GL_ES\n\n"
  1683. );
  1684. }
  1685. }
  1686. bx::write(_writer, preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1687. return true;
  1688. }
  1689. {
  1690. std::string code;
  1691. if ('f' == _options.shaderType)
  1692. {
  1693. bx::write(_writer, BGFX_CHUNK_MAGIC_FSH);
  1694. bx::write(_writer, inputHash);
  1695. bx::write(_writer, uint32_t(0) );
  1696. }
  1697. else if ('v' == _options.shaderType)
  1698. {
  1699. bx::write(_writer, BGFX_CHUNK_MAGIC_VSH);
  1700. bx::write(_writer, uint32_t(0) );
  1701. bx::write(_writer, outputHash);
  1702. }
  1703. else
  1704. {
  1705. bx::write(_writer, BGFX_CHUNK_MAGIC_CSH);
  1706. bx::write(_writer, uint32_t(0) );
  1707. bx::write(_writer, outputHash);
  1708. }
  1709. if (0 != glsl
  1710. || 0 != essl)
  1711. {
  1712. const bx::StringView preprocessedInput(preprocessor.m_preprocessed.c_str() );
  1713. if (!bx::strFind(preprocessedInput, "layout(std430").isEmpty()
  1714. || !bx::strFind(preprocessedInput, "image2D").isEmpty() )
  1715. {
  1716. glsl = 430;
  1717. }
  1718. if (glsl < 400)
  1719. {
  1720. const bool usesTextureLod = false
  1721. || !bx::findIdentifierMatch(input, s_ARB_shader_texture_lod).isEmpty()
  1722. || !bx::findIdentifierMatch(input, s_EXT_shader_texture_lod).isEmpty()
  1723. ;
  1724. const bool usesInstanceID = !bx::findIdentifierMatch(input, "gl_InstanceID").isEmpty();
  1725. const bool usesGpuShader4 = !bx::findIdentifierMatch(input, s_EXT_gpu_shader4).isEmpty();
  1726. const bool usesGpuShader5 = !bx::findIdentifierMatch(input, s_ARB_gpu_shader5).isEmpty();
  1727. const bool usesTexelFetch = !bx::findIdentifierMatch(input, s_texelFetch).isEmpty();
  1728. const bool usesTextureMS = !bx::findIdentifierMatch(input, s_ARB_texture_multisample).isEmpty();
  1729. const bool usesTextureArray = !bx::findIdentifierMatch(input, s_textureArray).isEmpty();
  1730. const bool usesPacking = !bx::findIdentifierMatch(input, s_ARB_shading_language_packing).isEmpty();
  1731. if (0 == essl)
  1732. {
  1733. const bool need130 = (120 == glsl && (false
  1734. || !bx::findIdentifierMatch(input, s_130).isEmpty()
  1735. || usesInterpolationQualifiers
  1736. || usesTexelFetch
  1737. ) );
  1738. bx::stringPrintf(code, "#version %s\n", need130 ? "130" : _options.profile.c_str());
  1739. glsl = 130;
  1740. if (need130)
  1741. {
  1742. bx::stringPrintf(code, "#define varying %s\n"
  1743. , 'f' == _options.shaderType ? "in" : "out"
  1744. );
  1745. }
  1746. if (usesInstanceID)
  1747. {
  1748. bx::stringPrintf(code
  1749. , "#extension GL_ARB_draw_instanced : enable\n"
  1750. );
  1751. }
  1752. if (usesGpuShader4)
  1753. {
  1754. bx::stringPrintf(code
  1755. , "#extension GL_EXT_gpu_shader4 : enable\n"
  1756. );
  1757. }
  1758. if (usesGpuShader5)
  1759. {
  1760. bx::stringPrintf(code
  1761. , "#extension GL_ARB_gpu_shader5 : enable\n"
  1762. );
  1763. }
  1764. if (usesPacking)
  1765. {
  1766. bx::stringPrintf(code
  1767. , "#extension GL_ARB_shading_language_packing : enable\n"
  1768. );
  1769. }
  1770. bool ARB_shader_texture_lod = false;
  1771. bool EXT_shader_texture_lod = false;
  1772. if (usesTextureLod)
  1773. {
  1774. if ('f' == _options.sha