shaderc.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753
  1. /*
  2. * Copyright 2011-2014 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/BSD-2-Clause
  4. */
  5. #define _BX_TRACE(_format, ...) \
  6. BX_MACRO_BLOCK_BEGIN \
  7. if (g_verbose) \
  8. { \
  9. fprintf(stderr, BX_FILE_LINE_LITERAL "" _format "\n", ##__VA_ARGS__); \
  10. } \
  11. BX_MACRO_BLOCK_END
  12. #define _BX_WARN(_condition, _format, ...) \
  13. BX_MACRO_BLOCK_BEGIN \
  14. if (!(_condition) ) \
  15. { \
  16. BX_TRACE("WARN " _format, ##__VA_ARGS__); \
  17. } \
  18. BX_MACRO_BLOCK_END
  19. #define _BX_CHECK(_condition, _format, ...) \
  20. BX_MACRO_BLOCK_BEGIN \
  21. if (!(_condition) ) \
  22. { \
  23. BX_TRACE("CHECK " _format, ##__VA_ARGS__); \
  24. bx::debugBreak(); \
  25. } \
  26. BX_MACRO_BLOCK_END
  27. #define BX_TRACE _BX_TRACE
  28. #define BX_WARN _BX_WARN
  29. #define BX_CHECK _BX_CHECK
  30. bool g_verbose = false;
  31. #include <bx/bx.h>
  32. #include <bx/debug.h>
  33. #define NOMINMAX
  34. #include <alloca.h>
  35. #include <stdio.h>
  36. #include <stdint.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <algorithm>
  40. #include <string>
  41. #include <vector>
  42. #include <unordered_map>
  43. #define MAX_TAGS 256
  44. extern "C"
  45. {
  46. #include <fpp.h>
  47. } // extern "C"
  48. #define BGFX_CHUNK_MAGIC_CSH BX_MAKEFOURCC('C', 'S', 'H', 0x0)
  49. #define BGFX_CHUNK_MAGIC_VSH BX_MAKEFOURCC('V', 'S', 'H', 0x2)
  50. #define BGFX_CHUNK_MAGIC_FSH BX_MAKEFOURCC('F', 'S', 'H', 0x2)
  51. #include <bx/commandline.h>
  52. #include <bx/endian.h>
  53. #include <bx/uint32_t.h>
  54. #include <bx/readerwriter.h>
  55. #include <bx/string.h>
  56. #include <bx/hash.h>
  57. #include "glsl_optimizer.h"
  58. #if BX_PLATFORM_WINDOWS
  59. # include <sal.h>
  60. # define __D3DX9MATH_INL__ // not used and MinGW complains about type-punning
  61. # include <d3dx9.h>
  62. # include <d3dcompiler.h>
  63. #endif // BX_PLATFORM_WINDOWS
  64. long int fsize(FILE* _file)
  65. {
  66. long int pos = ftell(_file);
  67. fseek(_file, 0L, SEEK_END);
  68. long int size = ftell(_file);
  69. fseek(_file, pos, SEEK_SET);
  70. return size;
  71. }
  72. struct Attrib
  73. {
  74. enum Enum
  75. {
  76. Position = 0,
  77. Normal,
  78. Tangent,
  79. Color0,
  80. Color1,
  81. Indices,
  82. Weight,
  83. TexCoord0,
  84. TexCoord1,
  85. TexCoord2,
  86. TexCoord3,
  87. TexCoord4,
  88. TexCoord5,
  89. TexCoord6,
  90. TexCoord7,
  91. Count,
  92. };
  93. };
  94. static const char* s_ARB_shader_texture_lod[] =
  95. {
  96. "texture2DLod",
  97. "texture2DProjLod",
  98. "texture3DLod",
  99. "texture3DProjLod",
  100. "textureCubeLod",
  101. "shadow2DLod",
  102. "shadow2DProjLod",
  103. NULL
  104. // "texture1DLod",
  105. // "texture1DProjLod",
  106. // "shadow1DLod",
  107. // "shadow1DProjLod",
  108. };
  109. static const char* s_EXT_shadow_samplers[] =
  110. {
  111. "shadow2D",
  112. "shadow2DProj",
  113. "sampler2DShadow",
  114. NULL
  115. };
  116. static const char* s_OES_standard_derivatives[] =
  117. {
  118. "dFdx",
  119. "dFdy",
  120. "fwidth",
  121. NULL
  122. };
  123. static const char* s_OES_texture_3D[] =
  124. {
  125. "texture3D",
  126. "texture3DProj",
  127. "texture3DLod",
  128. "texture3DProjLod",
  129. NULL
  130. };
  131. struct RemapInputSemantic
  132. {
  133. Attrib::Enum m_attr;
  134. const char* m_name;
  135. uint8_t m_index;
  136. };
  137. static const RemapInputSemantic s_remapInputSemantic[Attrib::Count+1] =
  138. {
  139. { Attrib::Position, "POSITION", 0 },
  140. { Attrib::Normal, "NORMAL", 0 },
  141. { Attrib::Tangent, "TANGENT", 0 },
  142. { Attrib::Color0, "COLOR", 0 },
  143. { Attrib::Color1, "COLOR", 1 },
  144. { Attrib::Indices, "BLENDINDICES", 0 },
  145. { Attrib::Weight, "BLENDWEIGHT", 0 },
  146. { Attrib::TexCoord0, "TEXCOORD", 0 },
  147. { Attrib::TexCoord1, "TEXCOORD", 1 },
  148. { Attrib::TexCoord2, "TEXCOORD", 2 },
  149. { Attrib::TexCoord3, "TEXCOORD", 3 },
  150. { Attrib::TexCoord4, "TEXCOORD", 4 },
  151. { Attrib::TexCoord5, "TEXCOORD", 5 },
  152. { Attrib::TexCoord6, "TEXCOORD", 6 },
  153. { Attrib::TexCoord7, "TEXCOORD", 7 },
  154. { Attrib::Count, "", 0 },
  155. };
  156. const RemapInputSemantic& findInputSemantic(const char* _name, uint8_t _index)
  157. {
  158. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  159. {
  160. const RemapInputSemantic& ris = s_remapInputSemantic[ii];
  161. if (0 == strcmp(ris.m_name, _name)
  162. && ris.m_index == _index)
  163. {
  164. return ris;
  165. }
  166. }
  167. return s_remapInputSemantic[Attrib::Count];
  168. }
  169. struct UniformType
  170. {
  171. enum Enum
  172. {
  173. Uniform1i,
  174. Uniform1f,
  175. End,
  176. Uniform1iv,
  177. Uniform1fv,
  178. Uniform2fv,
  179. Uniform3fv,
  180. Uniform4fv,
  181. Uniform3x3fv,
  182. Uniform4x4fv,
  183. Count
  184. };
  185. };
  186. #define BGFX_UNIFORM_FRAGMENTBIT UINT8_C(0x10)
  187. const char* s_uniformTypeName[UniformType::Count] =
  188. {
  189. "int",
  190. "float",
  191. NULL,
  192. "int",
  193. "float",
  194. "vec2",
  195. "vec3",
  196. "vec4",
  197. "mat3",
  198. "mat4",
  199. };
  200. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  201. {
  202. for (uint32_t ii = 0; ii < UniformType::Count; ++ii)
  203. {
  204. if (NULL != s_uniformTypeName[ii]
  205. && 0 == strcmp(_name, s_uniformTypeName[ii]) )
  206. {
  207. return UniformType::Enum(ii);
  208. }
  209. }
  210. return UniformType::Count;
  211. }
  212. struct Uniform
  213. {
  214. std::string name;
  215. UniformType::Enum type;
  216. uint8_t num;
  217. uint16_t regIndex;
  218. uint16_t regCount;
  219. };
  220. typedef std::vector<Uniform> UniformArray;
  221. const char* interpolationDx11(const char* _glsl)
  222. {
  223. if (0 == strcmp(_glsl, "smooth") )
  224. {
  225. return "linear";
  226. }
  227. else if (0 == strcmp(_glsl, "flat") )
  228. {
  229. return "nointerpolation";
  230. }
  231. return _glsl; // noperspective
  232. }
  233. #if BX_PLATFORM_WINDOWS
  234. struct UniformRemapDx9
  235. {
  236. UniformType::Enum id;
  237. D3DXPARAMETER_CLASS paramClass;
  238. D3DXPARAMETER_TYPE paramType;
  239. uint8_t columns;
  240. uint8_t rows;
  241. };
  242. static const UniformRemapDx9 s_constRemapDx9[7] =
  243. {
  244. { UniformType::Uniform1iv, D3DXPC_SCALAR, D3DXPT_INT, 0, 0 },
  245. { UniformType::Uniform1fv, D3DXPC_SCALAR, D3DXPT_FLOAT, 0, 0 },
  246. { UniformType::Uniform2fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
  247. { UniformType::Uniform3fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
  248. { UniformType::Uniform4fv, D3DXPC_VECTOR, D3DXPT_FLOAT, 0, 0 },
  249. { UniformType::Uniform3x3fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 3, 3 },
  250. { UniformType::Uniform4x4fv, D3DXPC_MATRIX_COLUMNS, D3DXPT_FLOAT, 4, 4 },
  251. };
  252. UniformType::Enum findUniformTypeDx9(const D3DXCONSTANT_DESC& constDesc)
  253. {
  254. for (uint32_t ii = 0; ii < BX_COUNTOF(s_constRemapDx9); ++ii)
  255. {
  256. const UniformRemapDx9& remap = s_constRemapDx9[ii];
  257. if (remap.paramClass == constDesc.Class
  258. && remap.paramType == constDesc.Type)
  259. {
  260. if (D3DXPC_MATRIX_COLUMNS != constDesc.Class)
  261. {
  262. return remap.id;
  263. }
  264. if (remap.columns == constDesc.Columns
  265. && remap.rows == constDesc.Rows)
  266. {
  267. return remap.id;
  268. }
  269. }
  270. }
  271. return UniformType::Count;
  272. }
  273. static uint32_t s_optimizationLevelDx9[4] =
  274. {
  275. D3DXSHADER_OPTIMIZATION_LEVEL0,
  276. D3DXSHADER_OPTIMIZATION_LEVEL1,
  277. D3DXSHADER_OPTIMIZATION_LEVEL2,
  278. D3DXSHADER_OPTIMIZATION_LEVEL3,
  279. };
  280. struct UniformRemapDx11
  281. {
  282. UniformType::Enum id;
  283. D3D_SHADER_VARIABLE_CLASS paramClass;
  284. D3D_SHADER_VARIABLE_TYPE paramType;
  285. uint8_t columns;
  286. uint8_t rows;
  287. };
  288. static const UniformRemapDx11 s_constRemapDx11[7] =
  289. {
  290. { UniformType::Uniform1iv, D3D_SVC_SCALAR, D3D_SVT_INT, 0, 0 },
  291. { UniformType::Uniform1fv, D3D_SVC_SCALAR, D3D_SVT_FLOAT, 0, 0 },
  292. { UniformType::Uniform2fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  293. { UniformType::Uniform3fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  294. { UniformType::Uniform4fv, D3D_SVC_VECTOR, D3D_SVT_FLOAT, 0, 0 },
  295. { UniformType::Uniform3x3fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 3, 3 },
  296. { UniformType::Uniform4x4fv, D3D_SVC_MATRIX_COLUMNS, D3D_SVT_FLOAT, 4, 4 },
  297. };
  298. UniformType::Enum findUniformTypeDx11(const D3D11_SHADER_TYPE_DESC& constDesc)
  299. {
  300. for (uint32_t ii = 0; ii < BX_COUNTOF(s_constRemapDx11); ++ii)
  301. {
  302. const UniformRemapDx11& remap = s_constRemapDx11[ii];
  303. if (remap.paramClass == constDesc.Class
  304. && remap.paramType == constDesc.Type)
  305. {
  306. if (D3D_SVC_MATRIX_COLUMNS != constDesc.Class)
  307. {
  308. return remap.id;
  309. }
  310. if (remap.columns == constDesc.Columns
  311. && remap.rows == constDesc.Rows)
  312. {
  313. return remap.id;
  314. }
  315. }
  316. }
  317. return UniformType::Count;
  318. }
  319. static uint32_t s_optimizationLevelDx11[4] =
  320. {
  321. D3DCOMPILE_OPTIMIZATION_LEVEL0,
  322. D3DCOMPILE_OPTIMIZATION_LEVEL1,
  323. D3DCOMPILE_OPTIMIZATION_LEVEL2,
  324. D3DCOMPILE_OPTIMIZATION_LEVEL3,
  325. };
  326. #endif // BX_PLATFORM_WINDOWS
  327. int32_t writef(bx::WriterI* _writer, const char* _format, ...)
  328. {
  329. va_list argList;
  330. va_start(argList, _format);
  331. char temp[2048];
  332. char* out = temp;
  333. int32_t max = sizeof(temp);
  334. int32_t len = bx::vsnprintf(out, max, _format, argList);
  335. if (len > max)
  336. {
  337. out = (char*)alloca(len);
  338. len = bx::vsnprintf(out, len, _format, argList);
  339. }
  340. len = bx::write(_writer, out, len);
  341. va_end(argList);
  342. return len;
  343. }
  344. class Bin2cWriter : public bx::CrtFileWriter
  345. {
  346. public:
  347. Bin2cWriter(const char* _name)
  348. : m_name(_name)
  349. {
  350. }
  351. virtual ~Bin2cWriter()
  352. {
  353. }
  354. virtual int32_t close() BX_OVERRIDE
  355. {
  356. generate();
  357. return bx::CrtFileWriter::close();
  358. }
  359. virtual int32_t write(const void* _data, int32_t _size) BX_OVERRIDE
  360. {
  361. const char* data = (const char*)_data;
  362. m_buffer.insert(m_buffer.end(), data, data+_size);
  363. return _size;
  364. }
  365. private:
  366. void generate()
  367. {
  368. #define HEX_DUMP_WIDTH 16
  369. #define HEX_DUMP_SPACE_WIDTH 96
  370. #define HEX_DUMP_FORMAT "%-" BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." BX_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  371. const uint8_t* data = &m_buffer[0];
  372. uint32_t size = (uint32_t)m_buffer.size();
  373. outf("static const uint8_t %s[%d] =\n{\n", m_name.c_str(), size);
  374. if (NULL != data)
  375. {
  376. char hex[HEX_DUMP_SPACE_WIDTH+1];
  377. char ascii[HEX_DUMP_WIDTH+1];
  378. uint32_t hexPos = 0;
  379. uint32_t asciiPos = 0;
  380. for (uint32_t ii = 0; ii < size; ++ii)
  381. {
  382. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "0x%02x, ", data[asciiPos]);
  383. hexPos += 6;
  384. ascii[asciiPos] = isprint(data[asciiPos]) && data[asciiPos] != '\\' ? data[asciiPos] : '.';
  385. asciiPos++;
  386. if (HEX_DUMP_WIDTH == asciiPos)
  387. {
  388. ascii[asciiPos] = '\0';
  389. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  390. data += asciiPos;
  391. hexPos = 0;
  392. asciiPos = 0;
  393. }
  394. }
  395. if (0 != asciiPos)
  396. {
  397. ascii[asciiPos] = '\0';
  398. outf("\t" HEX_DUMP_FORMAT "// %s\n", hex, ascii);
  399. }
  400. }
  401. outf("};\n");
  402. #undef HEX_DUMP_WIDTH
  403. #undef HEX_DUMP_SPACE_WIDTH
  404. #undef HEX_DUMP_FORMAT
  405. }
  406. int32_t outf(const char* _format, ...)
  407. {
  408. va_list argList;
  409. va_start(argList, _format);
  410. char temp[2048];
  411. char* out = temp;
  412. int32_t max = sizeof(temp);
  413. int32_t len = bx::vsnprintf(out, max, _format, argList);
  414. if (len > max)
  415. {
  416. out = (char*)alloca(len);
  417. len = bx::vsnprintf(out, len, _format, argList);
  418. }
  419. int32_t size = bx::CrtFileWriter::write(out, len);
  420. va_end(argList);
  421. return size;
  422. }
  423. std::string m_filePath;
  424. std::string m_name;
  425. typedef std::vector<uint8_t> Buffer;
  426. Buffer m_buffer;
  427. };
  428. struct Varying
  429. {
  430. std::string m_precision;
  431. std::string m_interpolation;
  432. std::string m_name;
  433. std::string m_type;
  434. std::string m_init;
  435. std::string m_semantics;
  436. };
  437. typedef std::unordered_map<std::string, Varying> VaryingMap;
  438. class File
  439. {
  440. public:
  441. File(const char* _filePath)
  442. : m_data(NULL)
  443. {
  444. FILE* file = fopen(_filePath, "r");
  445. if (NULL != file)
  446. {
  447. m_size = fsize(file);
  448. m_data = new char[m_size+1];
  449. m_size = (uint32_t)fread(m_data, 1, m_size, file);
  450. m_data[m_size] = '\0';
  451. fclose(file);
  452. }
  453. }
  454. ~File()
  455. {
  456. delete [] m_data;
  457. }
  458. const char* getData() const
  459. {
  460. return m_data;
  461. }
  462. uint32_t getSize() const
  463. {
  464. return m_size;
  465. }
  466. private:
  467. char* m_data;
  468. uint32_t m_size;
  469. };
  470. void strins(char* _str, const char* _insert)
  471. {
  472. size_t len = strlen(_insert);
  473. memmove(&_str[len], _str, strlen(_str) );
  474. memcpy(_str, _insert, len);
  475. }
  476. void strreplace(char* _str, const char* _find, const char* _replace)
  477. {
  478. const size_t len = strlen(_find);
  479. char* replace = (char*)alloca(len+1);
  480. bx::strlcpy(replace, _replace, len+1);
  481. for (uint32_t ii = strlen(replace); ii < len; ++ii)
  482. {
  483. replace[ii] = ' ';
  484. }
  485. replace[len] = '\0';
  486. BX_CHECK(len >= strlen(_replace), "");
  487. for (char* ptr = strstr(_str, _find); NULL != ptr; ptr = strstr(ptr + len, _find) )
  488. {
  489. memcpy(ptr, replace, len);
  490. }
  491. }
  492. class LineReader
  493. {
  494. public:
  495. LineReader(const char* _str)
  496. : m_str(_str)
  497. , m_pos(0)
  498. , m_size( (uint32_t)strlen(_str) )
  499. {
  500. }
  501. std::string getLine()
  502. {
  503. const char* str = &m_str[m_pos];
  504. skipLine();
  505. const char* eol = &m_str[m_pos];
  506. std::string tmp;
  507. tmp.assign(str, eol-str);
  508. return tmp;
  509. }
  510. bool isEof() const
  511. {
  512. return m_str[m_pos] == '\0';
  513. }
  514. void skipLine()
  515. {
  516. const char* str = &m_str[m_pos];
  517. const char* nl = bx::strnl(str);
  518. m_pos += (uint32_t)(nl - str);
  519. }
  520. const char* m_str;
  521. uint32_t m_pos;
  522. uint32_t m_size;
  523. };
  524. void printCode(const char* _code, int32_t _line = 0, int32_t _start = 0, int32_t _end = INT32_MAX)
  525. {
  526. fprintf(stderr, "Code:\n---\n");
  527. LineReader lr(_code);
  528. for (int32_t line = 1; !lr.isEof() && line < _end; ++line)
  529. {
  530. if (line >= _start)
  531. {
  532. fprintf(stderr, "%s%3d: %s", _line == line ? ">>> " : " ", line, lr.getLine().c_str() );
  533. }
  534. else
  535. {
  536. lr.skipLine();
  537. }
  538. }
  539. fprintf(stderr, "---\n");
  540. }
  541. void writeFile(const char* _filePath, const void* _data, int32_t _size)
  542. {
  543. bx::CrtFileWriter out;
  544. if (0 == out.open(_filePath) )
  545. {
  546. out.write(_data, _size);
  547. out.close();
  548. }
  549. }
  550. bool compileGLSLShader(bx::CommandLine& _cmdLine, uint32_t _gles, const std::string& _code, bx::WriterI* _writer)
  551. {
  552. char ch = tolower(_cmdLine.findOption('\0', "type")[0]);
  553. const glslopt_shader_type type = ch == 'f'
  554. ? kGlslOptShaderFragment
  555. : (ch == 'c' ? kGlslOptShaderCompute : kGlslOptShaderVertex);
  556. glslopt_target target = kGlslTargetOpenGL;
  557. switch (_gles)
  558. {
  559. case 2:
  560. target = kGlslTargetOpenGLES20;
  561. break;
  562. case 3:
  563. target = kGlslTargetOpenGLES30;
  564. break;
  565. default:
  566. target = kGlslTargetOpenGL;
  567. break;
  568. }
  569. glslopt_ctx* ctx = glslopt_initialize(target);
  570. glslopt_shader* shader = glslopt_optimize(ctx, type, _code.c_str(), 0);
  571. if (!glslopt_get_status(shader) )
  572. {
  573. const char* log = glslopt_get_log(shader);
  574. int32_t source = 0;
  575. int32_t line = 0;
  576. int32_t column = 0;
  577. int32_t start = 0;
  578. int32_t end = INT32_MAX;
  579. if (3 == sscanf(log, "%u:%u(%u):", &source, &line, &column)
  580. && 0 != line)
  581. {
  582. start = bx::uint32_imax(1, line-10);
  583. end = start + 20;
  584. }
  585. printCode(_code.c_str(), line, start, end);
  586. fprintf(stderr, "Error: %s\n", log);
  587. glslopt_cleanup(ctx);
  588. return false;
  589. }
  590. const char* optimizedShader = glslopt_get_output(shader);
  591. // Trim all directives.
  592. while ('#' == *optimizedShader)
  593. {
  594. optimizedShader = bx::strnl(optimizedShader);
  595. }
  596. if (0 != _gles)
  597. {
  598. char* shader = const_cast<char*>(optimizedShader);
  599. strreplace(shader, "gl_FragDepthEXT", "gl_FragDepth");
  600. strreplace(shader, "texture2DLodEXT", "texture2DLod");
  601. strreplace(shader, "texture2DProjLodEXT", "texture2DProjLod");
  602. strreplace(shader, "textureCubeLodEXT", "textureCubeLod");
  603. strreplace(shader, "texture2DGradEXT", "texture2DGrad");
  604. strreplace(shader, "texture2DProjGradEXT", "texture2DProjGrad");
  605. strreplace(shader, "textureCubeGradEXT", "textureCubeGrad");
  606. strreplace(shader, "shadow2DEXT", "shadow2D");
  607. strreplace(shader, "shadow2DProjEXT", "shadow2DProj");
  608. }
  609. UniformArray uniforms;
  610. {
  611. const char* parse = optimizedShader;
  612. while (NULL != parse
  613. && *parse != '\0')
  614. {
  615. parse = bx::strws(parse);
  616. const char* eol = strchr(parse, ';');
  617. if (NULL != eol)
  618. {
  619. const char* qualifier = parse;
  620. parse = bx::strws(bx::strword(parse) );
  621. if (0 == strncmp(qualifier, "attribute", 9)
  622. || 0 == strncmp(qualifier, "varying", 7) )
  623. {
  624. // skip attributes and varyings.
  625. parse = eol + 1;
  626. continue;
  627. }
  628. if (0 != strncmp(qualifier, "uniform", 7) )
  629. {
  630. // end if there is no uniform keyword.
  631. parse = NULL;
  632. continue;
  633. }
  634. const char* precision = NULL;
  635. const char* type = parse;
  636. if (0 == strncmp(type, "lowp", 4)
  637. || 0 == strncmp(type, "mediump", 7)
  638. || 0 == strncmp(type, "highp", 5) )
  639. {
  640. precision = type;
  641. type = parse = bx::strws(bx::strword(parse) );
  642. }
  643. BX_UNUSED(precision);
  644. char uniformType[256];
  645. parse = bx::strword(parse);
  646. if (0 == strncmp(type, "sampler", 7) )
  647. {
  648. strcpy(uniformType, "int");
  649. }
  650. else
  651. {
  652. bx::strlcpy(uniformType, type, parse-type+1);
  653. }
  654. const char* name = parse = bx::strws(parse);
  655. char uniformName[256];
  656. uint8_t num = 1;
  657. const char* array = bx::strnstr(name, "[", eol-parse);
  658. if (NULL != array)
  659. {
  660. bx::strlcpy(uniformName, name, array-name+1);
  661. char arraySize[32];
  662. const char* end = bx::strnstr(array, "]", eol-array);
  663. bx::strlcpy(arraySize, array+1, end-array);
  664. num = atoi(arraySize);
  665. }
  666. else
  667. {
  668. bx::strlcpy(uniformName, name, eol-name+1);
  669. }
  670. Uniform un;
  671. un.type = nameToUniformTypeEnum(uniformType);
  672. if (UniformType::Count != un.type)
  673. {
  674. BX_TRACE("name: %s (type %d, num %d)", uniformName, un.type, num);
  675. un.name = uniformName;
  676. un.num = num;
  677. un.regIndex = 0;
  678. un.regCount = num;
  679. uniforms.push_back(un);
  680. }
  681. parse = eol + 1;
  682. }
  683. }
  684. }
  685. uint16_t count = (uint16_t)uniforms.size();
  686. bx::write(_writer, count);
  687. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  688. {
  689. const Uniform& un = *it;
  690. uint8_t nameSize = (uint8_t)un.name.size();
  691. bx::write(_writer, nameSize);
  692. bx::write(_writer, un.name.c_str(), nameSize);
  693. uint8_t type = un.type;
  694. bx::write(_writer, type);
  695. bx::write(_writer, un.num);
  696. bx::write(_writer, un.regIndex);
  697. bx::write(_writer, un.regCount);
  698. BX_TRACE("%s, %s, %d, %d, %d"
  699. , un.name.c_str()
  700. , s_uniformTypeName[un.type]
  701. , un.num
  702. , un.regIndex
  703. , un.regCount
  704. );
  705. }
  706. uint32_t shaderSize = (uint32_t)strlen(optimizedShader);
  707. bx::write(_writer, shaderSize);
  708. bx::write(_writer, optimizedShader, shaderSize);
  709. uint8_t nul = 0;
  710. bx::write(_writer, nul);
  711. glslopt_cleanup(ctx);
  712. return true;
  713. }
  714. bool compileHLSLShaderDx9(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  715. {
  716. #if BX_PLATFORM_WINDOWS
  717. BX_TRACE("DX9");
  718. const char* profile = _cmdLine.findOption('p', "profile");
  719. if (NULL == profile)
  720. {
  721. fprintf(stderr, "Shader profile must be specified.\n");
  722. return false;
  723. }
  724. bool debug = _cmdLine.hasArg('\0', "debug");
  725. uint32_t flags = 0;
  726. flags |= debug ? D3DXSHADER_DEBUG : 0;
  727. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DXSHADER_AVOID_FLOW_CONTROL : 0;
  728. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DXSHADER_NO_PRESHADER : 0;
  729. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DXSHADER_PARTIALPRECISION : 0;
  730. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DXSHADER_PREFER_FLOW_CONTROL : 0;
  731. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  732. bool werror = _cmdLine.hasArg('\0', "Werror");
  733. uint32_t optimization = 3;
  734. if (_cmdLine.hasArg(optimization, 'O') )
  735. {
  736. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx9)-1);
  737. flags |= s_optimizationLevelDx9[optimization];
  738. }
  739. else
  740. {
  741. flags |= D3DXSHADER_SKIPOPTIMIZATION;
  742. }
  743. BX_TRACE("Profile: %s", profile);
  744. BX_TRACE("Flags: 0x%08x", flags);
  745. LPD3DXBUFFER code;
  746. LPD3DXBUFFER errorMsg;
  747. LPD3DXCONSTANTTABLE constantTable;
  748. HRESULT hr;
  749. // Output preprocessed shader so that HLSL can be debugged via GPA
  750. // or PIX. Compiling through memory won't embed preprocessed shader
  751. // file path.
  752. if (debug)
  753. {
  754. std::string hlslfp = _cmdLine.findOption('o');
  755. hlslfp += ".hlsl";
  756. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  757. hr = D3DXCompileShaderFromFileA(hlslfp.c_str()
  758. , NULL
  759. , NULL
  760. , "main"
  761. , profile
  762. , flags
  763. , &code
  764. , &errorMsg
  765. , &constantTable
  766. );
  767. }
  768. else
  769. {
  770. hr = D3DXCompileShader(_code.c_str()
  771. , (uint32_t)_code.size()
  772. , NULL
  773. , NULL
  774. , "main"
  775. , profile
  776. , flags
  777. , &code
  778. , &errorMsg
  779. , &constantTable
  780. );
  781. }
  782. if (FAILED(hr)
  783. || (werror && NULL != errorMsg) )
  784. {
  785. const char* log = (const char*)errorMsg->GetBufferPointer();
  786. char source[1024];
  787. int32_t line = 0;
  788. int32_t column = 0;
  789. int32_t start = 0;
  790. int32_t end = INT32_MAX;
  791. if (3 == sscanf(log, "%[^(](%u,%u):", source, &line, &column)
  792. && 0 != line)
  793. {
  794. start = bx::uint32_imax(1, line-10);
  795. end = start + 20;
  796. }
  797. printCode(_code.c_str(), line, start, end);
  798. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  799. errorMsg->Release();
  800. return false;
  801. }
  802. D3DXCONSTANTTABLE_DESC desc;
  803. hr = constantTable->GetDesc(&desc);
  804. if (FAILED(hr) )
  805. {
  806. fprintf(stderr, "Error 0x%08x\n", (uint32_t)hr);
  807. return false;
  808. }
  809. BX_TRACE("Creator: %s 0x%08x", desc.Creator, (uint32_t /*mingw warning*/)desc.Version);
  810. BX_TRACE("Num constants: %d", desc.Constants);
  811. BX_TRACE("# cl ty RxC S By Name");
  812. UniformArray uniforms;
  813. for (uint32_t ii = 0; ii < desc.Constants; ++ii)
  814. {
  815. D3DXHANDLE handle = constantTable->GetConstant(NULL, ii);
  816. D3DXCONSTANT_DESC constDesc;
  817. uint32_t count;
  818. constantTable->GetConstantDesc(handle, &constDesc, &count);
  819. BX_TRACE("%3d %2d %2d [%dx%d] %d %3d %s[%d] c%d (%d)"
  820. , ii
  821. , constDesc.Class
  822. , constDesc.Type
  823. , constDesc.Rows
  824. , constDesc.Columns
  825. , constDesc.StructMembers
  826. , constDesc.Bytes
  827. , constDesc.Name
  828. , constDesc.Elements
  829. , constDesc.RegisterIndex
  830. , constDesc.RegisterCount
  831. );
  832. UniformType::Enum type = findUniformTypeDx9(constDesc);
  833. if (UniformType::Count != type)
  834. {
  835. Uniform un;
  836. un.name = '$' == constDesc.Name[0] ? constDesc.Name+1 : constDesc.Name;
  837. un.type = type;
  838. un.num = constDesc.Elements;
  839. un.regIndex = constDesc.RegisterIndex;
  840. un.regCount = constDesc.RegisterCount;
  841. uniforms.push_back(un);
  842. }
  843. }
  844. uint16_t count = (uint16_t)uniforms.size();
  845. bx::write(_writer, count);
  846. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  847. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  848. {
  849. const Uniform& un = *it;
  850. uint8_t nameSize = (uint8_t)un.name.size();
  851. bx::write(_writer, nameSize);
  852. bx::write(_writer, un.name.c_str(), nameSize);
  853. uint8_t type = un.type|fragmentBit;
  854. bx::write(_writer, type);
  855. bx::write(_writer, un.num);
  856. bx::write(_writer, un.regIndex);
  857. bx::write(_writer, un.regCount);
  858. BX_TRACE("%s, %s, %d, %d, %d"
  859. , un.name.c_str()
  860. , s_uniformTypeName[un.type]
  861. , un.num
  862. , un.regIndex
  863. , un.regCount
  864. );
  865. }
  866. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  867. bx::write(_writer, shaderSize);
  868. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  869. uint8_t nul = 0;
  870. bx::write(_writer, nul);
  871. if (_cmdLine.hasArg('\0', "disasm") )
  872. {
  873. LPD3DXBUFFER disasm;
  874. D3DXDisassembleShader( (const DWORD*)code->GetBufferPointer()
  875. , false
  876. , NULL
  877. , &disasm
  878. );
  879. if (NULL != disasm)
  880. {
  881. std::string disasmfp = _cmdLine.findOption('o');
  882. disasmfp += ".disasm";
  883. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), disasm->GetBufferSize() );
  884. disasm->Release();
  885. }
  886. }
  887. if (NULL != code)
  888. {
  889. code->Release();
  890. }
  891. if (NULL != errorMsg)
  892. {
  893. errorMsg->Release();
  894. }
  895. if (NULL != constantTable)
  896. {
  897. constantTable->Release();
  898. }
  899. return true;
  900. #else
  901. BX_UNUSED(_cmdLine, _code, _writer);
  902. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  903. return false;
  904. #endif // BX_PLATFORM_WINDOWS
  905. }
  906. bool compileHLSLShaderDx11(bx::CommandLine& _cmdLine, const std::string& _code, bx::WriterI* _writer)
  907. {
  908. #if BX_PLATFORM_WINDOWS
  909. BX_TRACE("DX11");
  910. const char* profile = _cmdLine.findOption('p', "profile");
  911. if (NULL == profile)
  912. {
  913. fprintf(stderr, "Shader profile must be specified.\n");
  914. return false;
  915. }
  916. bool debug = _cmdLine.hasArg('\0', "debug");
  917. uint32_t flags = D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY;
  918. flags |= debug ? D3DCOMPILE_DEBUG : 0;
  919. flags |= _cmdLine.hasArg('\0', "avoid-flow-control") ? D3DCOMPILE_AVOID_FLOW_CONTROL : 0;
  920. flags |= _cmdLine.hasArg('\0', "no-preshader") ? D3DCOMPILE_NO_PRESHADER : 0;
  921. flags |= _cmdLine.hasArg('\0', "partial-precision") ? D3DCOMPILE_PARTIAL_PRECISION : 0;
  922. flags |= _cmdLine.hasArg('\0', "prefer-flow-control") ? D3DCOMPILE_PREFER_FLOW_CONTROL : 0;
  923. flags |= _cmdLine.hasArg('\0', "backwards-compatibility") ? D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY : 0;
  924. bool werror = _cmdLine.hasArg('\0', "Werror");
  925. if (werror)
  926. {
  927. flags |= D3DCOMPILE_WARNINGS_ARE_ERRORS;
  928. }
  929. uint32_t optimization = 3;
  930. if (_cmdLine.hasArg(optimization, 'O') )
  931. {
  932. optimization = bx::uint32_min(optimization, BX_COUNTOF(s_optimizationLevelDx11)-1);
  933. flags |= s_optimizationLevelDx11[optimization];
  934. }
  935. else
  936. {
  937. flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
  938. }
  939. BX_TRACE("Profile: %s", profile);
  940. BX_TRACE("Flags: 0x%08x", flags);
  941. ID3DBlob* code;
  942. ID3DBlob* errorMsg;
  943. // Output preprocessed shader so that HLSL can be debugged via GPA
  944. // or PIX. Compiling through memory won't embed preprocessed shader
  945. // file path.
  946. std::string hlslfp;
  947. if (debug)
  948. {
  949. hlslfp = _cmdLine.findOption('o');
  950. hlslfp += ".hlsl";
  951. writeFile(hlslfp.c_str(), _code.c_str(), (int32_t)_code.size() );
  952. }
  953. HRESULT hr = D3DCompile(_code.c_str()
  954. , _code.size()
  955. , hlslfp.c_str()
  956. , NULL
  957. , NULL
  958. , "main"
  959. , profile
  960. , flags
  961. , 0
  962. , &code
  963. , &errorMsg
  964. );
  965. if (FAILED(hr)
  966. || (werror && NULL != errorMsg) )
  967. {
  968. const char* log = (char*)errorMsg->GetBufferPointer();
  969. int32_t line = 0;
  970. int32_t column = 0;
  971. int32_t start = 0;
  972. int32_t end = INT32_MAX;
  973. if (2 == sscanf(log, "(%u,%u):", &line, &column)
  974. && 0 != line)
  975. {
  976. start = bx::uint32_imax(1, line-10);
  977. end = start + 20;
  978. }
  979. printCode(_code.c_str(), line, start, end);
  980. fprintf(stderr, "Error: 0x%08x %s\n", (uint32_t)hr, log);
  981. errorMsg->Release();
  982. return false;
  983. }
  984. UniformArray uniforms;
  985. ID3D11ShaderReflection* reflect = NULL;
  986. hr = D3DReflect(code->GetBufferPointer()
  987. , code->GetBufferSize()
  988. , IID_ID3D11ShaderReflection
  989. , (void**)&reflect
  990. );
  991. if (FAILED(hr) )
  992. {
  993. fprintf(stderr, "Error: 0x%08x\n", (uint32_t)hr);
  994. return false;
  995. }
  996. D3D11_SHADER_DESC desc;
  997. hr = reflect->GetDesc(&desc);
  998. if (FAILED(hr) )
  999. {
  1000. fprintf(stderr, BX_FILE_LINE_LITERAL "Error: 0x%08x\n", (uint32_t)hr);
  1001. return false;
  1002. }
  1003. BX_TRACE("Creator: %s 0x%08x", desc.Creator, desc.Version);
  1004. BX_TRACE("Num constant buffers: %d", desc.ConstantBuffers);
  1005. BX_TRACE("Input:");
  1006. uint8_t attrMask[Attrib::Count];
  1007. memset(attrMask, 0, sizeof(attrMask) );
  1008. for (uint32_t ii = 0; ii < desc.InputParameters; ++ii)
  1009. {
  1010. D3D11_SIGNATURE_PARAMETER_DESC spd;
  1011. reflect->GetInputParameterDesc(ii, &spd);
  1012. BX_TRACE("\t%2d: %s%d, vt %d, ct %d, mask %x, reg %d"
  1013. , ii
  1014. , spd.SemanticName
  1015. , spd.SemanticIndex
  1016. , spd.SystemValueType
  1017. , spd.ComponentType
  1018. , spd.Mask
  1019. , spd.Register
  1020. );
  1021. const RemapInputSemantic& ris = findInputSemantic(spd.SemanticName, spd.SemanticIndex);
  1022. if (ris.m_attr != Attrib::Count)
  1023. {
  1024. attrMask[ris.m_attr] = 0xff;
  1025. }
  1026. }
  1027. BX_TRACE("Output:");
  1028. for (uint32_t ii = 0; ii < desc.OutputParameters; ++ii)
  1029. {
  1030. D3D11_SIGNATURE_PARAMETER_DESC spd;
  1031. reflect->GetOutputParameterDesc(ii, &spd);
  1032. BX_TRACE("\t%2d: %s%d, %d, %d", ii, spd.SemanticName, spd.SemanticIndex, spd.SystemValueType, spd.ComponentType);
  1033. }
  1034. uint16_t size = 0;
  1035. for (uint32_t ii = 0; ii < bx::uint32_min(1, desc.ConstantBuffers); ++ii)
  1036. {
  1037. ID3D11ShaderReflectionConstantBuffer* cbuffer = reflect->GetConstantBufferByIndex(ii);
  1038. D3D11_SHADER_BUFFER_DESC bufferDesc;
  1039. hr = cbuffer->GetDesc(&bufferDesc);
  1040. size = (uint16_t)bufferDesc.Size;
  1041. if (SUCCEEDED(hr) )
  1042. {
  1043. BX_TRACE("%s, %d, vars %d, size %d"
  1044. , bufferDesc.Name
  1045. , bufferDesc.Type
  1046. , bufferDesc.Variables
  1047. , bufferDesc.Size
  1048. );
  1049. for (uint32_t jj = 0; jj < bufferDesc.Variables; ++jj)
  1050. {
  1051. ID3D11ShaderReflectionVariable* var = cbuffer->GetVariableByIndex(jj);
  1052. ID3D11ShaderReflectionType* type = var->GetType();
  1053. D3D11_SHADER_VARIABLE_DESC varDesc;
  1054. hr = var->GetDesc(&varDesc);
  1055. if (SUCCEEDED(hr) )
  1056. {
  1057. D3D11_SHADER_TYPE_DESC constDesc;
  1058. hr = type->GetDesc(&constDesc);
  1059. if (SUCCEEDED(hr) )
  1060. {
  1061. UniformType::Enum type = findUniformTypeDx11(constDesc);
  1062. if (UniformType::Count != type
  1063. && 0 != (varDesc.uFlags & D3D_SVF_USED) )
  1064. {
  1065. Uniform un;
  1066. un.name = varDesc.Name;
  1067. un.type = type;
  1068. un.num = constDesc.Elements;
  1069. un.regIndex = varDesc.StartOffset;
  1070. un.regCount = BX_ALIGN_16(varDesc.Size)/16;
  1071. uniforms.push_back(un);
  1072. BX_TRACE("\t%s, %d, size %d, flags 0x%08x, %d"
  1073. , varDesc.Name
  1074. , varDesc.StartOffset
  1075. , varDesc.Size
  1076. , varDesc.uFlags
  1077. , type
  1078. );
  1079. }
  1080. else
  1081. {
  1082. BX_TRACE("\t%s, unknown type", varDesc.Name);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. }
  1088. }
  1089. BX_TRACE("Bound:");
  1090. for (uint32_t ii = 0; ii < desc.BoundResources; ++ii)
  1091. {
  1092. D3D11_SHADER_INPUT_BIND_DESC bindDesc;
  1093. hr = reflect->GetResourceBindingDesc(ii, &bindDesc);
  1094. if (SUCCEEDED(hr) )
  1095. {
  1096. // if (bindDesc.Type == D3D_SIT_SAMPLER)
  1097. {
  1098. BX_TRACE("\t%s, %d, %d, %d"
  1099. , bindDesc.Name
  1100. , bindDesc.Type
  1101. , bindDesc.BindPoint
  1102. , bindDesc.BindCount
  1103. );
  1104. }
  1105. }
  1106. }
  1107. uint16_t count = (uint16_t)uniforms.size();
  1108. bx::write(_writer, count);
  1109. uint32_t fragmentBit = profile[0] == 'p' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  1110. for (UniformArray::const_iterator it = uniforms.begin(); it != uniforms.end(); ++it)
  1111. {
  1112. const Uniform& un = *it;
  1113. uint8_t nameSize = (uint8_t)un.name.size();
  1114. bx::write(_writer, nameSize);
  1115. bx::write(_writer, un.name.c_str(), nameSize);
  1116. uint8_t type = un.type|fragmentBit;
  1117. bx::write(_writer, type);
  1118. bx::write(_writer, un.num);
  1119. bx::write(_writer, un.regIndex);
  1120. bx::write(_writer, un.regCount);
  1121. BX_TRACE("%s, %s, %d, %d, %d"
  1122. , un.name.c_str()
  1123. , s_uniformTypeName[un.type]
  1124. , un.num
  1125. , un.regIndex
  1126. , un.regCount
  1127. );
  1128. }
  1129. uint16_t shaderSize = (uint16_t)code->GetBufferSize();
  1130. bx::write(_writer, shaderSize);
  1131. bx::write(_writer, code->GetBufferPointer(), shaderSize);
  1132. uint8_t nul = 0;
  1133. bx::write(_writer, nul);
  1134. bx::write(_writer, attrMask, sizeof(attrMask) );
  1135. bx::write(_writer, size);
  1136. if (_cmdLine.hasArg('\0', "disasm") )
  1137. {
  1138. ID3DBlob* disasm;
  1139. D3DDisassemble(code->GetBufferPointer()
  1140. , code->GetBufferSize()
  1141. , 0
  1142. , NULL
  1143. , &disasm
  1144. );
  1145. if (NULL != disasm)
  1146. {
  1147. std::string disasmfp = _cmdLine.findOption('o');
  1148. disasmfp += ".disasm";
  1149. writeFile(disasmfp.c_str(), disasm->GetBufferPointer(), (uint32_t)disasm->GetBufferSize() );
  1150. disasm->Release();
  1151. }
  1152. }
  1153. if (NULL != reflect)
  1154. {
  1155. reflect->Release();
  1156. }
  1157. if (NULL != errorMsg)
  1158. {
  1159. errorMsg->Release();
  1160. }
  1161. code->Release();
  1162. return true;
  1163. #else
  1164. BX_UNUSED(_cmdLine, _code, _writer);
  1165. fprintf(stderr, "HLSL compiler is not supported on this platform.\n");
  1166. return false;
  1167. #endif // BX_PLATFORM_WINDOWS
  1168. }
  1169. struct Preprocessor
  1170. {
  1171. Preprocessor(const char* _filePath, bool _gles, const char* _includeDir = NULL)
  1172. : m_tagptr(m_tags)
  1173. , m_scratchPos(0)
  1174. , m_fgetsPos(0)
  1175. {
  1176. m_tagptr->tag = FPPTAG_USERDATA;
  1177. m_tagptr->data = this;
  1178. m_tagptr++;
  1179. m_tagptr->tag = FPPTAG_DEPENDS;
  1180. m_tagptr->data = (void*)fppDepends;
  1181. m_tagptr++;
  1182. m_tagptr->tag = FPPTAG_INPUT;
  1183. m_tagptr->data = (void*)fppInput;
  1184. m_tagptr++;
  1185. m_tagptr->tag = FPPTAG_OUTPUT;
  1186. m_tagptr->data = (void*)fppOutput;
  1187. m_tagptr++;
  1188. m_tagptr->tag = FPPTAG_ERROR;
  1189. m_tagptr->data = (void*)fppError;
  1190. m_tagptr++;
  1191. m_tagptr->tag = FPPTAG_IGNOREVERSION;
  1192. m_tagptr->data = (void*)0;
  1193. m_tagptr++;
  1194. m_tagptr->tag = FPPTAG_LINE;
  1195. m_tagptr->data = (void*)0;
  1196. m_tagptr++;
  1197. m_tagptr->tag = FPPTAG_INPUT_NAME;
  1198. m_tagptr->data = scratch(_filePath);
  1199. m_tagptr++;
  1200. if (NULL != _includeDir)
  1201. {
  1202. addInclude(_includeDir);
  1203. }
  1204. if (!_gles)
  1205. {
  1206. m_default = "#define lowp\n#define mediump\n#define highp\n";
  1207. }
  1208. }
  1209. void setDefine(const char* _define)
  1210. {
  1211. m_tagptr->tag = FPPTAG_DEFINE;
  1212. m_tagptr->data = scratch(_define);
  1213. m_tagptr++;
  1214. }
  1215. void setDefaultDefine(const char* _name)
  1216. {
  1217. char temp[1024];
  1218. bx::snprintf(temp, BX_COUNTOF(temp)
  1219. , "#ifndef %s\n"
  1220. "# define %s 0\n"
  1221. "#endif // %s\n"
  1222. "\n"
  1223. , _name
  1224. , _name
  1225. , _name
  1226. );
  1227. m_default += temp;
  1228. }
  1229. void writef(const char* _format, ...)
  1230. {
  1231. va_list argList;
  1232. va_start(argList, _format);
  1233. bx::stringPrintfVargs(m_default, _format, argList);
  1234. va_end(argList);
  1235. }
  1236. void addInclude(const char* _includeDir)
  1237. {
  1238. char* start = scratch(_includeDir);
  1239. for (char* split = strchr(start, ';'); NULL != split; split = strchr(start, ';'))
  1240. {
  1241. *split = '\0';
  1242. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1243. m_tagptr->data = start;
  1244. m_tagptr++;
  1245. start = split + 1;
  1246. }
  1247. m_tagptr->tag = FPPTAG_INCLUDE_DIR;
  1248. m_tagptr->data = start;
  1249. m_tagptr++;
  1250. }
  1251. void addDependency(const char* _fileName)
  1252. {
  1253. m_depends += " \\\n ";
  1254. m_depends += _fileName;
  1255. }
  1256. bool run(const char* _input)
  1257. {
  1258. m_fgetsPos = 0;
  1259. m_preprocessed.clear();
  1260. m_input = m_default;
  1261. m_input += "\n\n";
  1262. size_t len = strlen(_input)+1;
  1263. char* temp = new char[len];
  1264. bx::eolLF(temp, len, _input);
  1265. m_input += temp;
  1266. delete [] temp;
  1267. fppTag* tagptr = m_tagptr;
  1268. tagptr->tag = FPPTAG_END;
  1269. tagptr->data = 0;
  1270. tagptr++;
  1271. int result = fppPreProcess(m_tags);
  1272. return 0 == result;
  1273. }
  1274. char* fgets(char* _buffer, int _size)
  1275. {
  1276. int ii = 0;
  1277. for (char ch = m_input[m_fgetsPos]; m_fgetsPos < m_input.size() && ii < _size-1; ch = m_input[++m_fgetsPos])
  1278. {
  1279. _buffer[ii++] = ch;
  1280. if (ch == '\n' || ii == _size)
  1281. {
  1282. _buffer[ii] = '\0';
  1283. m_fgetsPos++;
  1284. return _buffer;
  1285. }
  1286. }
  1287. return NULL;
  1288. }
  1289. static void fppDepends(char* _fileName, void* _userData)
  1290. {
  1291. Preprocessor* thisClass = (Preprocessor*)_userData;
  1292. thisClass->addDependency(_fileName);
  1293. }
  1294. static char* fppInput(char* _buffer, int _size, void* _userData)
  1295. {
  1296. Preprocessor* thisClass = (Preprocessor*)_userData;
  1297. return thisClass->fgets(_buffer, _size);
  1298. }
  1299. static void fppOutput(int _ch, void* _userData)
  1300. {
  1301. Preprocessor* thisClass = (Preprocessor*)_userData;
  1302. thisClass->m_preprocessed += _ch;
  1303. }
  1304. static void fppError(void* /*_userData*/, char* _format, va_list _vargs)
  1305. {
  1306. vfprintf(stderr, _format, _vargs);
  1307. }
  1308. char* scratch(const char* _str)
  1309. {
  1310. char* result = &m_scratch[m_scratchPos];
  1311. strcpy(result, _str);
  1312. m_scratchPos += (uint32_t)strlen(_str)+1;
  1313. return result;
  1314. }
  1315. fppTag m_tags[MAX_TAGS];
  1316. fppTag* m_tagptr;
  1317. std::string m_depends;
  1318. std::string m_default;
  1319. std::string m_input;
  1320. std::string m_preprocessed;
  1321. char m_scratch[16<<10];
  1322. uint32_t m_scratchPos;
  1323. uint32_t m_fgetsPos;
  1324. };
  1325. const char* baseName(const char* _filePath)
  1326. {
  1327. const char* bs = strrchr(_filePath, '\\');
  1328. const char* fs = strrchr(_filePath, '/');
  1329. const char* column = strrchr(_filePath, ':');
  1330. const char* basename = std::max(std::max(bs, fs), column);
  1331. if (NULL != basename)
  1332. {
  1333. return basename+1;
  1334. }
  1335. return _filePath;
  1336. }
  1337. typedef std::vector<std::string> InOut;
  1338. uint32_t parseInOut(InOut& _inout, const char* _str, const char* _eol)
  1339. {
  1340. uint32_t hash = 0;
  1341. _str = bx::strws(_str);
  1342. if (_str < _eol)
  1343. {
  1344. const char* delim;
  1345. do
  1346. {
  1347. delim = strpbrk(_str, " ,");
  1348. if (NULL != delim)
  1349. {
  1350. delim = delim > _eol ? _eol : delim;
  1351. std::string token;
  1352. token.assign(_str, delim-_str);
  1353. _inout.push_back(token);
  1354. _str = bx::strws(delim + 1);
  1355. }
  1356. }
  1357. while (delim < _eol && _str < _eol && NULL != delim);
  1358. std::sort(_inout.begin(), _inout.end() );
  1359. bx::HashMurmur2A murmur;
  1360. murmur.begin();
  1361. for (InOut::const_iterator it = _inout.begin(), itEnd = _inout.end(); it != itEnd; ++it)
  1362. {
  1363. murmur.add(it->c_str(), (uint32_t)it->size() );
  1364. }
  1365. hash = murmur.end();
  1366. }
  1367. return hash;
  1368. }
  1369. void addFragData(Preprocessor& _preprocessor, char* _data, uint32_t _idx, bool _comma)
  1370. {
  1371. char find[32];
  1372. bx::snprintf(find, sizeof(find), "gl_FragData[%d]", _idx);
  1373. char replace[32];
  1374. bx::snprintf(replace, sizeof(replace), "gl_FragData_%d_", _idx);
  1375. strreplace(_data, find, replace);
  1376. _preprocessor.writef(
  1377. " \\\n\t%sout vec4 gl_FragData_%d_ : SV_TARGET%d"
  1378. , _comma ? ", " : " "
  1379. , _idx
  1380. , _idx
  1381. );
  1382. }
  1383. // c - compute
  1384. // d - domain
  1385. // f - fragment
  1386. // g - geometry
  1387. // h - hull
  1388. // v - vertex
  1389. //
  1390. // OpenGL #version Features Direct3D Features Shader Model
  1391. // 2.1 120 vf 9.0 vf 2.0
  1392. // 3.0 130
  1393. // 3.1 140
  1394. // 3.2 150 vgf
  1395. // 3.3 330 10.0 vgf 4.0
  1396. // 4.0 400 vhdgf
  1397. // 4.1 410
  1398. // 4.2 420 11.0 vhdgf+c 5.0
  1399. // 4.3 430 vhdgf+c
  1400. // 4.4 440
  1401. void help(const char* _error = NULL)
  1402. {
  1403. if (NULL != _error)
  1404. {
  1405. fprintf(stderr, "Error:\n%s\n\n", _error);
  1406. }
  1407. fprintf(stderr
  1408. , "shaderc, bgfx shader compiler tool\n"
  1409. "Copyright 2011-2014 Branimir Karadzic. All rights reserved.\n"
  1410. "License: http://www.opensource.org/licenses/BSD-2-Clause\n\n"
  1411. );
  1412. fprintf(stderr
  1413. , "Usage: shaderc -f <in> -o <out> --type <v/f> --platform <platform>\n"
  1414. "\n"
  1415. "Options:\n"
  1416. " -f <file path> Input file path.\n"
  1417. " -i <include path> Include path (for multiple paths use semicolon).\n"
  1418. " -o <file path> Output file path.\n"
  1419. " --bin2c <file path> Generate C header file.\n"
  1420. " --depends <file path> Generate makefile style depends file.\n"
  1421. " --platform <platform> Target platform.\n"
  1422. " android\n"
  1423. " asm.js\n"
  1424. " ios\n"
  1425. " linux\n"
  1426. " nacl\n"
  1427. " osx\n"
  1428. " windows\n"
  1429. " --preprocess Preprocess only.\n"
  1430. " --raw Do not process shader. No preprocessor, and no glsl-optimizer (GLSL only).\n"
  1431. " --type <type> Shader type (vertex, fragment)\n"
  1432. " --varyingdef <file path> Path to varying.def.sc file.\n"
  1433. " --verbose Verbose.\n"
  1434. "\n"
  1435. "Options (DX9 and DX11 only):\n"
  1436. "\n"
  1437. " --debug Debug information.\n"
  1438. " --disasm Disassemble compiled shader.\n"
  1439. " -p, --profile <profile> Shader model (f.e. ps_3_0).\n"
  1440. " -O <level> Optimization level (0, 1, 2, 3).\n"
  1441. " --Werror Treat warnings as errors.\n"
  1442. "\n"
  1443. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  1444. );
  1445. }
  1446. int main(int _argc, const char* _argv[])
  1447. {
  1448. bx::CommandLine cmdLine(_argc, _argv);
  1449. if (cmdLine.hasArg('h', "help") )
  1450. {
  1451. help();
  1452. return EXIT_FAILURE;
  1453. }
  1454. g_verbose = cmdLine.hasArg("verbose");
  1455. const char* filePath = cmdLine.findOption('f');
  1456. if (NULL == filePath)
  1457. {
  1458. help("Shader file name must be specified.");
  1459. return EXIT_FAILURE;
  1460. }
  1461. const char* outFilePath = cmdLine.findOption('o');
  1462. if (NULL == outFilePath)
  1463. {
  1464. help("Output file name must be specified.");
  1465. return EXIT_FAILURE;
  1466. }
  1467. const char* type = cmdLine.findOption('\0', "type");
  1468. if (NULL == type)
  1469. {
  1470. help("Must specify shader type.");
  1471. return EXIT_FAILURE;
  1472. }
  1473. const char* platform = cmdLine.findOption('\0', "platform");
  1474. if (NULL == platform)
  1475. {
  1476. help("Must specify platform.");
  1477. return EXIT_FAILURE;
  1478. }
  1479. bool raw = cmdLine.hasArg('\0', "raw");
  1480. uint32_t gles = 0;
  1481. uint32_t hlsl = 2;
  1482. const char* profile = cmdLine.findOption('p', "profile");
  1483. if (NULL != profile)
  1484. {
  1485. if (0 == strncmp(&profile[1], "s_3", 3) )
  1486. {
  1487. hlsl = 3;
  1488. }
  1489. else if (0 == strncmp(&profile[1], "s_4", 3) )
  1490. {
  1491. hlsl = 4;
  1492. }
  1493. else if (0 == strncmp(&profile[1], "s_5", 3) )
  1494. {
  1495. hlsl = 5;
  1496. }
  1497. }
  1498. else
  1499. {
  1500. gles = 2;
  1501. }
  1502. const char* bin2c = NULL;
  1503. if (cmdLine.hasArg("bin2c") )
  1504. {
  1505. bin2c = cmdLine.findOption("bin2c");
  1506. if (NULL == bin2c)
  1507. {
  1508. bin2c = baseName(outFilePath);
  1509. uint32_t len = (uint32_t)strlen(bin2c);
  1510. char* temp = (char*)alloca(len+1);
  1511. for (char *out = temp; *bin2c != '\0';)
  1512. {
  1513. char ch = *bin2c++;
  1514. if (isalnum(ch) )
  1515. {
  1516. *out++ = ch;
  1517. }
  1518. else
  1519. {
  1520. *out++ = '_';
  1521. }
  1522. }
  1523. temp[len] = '\0';
  1524. bin2c = temp;
  1525. }
  1526. }
  1527. bool depends = cmdLine.hasArg("depends");
  1528. bool preprocessOnly = cmdLine.hasArg("preprocess");
  1529. const char* includeDir = cmdLine.findOption('i');
  1530. Preprocessor preprocessor(filePath, 0 != gles, includeDir);
  1531. std::string dir;
  1532. {
  1533. const char* base = baseName(filePath);
  1534. if (base != filePath)
  1535. {
  1536. dir.assign(filePath, base-filePath);
  1537. preprocessor.addInclude(dir.c_str() );
  1538. }
  1539. }
  1540. preprocessor.setDefaultDefine("BX_PLATFORM_ANDROID");
  1541. preprocessor.setDefaultDefine("BX_PLATFORM_EMSCRIPTEN");
  1542. preprocessor.setDefaultDefine("BX_PLATFORM_IOS");
  1543. preprocessor.setDefaultDefine("BX_PLATFORM_LINUX");
  1544. preprocessor.setDefaultDefine("BX_PLATFORM_NACL");
  1545. preprocessor.setDefaultDefine("BX_PLATFORM_OSX");
  1546. preprocessor.setDefaultDefine("BX_PLATFORM_WINDOWS");
  1547. preprocessor.setDefaultDefine("BX_PLATFORM_XBOX360");
  1548. // preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_ESSL");
  1549. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_GLSL");
  1550. preprocessor.setDefaultDefine("BGFX_SHADER_LANGUAGE_HLSL");
  1551. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_COMPUTE");
  1552. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_FRAGMENT");
  1553. preprocessor.setDefaultDefine("BGFX_SHADER_TYPE_VERTEX");
  1554. bool glsl = false;
  1555. if (0 == bx::stricmp(platform, "android") )
  1556. {
  1557. preprocessor.setDefine("BX_PLATFORM_ANDROID=1");
  1558. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1559. glsl = true;
  1560. }
  1561. else if (0 == bx::stricmp(platform, "asm.js") )
  1562. {
  1563. preprocessor.setDefine("BX_PLATFORM_EMSCRIPTEN=1");
  1564. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1565. glsl = true;
  1566. }
  1567. else if (0 == bx::stricmp(platform, "ios") )
  1568. {
  1569. preprocessor.setDefine("BX_PLATFORM_IOS=1");
  1570. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1571. glsl = true;
  1572. }
  1573. else if (0 == bx::stricmp(platform, "linux") )
  1574. {
  1575. preprocessor.setDefine("BX_PLATFORM_LINUX=1");
  1576. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1577. glsl = true;
  1578. }
  1579. else if (0 == bx::stricmp(platform, "nacl") )
  1580. {
  1581. preprocessor.setDefine("BX_PLATFORM_NACL=1");
  1582. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1583. glsl = true;
  1584. }
  1585. else if (0 == bx::stricmp(platform, "osx") )
  1586. {
  1587. preprocessor.setDefine("BX_PLATFORM_OSX=1");
  1588. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_GLSL=1");
  1589. glsl = true;
  1590. }
  1591. else if (0 == bx::stricmp(platform, "windows") )
  1592. {
  1593. preprocessor.setDefine("BX_PLATFORM_WINDOWS=1");
  1594. char temp[256];
  1595. bx::snprintf(temp, sizeof(temp), "BGFX_SHADER_LANGUAGE_HLSL=%d", hlsl);
  1596. preprocessor.setDefine(temp);
  1597. }
  1598. else if (0 == bx::stricmp(platform, "xbox360") )
  1599. {
  1600. preprocessor.setDefine("BX_PLATFORM_XBOX360=1");
  1601. preprocessor.setDefine("BGFX_SHADER_LANGUAGE_HLSL=3");
  1602. }
  1603. else
  1604. {
  1605. fprintf(stderr, "Unknown platform %s?!", platform);
  1606. return EXIT_FAILURE;
  1607. }
  1608. preprocessor.setDefine("M_PI=3.1415926535897932384626433832795");
  1609. char shaderType = tolower(type[0]);
  1610. switch (shaderType)
  1611. {
  1612. case 'c':
  1613. preprocessor.setDefine("BGFX_SHADER_TYPE_COMPUTE=1");
  1614. break;
  1615. case 'f':
  1616. preprocessor.setDefine("BGFX_SHADER_TYPE_FRAGMENT=1");
  1617. break;
  1618. case 'v':
  1619. preprocessor.setDefine("BGFX_SHADER_TYPE_VERTEX=1");
  1620. break;
  1621. default:
  1622. fprintf(stderr, "Unknown type: %s?!", type);
  1623. return EXIT_FAILURE;
  1624. }
  1625. bool compiled = false;
  1626. FILE* file = fopen(filePath, "r");
  1627. if (NULL != file)
  1628. {
  1629. VaryingMap varyingMap;
  1630. std::string defaultVarying = dir + "varying.def.sc";
  1631. const char* varyingdef = cmdLine.findOption("varyingdef", defaultVarying.c_str() );
  1632. File attribdef(varyingdef);
  1633. const char* parse = attribdef.getData();
  1634. if (NULL != parse
  1635. && *parse != '\0')
  1636. {
  1637. preprocessor.addDependency(varyingdef);
  1638. }
  1639. while (NULL != parse
  1640. && *parse != '\0')
  1641. {
  1642. parse = bx::strws(parse);
  1643. const char* eol = strchr(parse, ';');
  1644. if (NULL != eol)
  1645. {
  1646. const char* precision = NULL;
  1647. const char* interpolation = NULL;
  1648. const char* type = parse;
  1649. if (0 == strncmp(type, "lowp", 4)
  1650. || 0 == strncmp(type, "mediump", 7)
  1651. || 0 == strncmp(type, "highp", 5) )
  1652. {
  1653. precision = type;
  1654. type = parse = bx::strws(bx::strword(parse) );
  1655. }
  1656. if (0 == strncmp(type, "flat", 4)
  1657. || 0 == strncmp(type, "smooth", 6)
  1658. || 0 == strncmp(type, "noperspective", 13) )
  1659. {
  1660. interpolation = type;
  1661. type = parse = bx::strws(bx::strword(parse) );
  1662. }
  1663. const char* name = parse = bx::strws(bx::strword(parse) );
  1664. const char* column = parse = bx::strws(bx::strword(parse) );
  1665. const char* semantics = parse = bx::strws(bx::strnws (parse) );
  1666. const char* assign = parse = bx::strws(bx::strword(parse) );
  1667. const char* init = parse = bx::strws(bx::strnws (parse) );
  1668. if (type < eol
  1669. && name < eol
  1670. && column < eol
  1671. && ':' == *column
  1672. && semantics < eol)
  1673. {
  1674. Varying var;
  1675. if (NULL != precision)
  1676. {
  1677. var.m_precision.assign(precision, bx::strword(precision)-precision);
  1678. }
  1679. if (NULL != interpolation)
  1680. {
  1681. var.m_interpolation.assign(interpolation, bx::strword(interpolation)-interpolation);
  1682. }
  1683. var.m_type.assign(type, bx::strword(type)-type);
  1684. var.m_name.assign(name, bx::strword(name)-name);
  1685. var.m_semantics.assign(semantics, bx::strword(semantics)-semantics);
  1686. if (assign < eol
  1687. && '=' == *assign
  1688. && init < eol)
  1689. {
  1690. var.m_init.assign(init, eol-init);
  1691. }
  1692. varyingMap.insert(std::make_pair(var.m_name, var) );
  1693. }
  1694. parse = bx::strnl(eol);
  1695. }
  1696. }
  1697. InOut shaderInputs;
  1698. InOut shaderOutputs;
  1699. uint32_t inputHash = 0;
  1700. uint32_t outputHash = 0;
  1701. char* data;
  1702. char* input;
  1703. {
  1704. const size_t padding = 16;
  1705. uint32_t size = (uint32_t)fsize(file);
  1706. data = new char[size+padding+1];
  1707. size = (uint32_t)fread(data, 1, size, file);
  1708. // Compiler generates "error X3000: syntax error: unexpected end of file"
  1709. // if input doesn't have empty line at EOF.
  1710. data[size] = '\n';
  1711. memset(&data[size+1], 0, padding);
  1712. fclose(file);
  1713. input = data;
  1714. while (input[0] == '$')
  1715. {
  1716. const char* str = input+1;
  1717. const char* eol = bx::streol(str);
  1718. const char* nl = bx::strnl(eol);
  1719. input = const_cast<char*>(nl);
  1720. if (0 == strncmp(str, "input", 5) )
  1721. {
  1722. str += 5;
  1723. const char* comment = strstr(str, "//");
  1724. eol = NULL != comment && comment < eol ? comment : eol;
  1725. inputHash = parseInOut(shaderInputs, str, eol);
  1726. }
  1727. else if (0 == strncmp(str, "output", 6) )
  1728. {
  1729. str += 6;
  1730. const char* comment = strstr(str, "//");
  1731. eol = NULL != comment && comment < eol ? comment : eol;
  1732. outputHash = parseInOut(shaderOutputs, str, eol);
  1733. }
  1734. else if (0 == strncmp(str, "raw", 3) )
  1735. {
  1736. raw = true;
  1737. str += 3;
  1738. }
  1739. }
  1740. if (!raw)
  1741. {
  1742. // To avoid commented code being recognized as used feature,
  1743. // first preprocess pass is used to strip all comments before
  1744. // substituting code.
  1745. preprocessor.run(input);
  1746. delete [] data;
  1747. size = preprocessor.m_preprocessed.size();
  1748. data = new char[size+padding+1];
  1749. memcpy(data, preprocessor.m_preprocessed.c_str(), size);
  1750. memset(&data[size], 0, padding+1);
  1751. input = data;
  1752. }
  1753. }
  1754. if (raw)
  1755. {
  1756. bx::CrtFileWriter* writer = NULL;
  1757. if (NULL != bin2c)
  1758. {
  1759. writer = new Bin2cWriter(bin2c);
  1760. }
  1761. else
  1762. {
  1763. writer = new bx::CrtFileWriter;
  1764. }
  1765. if (0 != writer->open(outFilePath) )
  1766. {
  1767. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1768. return EXIT_FAILURE;
  1769. }
  1770. uint32_t inputHash = 0;
  1771. uint32_t outputHash = 0;
  1772. if ('f' == shaderType)
  1773. {
  1774. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  1775. bx::write(writer, inputHash);
  1776. }
  1777. else if ('v' == shaderType)
  1778. {
  1779. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  1780. bx::write(writer, outputHash);
  1781. }
  1782. else
  1783. {
  1784. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1785. bx::write(writer, outputHash);
  1786. }
  1787. if (glsl)
  1788. {
  1789. bx::write(writer, uint16_t(0) );
  1790. uint32_t shaderSize = (uint32_t)strlen(input);
  1791. bx::write(writer, shaderSize);
  1792. bx::write(writer, input, shaderSize);
  1793. bx::write(writer, uint8_t(0) );
  1794. compiled = true;
  1795. }
  1796. else
  1797. {
  1798. if (hlsl > 3)
  1799. {
  1800. compiled = compileHLSLShaderDx11(cmdLine, input, writer);
  1801. }
  1802. else
  1803. {
  1804. compiled = compileHLSLShaderDx9(cmdLine, input, writer);
  1805. }
  1806. }
  1807. writer->close();
  1808. delete writer;
  1809. }
  1810. else if ('c' == shaderType) // Compute
  1811. {
  1812. char* entry = strstr(input, "void main()");
  1813. if (NULL == entry)
  1814. {
  1815. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1816. }
  1817. else
  1818. {
  1819. if (glsl)
  1820. {
  1821. }
  1822. else
  1823. {
  1824. preprocessor.writef(
  1825. "#define lowp\n"
  1826. "#define mediump\n"
  1827. "#define highp\n"
  1828. "#define ivec2 int2\n"
  1829. "#define ivec3 int3\n"
  1830. "#define ivec4 int4\n"
  1831. "#define uvec2 uint2\n"
  1832. "#define uvec3 uint3\n"
  1833. "#define uvec4 uint4\n"
  1834. "#define vec2 float2\n"
  1835. "#define vec3 float3\n"
  1836. "#define vec4 float4\n"
  1837. "#define mat2 float2x2\n"
  1838. "#define mat3 float3x3\n"
  1839. "#define mat4 float4x4\n"
  1840. );
  1841. entry[4] = '_';
  1842. preprocessor.writef("#define void_main()");
  1843. preprocessor.writef(" \\\n\tvoid main(");
  1844. uint32_t arg = 0;
  1845. const bool hasLocalInvocationID = NULL != strstr(input, "gl_LocalInvocationID");
  1846. const bool hasLocalInvocationIndex = NULL != strstr(input, "gl_LocalInvocationIndex");
  1847. const bool hasGlobalInvocationID = NULL != strstr(input, "gl_GlobalInvocationID");
  1848. const bool hasWorkGroupID = NULL != strstr(input, "gl_WorkGroupID");
  1849. if (hasLocalInvocationID)
  1850. {
  1851. preprocessor.writef(
  1852. " \\\n\t%sint3 gl_LocalInvocationID : SV_GroupThreadID"
  1853. , arg++ > 0 ? ", " : " "
  1854. );
  1855. }
  1856. if (hasLocalInvocationIndex)
  1857. {
  1858. preprocessor.writef(
  1859. " \\\n\t%sint gl_LocalInvocationIndex : SV_GroupIndex"
  1860. , arg++ > 0 ? ", " : " "
  1861. );
  1862. }
  1863. if (hasGlobalInvocationID)
  1864. {
  1865. preprocessor.writef(
  1866. " \\\n\t%sint3 gl_GlobalInvocationID : SV_DispatchThreadID"
  1867. , arg++ > 0 ? ", " : " "
  1868. );
  1869. }
  1870. if (hasWorkGroupID)
  1871. {
  1872. preprocessor.writef(
  1873. " \\\n\t%sint3 gl_WorkGroupID : SV_GroupID"
  1874. , arg++ > 0 ? ", " : " "
  1875. );
  1876. }
  1877. preprocessor.writef(
  1878. " \\\n\t)\n"
  1879. );
  1880. }
  1881. if (preprocessor.run(input) )
  1882. {
  1883. BX_TRACE("Input file: %s", filePath);
  1884. BX_TRACE("Output file: %s", outFilePath);
  1885. if (preprocessOnly)
  1886. {
  1887. bx::CrtFileWriter writer;
  1888. if (0 != writer.open(outFilePath) )
  1889. {
  1890. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1891. return EXIT_FAILURE;
  1892. }
  1893. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  1894. writer.close();
  1895. return EXIT_SUCCESS;
  1896. }
  1897. {
  1898. bx::CrtFileWriter* writer = NULL;
  1899. if (NULL != bin2c)
  1900. {
  1901. writer = new Bin2cWriter(bin2c);
  1902. }
  1903. else
  1904. {
  1905. writer = new bx::CrtFileWriter;
  1906. }
  1907. if (0 != writer->open(outFilePath) )
  1908. {
  1909. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  1910. return EXIT_FAILURE;
  1911. }
  1912. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  1913. bx::write(writer, outputHash);
  1914. if (glsl)
  1915. {
  1916. std::string code;
  1917. if (gles)
  1918. {
  1919. bx::stringPrintf(code, "#version 310 es\n");
  1920. }
  1921. else
  1922. {
  1923. int32_t version = atoi(profile);
  1924. bx::stringPrintf(code, "#version %d\n", version == 0 ? 430 : version);
  1925. }
  1926. code += preprocessor.m_preprocessed;
  1927. #if 1
  1928. bx::write(writer, uint16_t(0) );
  1929. uint32_t shaderSize = (uint32_t)code.size();
  1930. bx::write(writer, shaderSize);
  1931. bx::write(writer, code.c_str(), shaderSize);
  1932. bx::write(writer, uint8_t(0) );
  1933. compiled = true;
  1934. #else
  1935. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  1936. #endif // 0
  1937. }
  1938. else
  1939. {
  1940. if (hlsl > 3)
  1941. {
  1942. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  1943. }
  1944. else
  1945. {
  1946. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  1947. }
  1948. }
  1949. writer->close();
  1950. delete writer;
  1951. }
  1952. if (compiled)
  1953. {
  1954. if (depends)
  1955. {
  1956. std::string ofp = outFilePath;
  1957. ofp += ".d";
  1958. bx::CrtFileWriter writer;
  1959. if (0 == writer.open(ofp.c_str() ) )
  1960. {
  1961. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  1962. writer.close();
  1963. }
  1964. }
  1965. }
  1966. }
  1967. }
  1968. }
  1969. else // Vertex/Fragment
  1970. {
  1971. char* entry = strstr(input, "void main()");
  1972. if (NULL == entry)
  1973. {
  1974. fprintf(stderr, "Shader entry point 'void main()' is not found.\n");
  1975. }
  1976. else
  1977. {
  1978. if (glsl)
  1979. {
  1980. preprocessor.writef(
  1981. "#define ivec2 vec2\n"
  1982. "#define ivec3 vec3\n"
  1983. "#define ivec4 vec4\n"
  1984. );
  1985. if (0 == gles)
  1986. {
  1987. // bgfx shadow2D/Proj behave like EXT_shadow_samplers
  1988. // not as GLSL language 1.2 specs shadow2D/Proj.
  1989. preprocessor.writef(
  1990. "#define shadow2D(_sampler, _coord) bgfxShadow2D(_sampler, _coord).x\n"
  1991. "#define shadow2DProj(_sampler, _coord) bgfxShadow2DProj(_sampler, _coord).x\n"
  1992. );
  1993. }
  1994. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  1995. {
  1996. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  1997. if (varyingIt != varyingMap.end() )
  1998. {
  1999. const Varying& var = varyingIt->second;
  2000. const char* name = var.m_name.c_str();
  2001. if (0 == strncmp(name, "a_", 2)
  2002. || 0 == strncmp(name, "i_", 2) )
  2003. {
  2004. preprocessor.writef("attribute %s %s %s %s;\n"
  2005. , var.m_precision.c_str()
  2006. , var.m_interpolation.c_str()
  2007. , var.m_type.c_str()
  2008. , name
  2009. );
  2010. }
  2011. else
  2012. {
  2013. preprocessor.writef("%s varying %s %s %s;\n"
  2014. , var.m_interpolation.c_str()
  2015. , var.m_precision.c_str()
  2016. , var.m_type.c_str()
  2017. , name
  2018. );
  2019. }
  2020. }
  2021. }
  2022. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2023. {
  2024. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2025. if (varyingIt != varyingMap.end() )
  2026. {
  2027. const Varying& var = varyingIt->second;
  2028. preprocessor.writef("%s varying %s %s;\n"
  2029. , var.m_interpolation.c_str()
  2030. , var.m_type.c_str()
  2031. , var.m_name.c_str()
  2032. );
  2033. }
  2034. }
  2035. }
  2036. else
  2037. {
  2038. preprocessor.writef(
  2039. "#define lowp\n"
  2040. "#define mediump\n"
  2041. "#define highp\n"
  2042. "#define ivec2 int2\n"
  2043. "#define ivec3 int3\n"
  2044. "#define ivec4 int4\n"
  2045. "#define uvec2 uint2\n"
  2046. "#define uvec3 uint3\n"
  2047. "#define uvec4 uint4\n"
  2048. "#define vec2 float2\n"
  2049. "#define vec3 float3\n"
  2050. "#define vec4 float4\n"
  2051. "#define mat2 float2x2\n"
  2052. "#define mat3 float3x3\n"
  2053. "#define mat4 float4x4\n"
  2054. );
  2055. if (hlsl < 4)
  2056. {
  2057. preprocessor.writef(
  2058. "#define flat\n"
  2059. "#define smooth\n"
  2060. "#define noperspective\n"
  2061. );
  2062. }
  2063. entry[4] = '_';
  2064. if ('f' == shaderType)
  2065. {
  2066. const bool hasFragCoord = NULL != strstr(input, "gl_FragCoord") || hlsl > 3;
  2067. const bool hasFragDepth = NULL != strstr(input, "gl_FragDepth");
  2068. const bool hasFrontFacing = NULL != strstr(input, "gl_FrontFacing");
  2069. const bool hasFragData0 = NULL != strstr(input, "gl_FragData[0]");
  2070. const bool hasFragData1 = NULL != strstr(input, "gl_FragData[1]");
  2071. const bool hasFragData2 = NULL != strstr(input, "gl_FragData[2]");
  2072. const bool hasFragData3 = NULL != strstr(input, "gl_FragData[3]");
  2073. if (!hasFragData0
  2074. && !hasFragData1
  2075. && !hasFragData2
  2076. && !hasFragData3)
  2077. {
  2078. // GL errors when both gl_FragColor and gl_FragData is used.
  2079. // This will trigger the same error with HLSL compiler too.
  2080. preprocessor.writef("#define gl_FragColor gl_FragData_0_\n");
  2081. }
  2082. preprocessor.writef("#define void_main()");
  2083. preprocessor.writef(" \\\n\tvoid main(");
  2084. uint32_t arg = 0;
  2085. if (hasFragCoord)
  2086. {
  2087. preprocessor.writef(" \\\n\tvec4 gl_FragCoord : SV_POSITION");
  2088. ++arg;
  2089. }
  2090. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  2091. {
  2092. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2093. if (varyingIt != varyingMap.end() )
  2094. {
  2095. const Varying& var = varyingIt->second;
  2096. preprocessor.writef(" \\\n\t%s%s %s %s : %s"
  2097. , arg++ > 0 ? ", " : " "
  2098. , interpolationDx11(var.m_interpolation.c_str() )
  2099. , var.m_type.c_str()
  2100. , var.m_name.c_str()
  2101. , var.m_semantics.c_str()
  2102. );
  2103. }
  2104. }
  2105. addFragData(preprocessor, input, 0, arg++ > 0);
  2106. if (hasFragData1)
  2107. {
  2108. addFragData(preprocessor, input, 1, arg++ > 0);
  2109. }
  2110. if (hasFragData2)
  2111. {
  2112. addFragData(preprocessor, input, 2, arg++ > 0);
  2113. }
  2114. if (hasFragData3)
  2115. {
  2116. addFragData(preprocessor, input, 3, arg++ > 0);
  2117. }
  2118. if (hasFragDepth)
  2119. {
  2120. preprocessor.writef(
  2121. " \\\n\t%sout float gl_FragDepth : SV_DEPTH"
  2122. , arg++ > 0 ? ", " : " "
  2123. );
  2124. }
  2125. if (hasFrontFacing)
  2126. {
  2127. preprocessor.writef(
  2128. " \\\n\t%sfloat __vface : VFACE"
  2129. , arg++ > 0 ? ", " : " "
  2130. );
  2131. }
  2132. preprocessor.writef(
  2133. " \\\n\t)\n"
  2134. );
  2135. if (hasFrontFacing)
  2136. {
  2137. preprocessor.writef(
  2138. "#define gl_FrontFacing (__vface <= 0.0)\n"
  2139. );
  2140. }
  2141. }
  2142. else if ('v' == shaderType)
  2143. {
  2144. const char* brace = strstr(entry, "{");
  2145. if (NULL != brace)
  2146. {
  2147. const char* end = bx::strmb(brace, '{', '}');
  2148. if (NULL != end)
  2149. {
  2150. strins(const_cast<char*>(end), "__RETURN__;\n");
  2151. }
  2152. }
  2153. preprocessor.writef(
  2154. "struct Output\n"
  2155. "{\n"
  2156. "\tvec4 gl_Position : SV_POSITION;\n"
  2157. "#define gl_Position _varying_.gl_Position\n"
  2158. );
  2159. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2160. {
  2161. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2162. if (varyingIt != varyingMap.end() )
  2163. {
  2164. const Varying& var = varyingIt->second;
  2165. preprocessor.writef("\t%s %s : %s;\n", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  2166. preprocessor.writef("#define %s _varying_.%s\n", var.m_name.c_str(), var.m_name.c_str() );
  2167. }
  2168. }
  2169. preprocessor.writef(
  2170. "};\n"
  2171. );
  2172. preprocessor.writef("#define void_main() \\\n");
  2173. preprocessor.writef("Output main(");
  2174. bool first = true;
  2175. for (InOut::const_iterator it = shaderInputs.begin(), itEnd = shaderInputs.end(); it != itEnd; ++it)
  2176. {
  2177. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2178. if (varyingIt != varyingMap.end() )
  2179. {
  2180. const Varying& var = varyingIt->second;
  2181. preprocessor.writef("%s%s %s : %s\\\n", first ? "" : "\t, ", var.m_type.c_str(), var.m_name.c_str(), var.m_semantics.c_str() );
  2182. first = false;
  2183. }
  2184. }
  2185. preprocessor.writef(
  2186. ") \\\n"
  2187. "{ \\\n"
  2188. "\tOutput _varying_;"
  2189. );
  2190. for (InOut::const_iterator it = shaderOutputs.begin(), itEnd = shaderOutputs.end(); it != itEnd; ++it)
  2191. {
  2192. VaryingMap::const_iterator varyingIt = varyingMap.find(*it);
  2193. if (varyingIt != varyingMap.end() )
  2194. {
  2195. const Varying& var = varyingIt->second;
  2196. preprocessor.writef(" \\\n\t%s = %s;", var.m_name.c_str(), var.m_init.c_str() );
  2197. }
  2198. }
  2199. preprocessor.writef(
  2200. "\n#define __RETURN__ \\\n"
  2201. "\t} \\\n"
  2202. "\treturn _varying_"
  2203. );
  2204. }
  2205. }
  2206. if (preprocessor.run(input) )
  2207. {
  2208. BX_TRACE("Input file: %s", filePath);
  2209. BX_TRACE("Output file: %s", outFilePath);
  2210. if (preprocessOnly)
  2211. {
  2212. bx::CrtFileWriter writer;
  2213. if (0 != writer.open(outFilePath) )
  2214. {
  2215. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2216. return EXIT_FAILURE;
  2217. }
  2218. if (glsl)
  2219. {
  2220. const char* profile = cmdLine.findOption('p', "profile");
  2221. if (NULL == profile)
  2222. {
  2223. writef(&writer
  2224. , "#ifdef GL_ES\n"
  2225. "precision highp float;\n"
  2226. "#endif // GL_ES\n\n"
  2227. );
  2228. }
  2229. }
  2230. writer.write(preprocessor.m_preprocessed.c_str(), (int32_t)preprocessor.m_preprocessed.size() );
  2231. writer.close();
  2232. return EXIT_SUCCESS;
  2233. }
  2234. {
  2235. bx::CrtFileWriter* writer = NULL;
  2236. if (NULL != bin2c)
  2237. {
  2238. writer = new Bin2cWriter(bin2c);
  2239. }
  2240. else
  2241. {
  2242. writer = new bx::CrtFileWriter;
  2243. }
  2244. if (0 != writer->open(outFilePath) )
  2245. {
  2246. fprintf(stderr, "Unable to open output file '%s'.", outFilePath);
  2247. return EXIT_FAILURE;
  2248. }
  2249. if ('f' == shaderType)
  2250. {
  2251. bx::write(writer, BGFX_CHUNK_MAGIC_FSH);
  2252. bx::write(writer, inputHash);
  2253. }
  2254. else if ('v' == shaderType)
  2255. {
  2256. bx::write(writer, BGFX_CHUNK_MAGIC_VSH);
  2257. bx::write(writer, outputHash);
  2258. }
  2259. else
  2260. {
  2261. bx::write(writer, BGFX_CHUNK_MAGIC_CSH);
  2262. bx::write(writer, outputHash);
  2263. }
  2264. if (glsl)
  2265. {
  2266. std::string code;
  2267. bool hasTextureLod = NULL != bx::findIdentifierMatch(input, s_ARB_shader_texture_lod /*EXT_shader_texture_lod*/);
  2268. if (0 == gles)
  2269. {
  2270. bx::stringPrintf(code, "#version %s\n", profile);
  2271. int32_t version = atoi(profile);
  2272. bx::stringPrintf(code
  2273. , "#define bgfxShadow2D shadow2D\n"
  2274. "#define bgfxShadow2DProj shadow2DProj\n"
  2275. );
  2276. if (hasTextureLod
  2277. && 130 > version)
  2278. {
  2279. bx::stringPrintf(code
  2280. , "#extension GL_ARB_shader_texture_lod : enable\n"
  2281. );
  2282. }
  2283. }
  2284. else
  2285. {
  2286. // Pretend that all extensions are available.
  2287. // This will be stripped later.
  2288. if (hasTextureLod)
  2289. {
  2290. bx::stringPrintf(code
  2291. , "#extension GL_EXT_shader_texture_lod : enable\n"
  2292. "#define texture2DLod texture2DLodEXT\n"
  2293. "#define texture2DProjLod texture2DProjLodEXT\n"
  2294. "#define textureCubeLod textureCubeLodEXT\n"
  2295. // "#define texture2DGrad texture2DGradEXT\n"
  2296. // "#define texture2DProjGrad texture2DProjGradEXT\n"
  2297. // "#define textureCubeGrad textureCubeGradEXT\n"
  2298. );
  2299. }
  2300. if (NULL != bx::findIdentifierMatch(input, s_OES_standard_derivatives) )
  2301. {
  2302. bx::stringPrintf(code, "#extension GL_OES_standard_derivatives : enable\n");
  2303. }
  2304. if (NULL != bx::findIdentifierMatch(input, s_OES_texture_3D) )
  2305. {
  2306. bx::stringPrintf(code, "#extension GL_OES_texture_3D : enable\n");
  2307. }
  2308. if (NULL != bx::findIdentifierMatch(input, s_EXT_shadow_samplers) )
  2309. {
  2310. bx::stringPrintf(code
  2311. , "#extension GL_EXT_shadow_samplers : enable\n"
  2312. "#define shadow2D shadow2DEXT\n"
  2313. "#define shadow2DProj shadow2DProjEXT\n"
  2314. );
  2315. }
  2316. if (NULL != bx::findIdentifierMatch(input, "gl_FragDepth") )
  2317. {
  2318. bx::stringPrintf(code
  2319. , "#extension GL_EXT_frag_depth : enable\n"
  2320. "#define gl_FragDepth gl_FragDepthEXT\n"
  2321. );
  2322. }
  2323. }
  2324. code += preprocessor.m_preprocessed;
  2325. compiled = compileGLSLShader(cmdLine, gles, code, writer);
  2326. }
  2327. else
  2328. {
  2329. if (hlsl > 3)
  2330. {
  2331. compiled = compileHLSLShaderDx11(cmdLine, preprocessor.m_preprocessed, writer);
  2332. }
  2333. else
  2334. {
  2335. compiled = compileHLSLShaderDx9(cmdLine, preprocessor.m_preprocessed, writer);
  2336. }
  2337. }
  2338. writer->close();
  2339. delete writer;
  2340. }
  2341. if (compiled)
  2342. {
  2343. if (depends)
  2344. {
  2345. std::string ofp = outFilePath;
  2346. ofp += ".d";
  2347. bx::CrtFileWriter writer;
  2348. if (0 == writer.open(ofp.c_str() ) )
  2349. {
  2350. writef(&writer, "%s : %s\n", outFilePath, preprocessor.m_depends.c_str() );
  2351. writer.close();
  2352. }
  2353. }
  2354. }
  2355. }
  2356. }
  2357. }
  2358. delete [] data;
  2359. }
  2360. if (compiled)
  2361. {
  2362. return EXIT_SUCCESS;
  2363. }
  2364. remove(outFilePath);
  2365. fprintf(stderr, "Failed to build shader.\n");
  2366. return EXIT_FAILURE;
  2367. }