BsSLFXCompiler.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsSLFXCompiler.h"
  4. #include "RenderAPI/BsGpuProgram.h"
  5. #include <regex>
  6. #include "Material/BsShader.h"
  7. #include "Material/BsTechnique.h"
  8. #include "Material/BsPass.h"
  9. #include "RenderAPI/BsSamplerState.h"
  10. #include "RenderAPI/BsRenderAPI.h"
  11. #include "Debug/BsDebug.h"
  12. #include "Material/BsShaderManager.h"
  13. #include "Material/BsShaderInclude.h"
  14. #include "Math/BsMatrix4.h"
  15. #include "Resources/BsBuiltinResources.h"
  16. #define XSC_ENABLE_LANGUAGE_EXT 1
  17. #include "Xsc/Xsc.h"
  18. #include "Material/BsShaderVariation.h"
  19. extern "C" {
  20. #include "BsMMAlloc.h"
  21. #include "BsParserFX.h"
  22. #include "BsLexerFX.h"
  23. }
  24. using namespace std;
  25. namespace bs
  26. {
  27. // Print out the FX AST, only for debug purposes
  28. void SLFXDebugPrint(ASTFXNode* node, String indent)
  29. {
  30. LOGDBG(indent + "NODE " + toString(node->type));
  31. for (int i = 0; i < node->options->count; i++)
  32. {
  33. OptionDataType odt = OPTION_LOOKUP[(int)node->options->entries[i].type].dataType;
  34. if (odt == ODT_Complex)
  35. {
  36. LOGDBG(indent + toString(i) + ". " + toString(node->options->entries[i].type));
  37. SLFXDebugPrint(node->options->entries[i].value.nodePtr, indent + "\t");
  38. continue;
  39. }
  40. String value;
  41. switch (odt)
  42. {
  43. case ODT_Bool:
  44. value = toString(node->options->entries[i].value.intValue != 0);
  45. break;
  46. case ODT_Int:
  47. value = toString(node->options->entries[i].value.intValue);
  48. break;
  49. case ODT_Float:
  50. value = toString(node->options->entries[i].value.floatValue);
  51. break;
  52. case ODT_String:
  53. value = node->options->entries[i].value.strValue;
  54. break;
  55. case ODT_Matrix:
  56. {
  57. Matrix4 mat4 = *(Matrix4*)(node->options->entries[i].value.matrixValue);
  58. value = toString(mat4);
  59. }
  60. break;
  61. default:
  62. break;
  63. }
  64. LOGDBG(indent + toString(i) + ". " + toString(node->options->entries[i].type) + " = " + value);
  65. }
  66. }
  67. class XscLog : public Xsc::Log
  68. {
  69. public:
  70. void SubmitReport(const Xsc::Report& report) override
  71. {
  72. switch (report.Type())
  73. {
  74. case Xsc::ReportTypes::Info:
  75. mInfos.push_back({ FullIndent(), report });
  76. break;
  77. case Xsc::ReportTypes::Warning:
  78. mWarnings.push_back({ FullIndent(), report });
  79. break;
  80. case Xsc::ReportTypes::Error:
  81. mErrors.push_back({ FullIndent(), report });
  82. break;
  83. }
  84. }
  85. void getMessages(StringStream& output)
  86. {
  87. printAndClearReports(output, mInfos);
  88. printAndClearReports(output, mWarnings, (mWarnings.size() == 1 ? "WARNING" : "WARNINGS"));
  89. printAndClearReports(output, mErrors, (mErrors.size() == 1 ? "ERROR" : "ERRORS"));
  90. }
  91. private:
  92. struct IndentReport
  93. {
  94. std::string indent;
  95. Xsc::Report report;
  96. };
  97. static void printMultiLineString(StringStream& output, const std::string& str, const std::string& indent)
  98. {
  99. // Determine at which position the actual text begins (excluding the "error (X:Y) : " or the like)
  100. auto textStartPos = str.find(" : ");
  101. if (textStartPos != std::string::npos)
  102. textStartPos += 3;
  103. else
  104. textStartPos = 0;
  105. std::string newLineIndent(textStartPos, ' ');
  106. size_t start = 0;
  107. bool useNewLineIndent = false;
  108. while (start < str.size())
  109. {
  110. output << indent;
  111. if (useNewLineIndent)
  112. output << newLineIndent;
  113. // Print next line
  114. auto end = str.find('\n', start);
  115. if (end != std::string::npos)
  116. {
  117. output << str.substr(start, end - start);
  118. start = end + 1;
  119. }
  120. else
  121. {
  122. output << str.substr(start);
  123. start = end;
  124. }
  125. output << std::endl;
  126. useNewLineIndent = true;
  127. }
  128. }
  129. void printReport(StringStream& output, const IndentReport& r)
  130. {
  131. // Print optional context description
  132. if (!r.report.Context().empty())
  133. printMultiLineString(output, r.report.Context(), r.indent);
  134. // Print report message
  135. const auto& msg = r.report.Message();
  136. printMultiLineString(output, msg, r.indent);
  137. // Print optional line and line-marker
  138. if (r.report.HasLine())
  139. {
  140. const auto& line = r.report.Line();
  141. const auto& marker = r.report.Marker();
  142. // Print line
  143. output << r.indent << line << std::endl;
  144. // Print line marker
  145. output << r.indent << marker << std::endl;
  146. }
  147. // Print optional hints
  148. for (const auto& hint : r.report.GetHints())
  149. output << r.indent << hint << std::endl;
  150. }
  151. void printAndClearReports(StringStream& output, Vector<IndentReport>& reports, const String& headline = "")
  152. {
  153. if (!reports.empty())
  154. {
  155. if (!headline.empty())
  156. {
  157. String s = toString((UINT32)reports.size()) + " " + headline;
  158. output << s << std::endl;
  159. output << String(s.size(), '-') << std::endl;
  160. }
  161. for (const auto& r : reports)
  162. printReport(output, r);
  163. reports.clear();
  164. }
  165. }
  166. Vector<IndentReport> mInfos;
  167. Vector<IndentReport> mWarnings;
  168. Vector<IndentReport> mErrors;
  169. };
  170. GpuParamObjectType ReflTypeToTextureType(Xsc::Reflection::BufferType type)
  171. {
  172. switch(type)
  173. {
  174. case Xsc::Reflection::BufferType::RWTexture1D: return GPOT_RWTEXTURE1D;
  175. case Xsc::Reflection::BufferType::RWTexture1DArray: return GPOT_RWTEXTURE1DARRAY;
  176. case Xsc::Reflection::BufferType::RWTexture2D: return GPOT_RWTEXTURE2D;
  177. case Xsc::Reflection::BufferType::RWTexture2DArray: return GPOT_RWTEXTURE2DARRAY;
  178. case Xsc::Reflection::BufferType::RWTexture3D: return GPOT_RWTEXTURE3D;
  179. case Xsc::Reflection::BufferType::Texture1D: return GPOT_TEXTURE1D;
  180. case Xsc::Reflection::BufferType::Texture1DArray: return GPOT_TEXTURE1DARRAY;
  181. case Xsc::Reflection::BufferType::Texture2D: return GPOT_TEXTURE2D;
  182. case Xsc::Reflection::BufferType::Texture2DArray: return GPOT_TEXTURE2DARRAY;
  183. case Xsc::Reflection::BufferType::Texture3D: return GPOT_TEXTURE3D;
  184. case Xsc::Reflection::BufferType::TextureCube: return GPOT_TEXTURECUBE;
  185. case Xsc::Reflection::BufferType::TextureCubeArray: return GPOT_TEXTURECUBEARRAY;
  186. case Xsc::Reflection::BufferType::Texture2DMS: return GPOT_TEXTURE2DMS;
  187. case Xsc::Reflection::BufferType::Texture2DMSArray: return GPOT_TEXTURE2DMSARRAY;
  188. default: return GPOT_UNKNOWN;
  189. }
  190. }
  191. GpuParamObjectType ReflTypeToBufferType(Xsc::Reflection::BufferType type)
  192. {
  193. switch(type)
  194. {
  195. case Xsc::Reflection::BufferType::Buffer: return GPOT_RWTYPED_BUFFER;
  196. case Xsc::Reflection::BufferType::StructuredBuffer: return GPOT_STRUCTURED_BUFFER;
  197. case Xsc::Reflection::BufferType::ByteAddressBuffer: return GPOT_BYTE_BUFFER;
  198. case Xsc::Reflection::BufferType::RWBuffer: return GPOT_RWTYPED_BUFFER;
  199. case Xsc::Reflection::BufferType::RWStructuredBuffer: return GPOT_RWSTRUCTURED_BUFFER;
  200. case Xsc::Reflection::BufferType::RWByteAddressBuffer: return GPOT_RWBYTE_BUFFER;
  201. case Xsc::Reflection::BufferType::AppendStructuredBuffer: return GPOT_RWAPPEND_BUFFER;
  202. case Xsc::Reflection::BufferType::ConsumeStructuredBuffer: return GPOT_RWCONSUME_BUFFER;
  203. default: return GPOT_UNKNOWN;
  204. }
  205. }
  206. GpuParamDataType ReflTypeToDataType(Xsc::Reflection::DataType type)
  207. {
  208. switch (type)
  209. {
  210. case Xsc::Reflection::DataType::Bool: return GPDT_BOOL;
  211. case Xsc::Reflection::DataType::Float: return GPDT_FLOAT1;
  212. case Xsc::Reflection::DataType::Float2: return GPDT_FLOAT2;
  213. case Xsc::Reflection::DataType::Float3: return GPDT_FLOAT3;
  214. case Xsc::Reflection::DataType::Float4: return GPDT_FLOAT4;
  215. case Xsc::Reflection::DataType::UInt:
  216. case Xsc::Reflection::DataType::Int:
  217. return GPDT_INT1;
  218. case Xsc::Reflection::DataType::UInt2:
  219. case Xsc::Reflection::DataType::Int2:
  220. return GPDT_INT2;
  221. case Xsc::Reflection::DataType::UInt3:
  222. case Xsc::Reflection::DataType::Int3:
  223. return GPDT_INT3;
  224. case Xsc::Reflection::DataType::UInt4:
  225. case Xsc::Reflection::DataType::Int4:
  226. return GPDT_INT4;
  227. case Xsc::Reflection::DataType::Float2x2: return GPDT_MATRIX_2X2;
  228. case Xsc::Reflection::DataType::Float2x3: return GPDT_MATRIX_2X3;
  229. case Xsc::Reflection::DataType::Float2x4: return GPDT_MATRIX_2X4;
  230. case Xsc::Reflection::DataType::Float3x2: return GPDT_MATRIX_3X4;
  231. case Xsc::Reflection::DataType::Float3x3: return GPDT_MATRIX_3X3;
  232. case Xsc::Reflection::DataType::Float3x4: return GPDT_MATRIX_3X4;
  233. case Xsc::Reflection::DataType::Float4x2: return GPDT_MATRIX_4X2;
  234. case Xsc::Reflection::DataType::Float4x3: return GPDT_MATRIX_4X3;
  235. case Xsc::Reflection::DataType::Float4x4: return GPDT_MATRIX_4X4;
  236. default: return GPDT_UNKNOWN;
  237. }
  238. }
  239. HTexture getBuiltinTexture(UINT32 idx)
  240. {
  241. if (idx == 1)
  242. return BuiltinResources::getTexture(BuiltinTexture::White);
  243. else if (idx == 2)
  244. return BuiltinResources::getTexture(BuiltinTexture::Black);
  245. else if (idx == 3)
  246. return BuiltinResources::getTexture(BuiltinTexture::Normal);
  247. return HTexture();
  248. }
  249. TextureAddressingMode parseTexAddrMode(Xsc::Reflection::TextureAddressMode addrMode)
  250. {
  251. switch (addrMode)
  252. {
  253. case Xsc::Reflection::TextureAddressMode::Border:
  254. return TAM_BORDER;
  255. case Xsc::Reflection::TextureAddressMode::Clamp:
  256. return TAM_CLAMP;
  257. case Xsc::Reflection::TextureAddressMode::Mirror:
  258. case Xsc::Reflection::TextureAddressMode::MirrorOnce:
  259. return TAM_MIRROR;
  260. case Xsc::Reflection::TextureAddressMode::Wrap:
  261. default:
  262. return TAM_WRAP;
  263. }
  264. }
  265. CompareFunction parseCompFunction(Xsc::Reflection::ComparisonFunc compFunc)
  266. {
  267. switch(compFunc)
  268. {
  269. case Xsc::Reflection::ComparisonFunc::Always:
  270. default:
  271. return CMPF_ALWAYS_PASS;
  272. case Xsc::Reflection::ComparisonFunc::Never:
  273. return CMPF_ALWAYS_FAIL;
  274. case Xsc::Reflection::ComparisonFunc::Equal:
  275. return CMPF_EQUAL;
  276. case Xsc::Reflection::ComparisonFunc::Greater:
  277. return CMPF_GREATER;
  278. case Xsc::Reflection::ComparisonFunc::GreaterEqual:
  279. return CMPF_GREATER_EQUAL;
  280. case Xsc::Reflection::ComparisonFunc::Less:
  281. return CMPF_LESS;
  282. case Xsc::Reflection::ComparisonFunc::LessEqual:
  283. return CMPF_LESS_EQUAL;
  284. case Xsc::Reflection::ComparisonFunc::NotEqual:
  285. return CMPF_NOT_EQUAL;
  286. }
  287. }
  288. SPtr<SamplerState> parseSamplerState(const Xsc::Reflection::SamplerState& sampState)
  289. {
  290. SAMPLER_STATE_DESC desc;
  291. desc.addressMode.u = parseTexAddrMode(sampState.addressU);
  292. desc.addressMode.v = parseTexAddrMode(sampState.addressV);
  293. desc.addressMode.w = parseTexAddrMode(sampState.addressW);
  294. desc.borderColor[0] = sampState.borderColor[0];
  295. desc.borderColor[1] = sampState.borderColor[1];
  296. desc.borderColor[2] = sampState.borderColor[2];
  297. desc.borderColor[3] = sampState.borderColor[3];
  298. desc.comparisonFunc = parseCompFunction(sampState.comparisonFunc);
  299. desc.maxAniso = sampState.maxAnisotropy;
  300. desc.mipMax = sampState.maxLOD;
  301. desc.mipMin = sampState.minLOD;
  302. desc.mipmapBias = sampState.mipLODBias;
  303. switch (sampState.filter)
  304. {
  305. case Xsc::Reflection::Filter::MinMagMipPoint:
  306. case Xsc::Reflection::Filter::ComparisonMinMagMipPoint:
  307. desc.minFilter = FO_POINT;
  308. desc.magFilter = FO_POINT;
  309. desc.mipFilter = FO_POINT;
  310. break;
  311. case Xsc::Reflection::Filter::MinMagPointMipLinear:
  312. case Xsc::Reflection::Filter::ComparisonMinMagPointMipLinear:
  313. desc.minFilter = FO_POINT;
  314. desc.magFilter = FO_POINT;
  315. desc.mipFilter = FO_LINEAR;
  316. break;
  317. case Xsc::Reflection::Filter::MinPointMagLinearMipPoint:
  318. case Xsc::Reflection::Filter::ComparisonMinPointMagLinearMipPoint:
  319. desc.minFilter = FO_POINT;
  320. desc.magFilter = FO_LINEAR;
  321. desc.mipFilter = FO_POINT;
  322. break;
  323. case Xsc::Reflection::Filter::MinPointMagMipLinear:
  324. case Xsc::Reflection::Filter::ComparisonMinPointMagMipLinear:
  325. desc.minFilter = FO_POINT;
  326. desc.magFilter = FO_LINEAR;
  327. desc.mipFilter = FO_LINEAR;
  328. break;
  329. case Xsc::Reflection::Filter::MinLinearMagMipPoint:
  330. case Xsc::Reflection::Filter::ComparisonMinLinearMagMipPoint:
  331. desc.minFilter = FO_LINEAR;
  332. desc.magFilter = FO_POINT;
  333. desc.mipFilter = FO_POINT;
  334. break;
  335. case Xsc::Reflection::Filter::MinLinearMagPointMipLinear:
  336. case Xsc::Reflection::Filter::ComparisonMinLinearMagPointMipLinear:
  337. desc.minFilter = FO_LINEAR;
  338. desc.magFilter = FO_POINT;
  339. desc.mipFilter = FO_LINEAR;
  340. break;
  341. case Xsc::Reflection::Filter::MinMagLinearMipPoint:
  342. case Xsc::Reflection::Filter::ComparisonMinMagLinearMipPoint:
  343. desc.minFilter = FO_LINEAR;
  344. desc.magFilter = FO_LINEAR;
  345. desc.mipFilter = FO_POINT;
  346. break;
  347. case Xsc::Reflection::Filter::MinMagMipLinear:
  348. case Xsc::Reflection::Filter::ComparisonMinMagMipLinear:
  349. desc.minFilter = FO_LINEAR;
  350. desc.magFilter = FO_LINEAR;
  351. desc.mipFilter = FO_LINEAR;
  352. break;
  353. case Xsc::Reflection::Filter::Anisotropic:
  354. case Xsc::Reflection::Filter::ComparisonAnisotropic:
  355. desc.minFilter = FO_ANISOTROPIC;
  356. desc.magFilter = FO_ANISOTROPIC;
  357. desc.minFilter = FO_ANISOTROPIC;
  358. break;
  359. default:
  360. break;
  361. }
  362. return SamplerState::create(desc);
  363. }
  364. void parseParameters(const Xsc::Reflection::ReflectionData& reflData, SHADER_DESC& desc)
  365. {
  366. for(auto& entry : reflData.uniforms)
  367. {
  368. if ((entry.flags & Xsc::Reflection::Uniform::Flags::Internal) != 0)
  369. continue;
  370. String ident = entry.ident.c_str();
  371. switch(entry.type)
  372. {
  373. case Xsc::Reflection::UniformType::UniformBuffer:
  374. desc.setParamBlockAttribs(entry.ident.c_str(), false, GPBU_STATIC);
  375. break;
  376. case Xsc::Reflection::UniformType::Buffer:
  377. {
  378. GpuParamObjectType objType = ReflTypeToTextureType((Xsc::Reflection::BufferType)entry.baseType);
  379. if(objType != GPOT_UNKNOWN)
  380. {
  381. if (entry.defaultValue == -1)
  382. desc.addParameter(ident, ident, objType);
  383. else
  384. desc.addParameter(ident, ident, objType, getBuiltinTexture(entry.defaultValue));
  385. }
  386. else
  387. {
  388. objType = ReflTypeToBufferType((Xsc::Reflection::BufferType)entry.baseType);
  389. desc.addParameter(ident, ident, objType);
  390. }
  391. }
  392. break;
  393. case Xsc::Reflection::UniformType::Sampler:
  394. {
  395. auto findIter = reflData.samplerStates.find(entry.ident);
  396. if (findIter != reflData.samplerStates.end())
  397. {
  398. String alias = findIter->second.alias.c_str();
  399. if(findIter->second.isNonDefault)
  400. {
  401. SPtr<SamplerState> defaultVal = parseSamplerState(findIter->second);
  402. desc.addParameter(ident, ident, GPOT_SAMPLER2D, defaultVal);
  403. if (!alias.empty())
  404. desc.addParameter(ident, alias, GPOT_SAMPLER2D, defaultVal);
  405. }
  406. else
  407. {
  408. desc.addParameter(ident, ident, GPOT_SAMPLER2D);
  409. if (!alias.empty())
  410. desc.addParameter(ident, alias, GPOT_SAMPLER2D);
  411. }
  412. }
  413. else
  414. {
  415. desc.addParameter(ident, ident, GPOT_SAMPLER2D);
  416. }
  417. break;
  418. }
  419. case Xsc::Reflection::UniformType::Variable:
  420. {
  421. bool isBlockInternal = false;
  422. if(entry.uniformBlock != -1)
  423. {
  424. std::string blockName = reflData.constantBuffers[entry.uniformBlock].ident;
  425. for (auto& uniform : reflData.uniforms)
  426. {
  427. if (uniform.type == Xsc::Reflection::UniformType::UniformBuffer && uniform.ident == blockName)
  428. {
  429. isBlockInternal = (uniform.flags & Xsc::Reflection::Uniform::Flags::Internal) != 0;
  430. break;
  431. }
  432. }
  433. }
  434. if (!isBlockInternal)
  435. {
  436. GpuParamDataType type = ReflTypeToDataType((Xsc::Reflection::DataType)entry.baseType);
  437. if ((entry.flags & Xsc::Reflection::Uniform::Flags::Color) != 0 &&
  438. (type == GPDT_FLOAT3 || type == GPDT_FLOAT4))
  439. {
  440. type = GPDT_COLOR;
  441. }
  442. if (entry.defaultValue == -1)
  443. desc.addParameter(ident, ident, type);
  444. else
  445. {
  446. const Xsc::Reflection::DefaultValue& defVal = reflData.defaultValues[entry.defaultValue];
  447. desc.addParameter(ident, ident, type, StringID::NONE, 1, 0, (UINT8*)defVal.matrix);
  448. }
  449. }
  450. }
  451. break;
  452. case Xsc::Reflection::UniformType::Struct: break;
  453. default: ;
  454. }
  455. }
  456. }
  457. String crossCompile(const String& hlsl, GpuProgramType type, bool vulkan, bool optionalEntry, UINT32& startBindingSlot,
  458. SHADER_DESC* shaderDesc = nullptr, Vector<GpuProgramType>* detectedTypes = nullptr)
  459. {
  460. SPtr<StringStream> input = bs_shared_ptr_new<StringStream>();
  461. if (vulkan)
  462. *input << "#define VULKAN 1" << std::endl;
  463. else
  464. *input << "#define OPENGL 1" << std::endl;
  465. *input << hlsl;
  466. Xsc::ShaderInput inputDesc;
  467. inputDesc.shaderVersion = Xsc::InputShaderVersion::HLSL5;
  468. inputDesc.sourceCode = input;
  469. inputDesc.extensions = Xsc::Extensions::LayoutAttribute;
  470. switch (type)
  471. {
  472. case GPT_VERTEX_PROGRAM:
  473. inputDesc.shaderTarget = Xsc::ShaderTarget::VertexShader;
  474. inputDesc.entryPoint = "vsmain";
  475. break;
  476. case GPT_GEOMETRY_PROGRAM:
  477. inputDesc.shaderTarget = Xsc::ShaderTarget::GeometryShader;
  478. inputDesc.entryPoint = "gsmain";
  479. break;
  480. case GPT_HULL_PROGRAM:
  481. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationControlShader;
  482. inputDesc.entryPoint = "hsmain";
  483. break;
  484. case GPT_DOMAIN_PROGRAM:
  485. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationEvaluationShader;
  486. inputDesc.entryPoint = "dsmain";
  487. break;
  488. case GPT_FRAGMENT_PROGRAM:
  489. inputDesc.shaderTarget = Xsc::ShaderTarget::FragmentShader;
  490. inputDesc.entryPoint = "fsmain";
  491. break;
  492. case GPT_COMPUTE_PROGRAM:
  493. inputDesc.shaderTarget = Xsc::ShaderTarget::ComputeShader;
  494. inputDesc.entryPoint = "csmain";
  495. break;
  496. default:
  497. break;
  498. }
  499. StringStream output;
  500. Xsc::ShaderOutput outputDesc;
  501. outputDesc.sourceCode = &output;
  502. outputDesc.options.autoBinding = vulkan;
  503. outputDesc.options.autoBindingStartSlot = startBindingSlot;
  504. outputDesc.options.separateShaders = true;
  505. outputDesc.options.separateSamplers = false;
  506. outputDesc.nameMangling.inputPrefix = "bs_";
  507. outputDesc.nameMangling.outputPrefix = "bs_";
  508. outputDesc.nameMangling.useAlwaysSemantics = true;
  509. outputDesc.nameMangling.renameBufferFields = true;
  510. if (vulkan)
  511. outputDesc.shaderVersion = Xsc::OutputShaderVersion::VKSL450;
  512. else
  513. outputDesc.shaderVersion = Xsc::OutputShaderVersion::GLSL450;
  514. XscLog log;
  515. Xsc::Reflection::ReflectionData reflectionData;
  516. bool compileSuccess = Xsc::CompileShader(inputDesc, outputDesc, &log, &reflectionData);
  517. if (!compileSuccess)
  518. {
  519. // If enabled, don't fail if entry point isn't found
  520. bool done = true;
  521. if(optionalEntry)
  522. {
  523. bool entryFound = false;
  524. for (auto& entry : reflectionData.functions)
  525. {
  526. if(entry.ident == inputDesc.entryPoint)
  527. {
  528. entryFound = true;
  529. break;
  530. }
  531. }
  532. if (!entryFound)
  533. done = false;
  534. }
  535. if (done)
  536. {
  537. StringStream logOutput;
  538. log.getMessages(logOutput);
  539. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  540. return "";
  541. }
  542. }
  543. for (auto& entry : reflectionData.constantBuffers)
  544. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  545. for (auto& entry : reflectionData.textures)
  546. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  547. for (auto& entry : reflectionData.storageBuffers)
  548. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  549. if(detectedTypes != nullptr)
  550. {
  551. for(auto& entry : reflectionData.functions)
  552. {
  553. if (entry.ident == "vsmain")
  554. detectedTypes->push_back(GPT_VERTEX_PROGRAM);
  555. else if (entry.ident == "fsmain")
  556. detectedTypes->push_back(GPT_FRAGMENT_PROGRAM);
  557. else if (entry.ident == "gsmain")
  558. detectedTypes->push_back(GPT_GEOMETRY_PROGRAM);
  559. else if (entry.ident == "dsmain")
  560. detectedTypes->push_back(GPT_DOMAIN_PROGRAM);
  561. else if (entry.ident == "hsmain")
  562. detectedTypes->push_back(GPT_HULL_PROGRAM);
  563. else if (entry.ident == "csmain")
  564. detectedTypes->push_back(GPT_COMPUTE_PROGRAM);
  565. }
  566. // If no entry points found, and error occurred, report error
  567. if(!compileSuccess && detectedTypes->size() == 0)
  568. {
  569. StringStream logOutput;
  570. log.getMessages(logOutput);
  571. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  572. return "";
  573. }
  574. }
  575. if (shaderDesc != nullptr)
  576. parseParameters(reflectionData, *shaderDesc);
  577. return output.str();
  578. }
  579. // Convert HLSL code to GLSL
  580. String HLSLtoGLSL(const String& hlsl, GpuProgramType type, bool vulkan, UINT32& startBindingSlot)
  581. {
  582. return crossCompile(hlsl, type, vulkan, false, startBindingSlot);
  583. }
  584. void reflectHLSL(const String& hlsl, SHADER_DESC& shaderDesc, Vector<GpuProgramType>& entryPoints)
  585. {
  586. UINT32 dummy = 0;
  587. crossCompile(hlsl, GPT_VERTEX_PROGRAM, false, true, dummy, &shaderDesc, &entryPoints);
  588. }
  589. BSLFXCompileResult BSLFXCompiler::compile(const String& name, const String& source,
  590. const UnorderedMap<String, String>& defines)
  591. {
  592. String parsedSource = source;
  593. // Run the lexer/parser and generate the AST
  594. ParseState* parseState = parseStateCreate();
  595. BSLFXCompileResult output = parseFX(parseState, parsedSource.c_str(), defines);
  596. if(!output.errorMessage.empty())
  597. parseStateDelete(parseState);
  598. else
  599. {
  600. // Only enable for debug purposes
  601. //SLFXDebugPrint(parseState->rootNode, "");
  602. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  603. {
  604. parseStateDelete(parseState);
  605. output.errorMessage = "Root not is null or not a shader.";
  606. return output;
  607. }
  608. // Parse global shader options & technique meta-data
  609. SHADER_DESC shaderDesc;
  610. Vector<pair<ASTFXNode*, TechniqueMetaData>> techniqueMetaData;
  611. //// Go in reverse because options are added in reverse order during parsing
  612. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  613. {
  614. NodeOption* option = &parseState->rootNode->options->entries[i];
  615. switch (option->type)
  616. {
  617. case OT_Options:
  618. parseOptions(option->value.nodePtr, shaderDesc);
  619. break;
  620. case OT_Technique:
  621. {
  622. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  623. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  624. techniqueMetaData.push_back(std::make_pair(option->value.nodePtr, metaData));
  625. break;
  626. }
  627. default:
  628. break;
  629. }
  630. }
  631. // Inherit variations from mixins
  632. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueMetaData.size());
  633. std::function<bool(const TechniqueMetaData&, TechniqueMetaData&)> parseInherited =
  634. [&](const TechniqueMetaData& metaData, TechniqueMetaData& combinedMetaData)
  635. {
  636. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  637. {
  638. const String& includes = *riter;
  639. UINT32 baseIdx = -1;
  640. for (UINT32 i = 0; i < (UINT32)techniqueMetaData.size(); i++)
  641. {
  642. auto& entry = techniqueMetaData[i];
  643. if (!entry.second.isMixin)
  644. continue;
  645. if (entry.second.name == includes)
  646. {
  647. bool matches =
  648. (entry.second.language == metaData.language ||
  649. entry.second.language == "Any") &&
  650. (entry.second.renderer == metaData.renderer ||
  651. entry.second.renderer == RendererAny);
  652. // We want the last matching technique, in order to allow techniques to override each other
  653. if (matches)
  654. baseIdx = i;
  655. }
  656. }
  657. if (baseIdx != (UINT32)-1)
  658. {
  659. auto& entry = techniqueMetaData[baseIdx];
  660. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  661. // include the same mixin)
  662. if (techniqueWasParsed[baseIdx])
  663. continue;
  664. if (!parseInherited(entry.second, combinedMetaData))
  665. return false;
  666. for(auto& variation : entry.second.variations)
  667. combinedMetaData.variations.push_back(variation);
  668. techniqueWasParsed[baseIdx] = true;
  669. }
  670. else
  671. {
  672. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  673. return false;
  674. }
  675. }
  676. return true;
  677. };
  678. for (auto& entry : techniqueMetaData)
  679. {
  680. TechniqueMetaData& metaData = entry.second;
  681. if (metaData.isMixin)
  682. continue;
  683. bs_zero_out(techniqueWasParsed, techniqueMetaData.size());
  684. TechniqueMetaData combinedMetaData = metaData;
  685. if (!parseInherited(metaData, combinedMetaData))
  686. {
  687. parseStateDelete(parseState);
  688. bs_stack_free(techniqueWasParsed);
  689. return output;
  690. }
  691. entry.second = combinedMetaData;
  692. }
  693. bs_stack_free(techniqueWasParsed);
  694. parseStateDelete(parseState);
  695. // Build a list of different variations and re-parse the source using the relevant defines
  696. Vector<SPtr<Technique>> techniques;
  697. UnorderedSet<String> includes;
  698. for (auto& entry : techniqueMetaData)
  699. {
  700. TechniqueMetaData& metaData = entry.second;
  701. if (metaData.isMixin)
  702. continue;
  703. // Generate a list of variations
  704. Vector<ShaderVariation> variations;
  705. if (metaData.variations.empty())
  706. variations.push_back(ShaderVariation());
  707. else
  708. {
  709. Vector<const VariationData*> todo;
  710. for (UINT32 i = 0; i < (UINT32)metaData.variations.size(); i++)
  711. todo.push_back(&metaData.variations[i]);
  712. while (!todo.empty())
  713. {
  714. const VariationData* current = todo.back();
  715. todo.erase(todo.end() - 1);
  716. // Variation parameter that's either defined or isn't
  717. if (current->values.empty())
  718. {
  719. // This is the first variation parameter, register new variations
  720. if (variations.empty())
  721. {
  722. ShaderVariation a;
  723. ShaderVariation b;
  724. b.addParam(ShaderVariation::Param(current->identifier, 1));
  725. variations.push_back(a);
  726. variations.push_back(b);
  727. }
  728. else // Duplicate existing variations, and add the parameter
  729. {
  730. UINT32 numVariations = (UINT32)variations.size();
  731. for (UINT32 i = 0; i < numVariations; i++)
  732. {
  733. // Make a copy
  734. variations.push_back(variations[i]);
  735. // Add the parameter to existing variation
  736. variations[i].addParam(ShaderVariation::Param(current->identifier, 1));
  737. }
  738. }
  739. }
  740. else // Variation parameter with multiple values
  741. {
  742. // This is the first variation parameter, register new variations
  743. if (variations.empty())
  744. {
  745. for (UINT32 i = 0; i < (UINT32)current->values.size(); i++)
  746. {
  747. ShaderVariation variation;
  748. variation.addParam(ShaderVariation::Param(current->identifier, current->values[i]));
  749. variations.push_back(variation);
  750. }
  751. }
  752. else // Duplicate existing variations, and add the parameter
  753. {
  754. UINT32 numVariations = (UINT32)variations.size();
  755. for (UINT32 i = 0; i < numVariations; i++)
  756. {
  757. for (UINT32 j = 1; j < (UINT32)current->values.size(); j++)
  758. {
  759. ShaderVariation copy = variations[i];
  760. copy.addParam(ShaderVariation::Param(current->identifier, current->values[j]));
  761. variations.push_back(copy);
  762. }
  763. variations[i].addParam(ShaderVariation::Param(current->identifier, current->values[0]));
  764. }
  765. }
  766. }
  767. }
  768. }
  769. // For every variation, re-parse the file with relevant defines
  770. for(auto& variation : variations)
  771. {
  772. UnorderedMap<String, String> globalDefines = defines;
  773. UnorderedMap<String, String> variationDefines = variation.getDefines().getAll();
  774. for(auto& define : variationDefines)
  775. globalDefines[define.first] = define.second;
  776. ParseState* variationParseState = parseStateCreate();
  777. output = parseFX(variationParseState, parsedSource.c_str(), globalDefines);
  778. if (!output.errorMessage.empty())
  779. parseStateDelete(variationParseState);
  780. else
  781. {
  782. Vector<String> codeBlocks;
  783. CodeString* codeString = variationParseState->codeStrings;
  784. while (codeString != nullptr)
  785. {
  786. while ((INT32)codeBlocks.size() <= codeString->index)
  787. codeBlocks.push_back(String());
  788. codeBlocks[codeString->index] = String(codeString->code, codeString->size);
  789. codeString = codeString->next;
  790. }
  791. output = parseTechniques(variationParseState, codeBlocks, variation, techniques, includes,
  792. shaderDesc);
  793. if(!output.errorMessage.empty())
  794. return output;
  795. }
  796. }
  797. }
  798. // Generate a shader from the parsed techniques
  799. Vector<String> includeArray;
  800. for (auto& entry : includes)
  801. includeArray.push_back(entry);
  802. output.shader = Shader::_createPtr(name, shaderDesc, techniques);
  803. output.shader->setIncludeFiles(includeArray);
  804. // Verify GPU programs compile correctly
  805. StringStream gpuProgError;
  806. bool hasError = false;
  807. if (output.shader != nullptr)
  808. {
  809. Vector<SPtr<Technique>> techniques = output.shader->getCompatibleTechniques();
  810. for (auto& technique : techniques)
  811. {
  812. UINT32 numPasses = technique->getNumPasses();
  813. for (UINT32 i = 0; i < numPasses; i++)
  814. {
  815. SPtr<Pass> pass = technique->getPass(i);
  816. auto checkCompileStatus = [&](const String& prefix, const SPtr<GpuProgram>& prog)
  817. {
  818. if (prog != nullptr)
  819. {
  820. prog->blockUntilCoreInitialized();
  821. if (!prog->isCompiled())
  822. {
  823. hasError = true;
  824. gpuProgError << prefix << ": " << prog->getCompileErrorMessage() << std::endl;
  825. }
  826. }
  827. };
  828. checkCompileStatus("Vertex program", pass->getVertexProgram());
  829. checkCompileStatus("Fragment program", pass->getFragmentProgram());
  830. checkCompileStatus("Geometry program", pass->getGeometryProgram());
  831. checkCompileStatus("Hull program", pass->getHullProgram());
  832. checkCompileStatus("Domain program", pass->getDomainProgram());
  833. checkCompileStatus("Compute program", pass->getComputeProgram());
  834. }
  835. }
  836. }
  837. if (hasError)
  838. {
  839. output.errorMessage = "Failed compiling GPU program(s): " + gpuProgError.str();
  840. output.errorLine = 0;
  841. output.errorColumn = 0;
  842. }
  843. }
  844. return output;
  845. }
  846. BSLFXCompileResult BSLFXCompiler::parseFX(ParseState* parseState, const char* source, const UnorderedMap<String, String>& defines)
  847. {
  848. for(auto& define : defines)
  849. {
  850. if (define.first.size() == 0)
  851. continue;
  852. addDefine(parseState, define.first.c_str());
  853. if(define.second.size() > 0)
  854. addDefineExpr(parseState, define.second.c_str());
  855. }
  856. yyscan_t scanner;
  857. YY_BUFFER_STATE state;
  858. BSLFXCompileResult output;
  859. if (yylex_init_extra(parseState, &scanner))
  860. {
  861. output.errorMessage = "Internal error: Lexer failed to initialize.";
  862. return output;
  863. }
  864. // If debug output from lexer is needed uncomment this and add %debug option to lexer file
  865. //yyset_debug(true, scanner);
  866. // If debug output from parser is needed uncomment this and add %debug option to parser file
  867. //yydebug = true;
  868. state = yy_scan_string(source, scanner);
  869. if (yyparse(parseState, scanner))
  870. {
  871. if (parseState->hasError > 0)
  872. {
  873. output.errorMessage = parseState->errorMessage;
  874. output.errorLine = parseState->errorLine;
  875. output.errorColumn = parseState->errorColumn;
  876. if (parseState->errorFile != nullptr)
  877. output.errorFile = parseState->errorFile;
  878. }
  879. else
  880. output.errorMessage = "Internal error: Parsing failed.";
  881. return output;
  882. }
  883. yy_delete_buffer(state, scanner);
  884. yylex_destroy(scanner);
  885. return output;
  886. }
  887. BSLFXCompiler::TechniqueMetaData BSLFXCompiler::parseTechniqueMetaData(ASTFXNode* technique)
  888. {
  889. TechniqueMetaData metaData;
  890. metaData.renderer = RendererAny;
  891. metaData.language = "hlsl";
  892. metaData.isMixin = technique->type == NT_Mixin;
  893. for (int i = 0; i < technique->options->count; i++)
  894. {
  895. NodeOption* option = &technique->options->entries[i];
  896. switch (option->type)
  897. {
  898. case OT_Renderer:
  899. metaData.renderer = parseRenderer(removeQuotes(option->value.strValue));
  900. break;
  901. case OT_Tags:
  902. {
  903. ASTFXNode* tagsNode = option->value.nodePtr;
  904. for (int j = 0; j < tagsNode->options->count; j++)
  905. {
  906. NodeOption* tagOption = &tagsNode->options->entries[j];
  907. if (tagOption->type == OT_TagValue)
  908. metaData.tags.push_back(removeQuotes(tagOption->value.strValue));
  909. }
  910. }
  911. break;
  912. case OT_Variations:
  913. {
  914. ASTFXNode* variationsNode = option->value.nodePtr;
  915. for (int j = 0; j < variationsNode->options->count; j++)
  916. {
  917. NodeOption* variationOption = &variationsNode->options->entries[j];
  918. if(variationOption->type == OT_Variation)
  919. parseVariations(metaData, variationOption->value.nodePtr);
  920. }
  921. }
  922. case OT_Identifier:
  923. metaData.name = option->value.strValue;
  924. break;
  925. case OT_Mixin:
  926. metaData.includes.push_back(option->value.strValue);
  927. break;
  928. default:
  929. break;
  930. }
  931. }
  932. return metaData;
  933. }
  934. void BSLFXCompiler::parseVariations(TechniqueMetaData& metaData, ASTFXNode* variations)
  935. {
  936. assert(variations->type == NT_Variation);
  937. VariationData variationData;
  938. for (int i = 0; i < variations->options->count; i++)
  939. {
  940. NodeOption* option = &variations->options->entries[i];
  941. switch (option->type)
  942. {
  943. case OT_Identifier:
  944. variationData.identifier = option->value.strValue;
  945. break;
  946. case OT_VariationValue:
  947. variationData.values.push_back(option->value.intValue);
  948. break;
  949. default:
  950. break;
  951. }
  952. }
  953. if (!variationData.identifier.empty())
  954. metaData.variations.push_back(variationData);
  955. }
  956. StringID BSLFXCompiler::parseRenderer(const String& name)
  957. {
  958. if (name == "Any")
  959. return RendererAny;
  960. else if (name == "Default")
  961. return RendererDefault;
  962. return RendererAny;
  963. }
  964. QueueSortType BSLFXCompiler::parseSortType(CullAndSortModeValue sortType)
  965. {
  966. switch (sortType)
  967. {
  968. case CASV_BackToFront:
  969. return QueueSortType::BackToFront;
  970. case CASV_FrontToBack:
  971. return QueueSortType::FrontToBack;
  972. case CASV_None:
  973. return QueueSortType::None;
  974. default:
  975. break;
  976. }
  977. return QueueSortType::None;
  978. }
  979. CompareFunction BSLFXCompiler::parseCompFunc(CompFuncValue compFunc)
  980. {
  981. switch (compFunc)
  982. {
  983. case CFV_Pass:
  984. return CMPF_ALWAYS_PASS;
  985. case CFV_Fail:
  986. return CMPF_ALWAYS_FAIL;
  987. case CFV_LT:
  988. return CMPF_LESS;
  989. case CFV_LTE:
  990. return CMPF_LESS_EQUAL;
  991. case CFV_EQ:
  992. return CMPF_EQUAL;
  993. case CFV_NEQ:
  994. return CMPF_NOT_EQUAL;
  995. case CFV_GT:
  996. return CMPF_GREATER;
  997. case CFV_GTE:
  998. return CMPF_GREATER_EQUAL;
  999. }
  1000. return CMPF_ALWAYS_PASS;
  1001. }
  1002. BlendFactor BSLFXCompiler::parseBlendFactor(OpValue factor)
  1003. {
  1004. switch (factor)
  1005. {
  1006. case OV_One:
  1007. return BF_ONE;
  1008. case OV_Zero:
  1009. return BF_ZERO;
  1010. case OV_DestColor:
  1011. return BF_DEST_COLOR;
  1012. case OV_SrcColor:
  1013. return BF_SOURCE_COLOR;
  1014. case OV_InvDestColor:
  1015. return BF_INV_DEST_COLOR;
  1016. case OV_InvSrcColor:
  1017. return BF_INV_SOURCE_COLOR;
  1018. case OV_DestAlpha:
  1019. return BF_DEST_ALPHA;
  1020. case OV_SrcAlpha:
  1021. return BF_SOURCE_ALPHA;
  1022. case OV_InvDestAlpha:
  1023. return BF_INV_DEST_ALPHA;
  1024. case OV_InvSrcAlpha:
  1025. return BF_INV_SOURCE_ALPHA;
  1026. default:
  1027. break;
  1028. }
  1029. return BF_ONE;
  1030. }
  1031. BlendOperation BSLFXCompiler::parseBlendOp(BlendOpValue op)
  1032. {
  1033. switch (op)
  1034. {
  1035. case BOV_Add:
  1036. return BO_ADD;
  1037. case BOV_Max:
  1038. return BO_MAX;
  1039. case BOV_Min:
  1040. return BO_MIN;
  1041. case BOV_Subtract:
  1042. return BO_SUBTRACT;
  1043. case BOV_RevSubtract:
  1044. return BO_REVERSE_SUBTRACT;
  1045. }
  1046. return BO_ADD;
  1047. }
  1048. StencilOperation BSLFXCompiler::parseStencilOp(OpValue op)
  1049. {
  1050. switch (op)
  1051. {
  1052. case OV_Keep:
  1053. return SOP_KEEP;
  1054. case OV_Zero:
  1055. return SOP_ZERO;
  1056. case OV_Replace:
  1057. return SOP_REPLACE;
  1058. case OV_Incr:
  1059. return SOP_INCREMENT;
  1060. case OV_Decr:
  1061. return SOP_DECREMENT;
  1062. case OV_IncrWrap:
  1063. return SOP_INCREMENT_WRAP;
  1064. case OV_DecrWrap:
  1065. return SOP_DECREMENT_WRAP;
  1066. case OV_Invert:
  1067. return SOP_INVERT;
  1068. default:
  1069. break;
  1070. }
  1071. return SOP_KEEP;
  1072. }
  1073. CullingMode BSLFXCompiler::parseCullMode(CullAndSortModeValue cm)
  1074. {
  1075. switch (cm)
  1076. {
  1077. case CASV_None:
  1078. return CULL_NONE;
  1079. case CASV_CW:
  1080. return CULL_CLOCKWISE;
  1081. case CASV_CCW:
  1082. return CULL_COUNTERCLOCKWISE;
  1083. default:
  1084. break;
  1085. }
  1086. return CULL_COUNTERCLOCKWISE;
  1087. }
  1088. PolygonMode BSLFXCompiler::parseFillMode(FillModeValue fm)
  1089. {
  1090. if (fm == FMV_Wire)
  1091. return PM_WIREFRAME;
  1092. return PM_SOLID;
  1093. }
  1094. void BSLFXCompiler::parseStencilFront(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1095. {
  1096. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1097. return;
  1098. for (int i = 0; i < stencilOpNode->options->count; i++)
  1099. {
  1100. NodeOption* option = &stencilOpNode->options->entries[i];
  1101. switch (option->type)
  1102. {
  1103. case OT_Fail:
  1104. desc.frontStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1105. break;
  1106. case OT_ZFail:
  1107. desc.frontStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1108. break;
  1109. case OT_PassOp:
  1110. desc.frontStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1111. break;
  1112. case OT_CompareFunc:
  1113. desc.frontStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1114. break;
  1115. default:
  1116. break;
  1117. }
  1118. }
  1119. }
  1120. void BSLFXCompiler::parseStencilBack(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1121. {
  1122. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1123. return;
  1124. for (int i = 0; i < stencilOpNode->options->count; i++)
  1125. {
  1126. NodeOption* option = &stencilOpNode->options->entries[i];
  1127. switch (option->type)
  1128. {
  1129. case OT_Fail:
  1130. desc.backStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1131. break;
  1132. case OT_ZFail:
  1133. desc.backStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1134. break;
  1135. case OT_PassOp:
  1136. desc.backStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1137. break;
  1138. case OT_CompareFunc:
  1139. desc.backStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1140. break;
  1141. default:
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. void BSLFXCompiler::parseColorBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1147. {
  1148. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1149. return;
  1150. for (int i = 0; i < blendDefNode->options->count; i++)
  1151. {
  1152. NodeOption* option = &blendDefNode->options->entries[i];
  1153. switch (option->type)
  1154. {
  1155. case OT_Source:
  1156. desc.srcBlend = parseBlendFactor((OpValue)option->value.intValue);
  1157. break;
  1158. case OT_Dest:
  1159. desc.dstBlend = parseBlendFactor((OpValue)option->value.intValue);
  1160. break;
  1161. case OT_Op:
  1162. desc.blendOp = parseBlendOp((BlendOpValue)option->value.intValue);
  1163. break;
  1164. default:
  1165. break;
  1166. }
  1167. }
  1168. }
  1169. void BSLFXCompiler::parseAlphaBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1170. {
  1171. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1172. return;
  1173. for (int i = 0; i < blendDefNode->options->count; i++)
  1174. {
  1175. NodeOption* option = &blendDefNode->options->entries[i];
  1176. switch (option->type)
  1177. {
  1178. case OT_Source:
  1179. desc.srcBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1180. break;
  1181. case OT_Dest:
  1182. desc.dstBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1183. break;
  1184. case OT_Op:
  1185. desc.blendOpAlpha = parseBlendOp((BlendOpValue)option->value.intValue);
  1186. break;
  1187. default:
  1188. break;
  1189. }
  1190. }
  1191. }
  1192. void BSLFXCompiler::parseRenderTargetBlendState(BLEND_STATE_DESC& desc, ASTFXNode* targetNode)
  1193. {
  1194. if (targetNode == nullptr || targetNode->type != NT_Target)
  1195. return;
  1196. UINT32 index = 0;
  1197. for (int i = 0; i < targetNode->options->count; i++)
  1198. {
  1199. NodeOption* option = &targetNode->options->entries[i];
  1200. switch (option->type)
  1201. {
  1202. case OT_Index:
  1203. index = option->value.intValue;
  1204. break;
  1205. default:
  1206. break;
  1207. }
  1208. }
  1209. if (index >= BS_MAX_MULTIPLE_RENDER_TARGETS)
  1210. return;
  1211. RENDER_TARGET_BLEND_STATE_DESC& rtDesc = desc.renderTargetDesc[index];
  1212. for (int i = 0; i < targetNode->options->count; i++)
  1213. {
  1214. NodeOption* option = &targetNode->options->entries[i];
  1215. switch (option->type)
  1216. {
  1217. case OT_Enabled:
  1218. rtDesc.blendEnable = option->value.intValue > 0;
  1219. break;
  1220. case OT_Color:
  1221. parseColorBlendDef(rtDesc, option->value.nodePtr);
  1222. break;
  1223. case OT_Alpha:
  1224. parseAlphaBlendDef(rtDesc, option->value.nodePtr);
  1225. break;
  1226. case OT_WriteMask:
  1227. rtDesc.renderTargetWriteMask = option->value.intValue;
  1228. break;
  1229. default:
  1230. break;
  1231. }
  1232. }
  1233. }
  1234. bool BSLFXCompiler::parseBlendState(PassData& desc, ASTFXNode* blendNode)
  1235. {
  1236. if (blendNode == nullptr || blendNode->type != NT_Blend)
  1237. return false;
  1238. bool isDefault = true;
  1239. for (int i = 0; i < blendNode->options->count; i++)
  1240. {
  1241. NodeOption* option = &blendNode->options->entries[i];
  1242. switch (option->type)
  1243. {
  1244. case OT_AlphaToCoverage:
  1245. desc.blendDesc.alphaToCoverageEnable = option->value.intValue > 0;
  1246. isDefault = false;
  1247. break;
  1248. case OT_IndependantBlend:
  1249. desc.blendDesc.independantBlendEnable = option->value.intValue > 0;
  1250. isDefault = false;
  1251. break;
  1252. case OT_Target:
  1253. parseRenderTargetBlendState(desc.blendDesc, option->value.nodePtr);
  1254. isDefault = false;
  1255. break;
  1256. default:
  1257. break;
  1258. }
  1259. }
  1260. return !isDefault;
  1261. }
  1262. bool BSLFXCompiler::parseRasterizerState(PassData& desc, ASTFXNode* rasterNode)
  1263. {
  1264. if (rasterNode == nullptr || rasterNode->type != NT_Raster)
  1265. return false;
  1266. bool isDefault = true;
  1267. for (int i = 0; i < rasterNode->options->count; i++)
  1268. {
  1269. NodeOption* option = &rasterNode->options->entries[i];
  1270. switch (option->type)
  1271. {
  1272. case OT_FillMode:
  1273. desc.rasterizerDesc.polygonMode = parseFillMode((FillModeValue)option->value.intValue);
  1274. isDefault = false;
  1275. break;
  1276. case OT_CullMode:
  1277. desc.rasterizerDesc.cullMode = parseCullMode((CullAndSortModeValue)option->value.intValue);
  1278. isDefault = false;
  1279. break;
  1280. case OT_DepthBias:
  1281. desc.rasterizerDesc.depthBias = option->value.floatValue;
  1282. isDefault = false;
  1283. break;
  1284. case OT_SDepthBias:
  1285. desc.rasterizerDesc.slopeScaledDepthBias = option->value.floatValue;
  1286. isDefault = false;
  1287. break;
  1288. case OT_DepthClip:
  1289. desc.rasterizerDesc.depthClipEnable = option->value.intValue > 0;
  1290. isDefault = false;
  1291. break;
  1292. case OT_Scissor:
  1293. desc.rasterizerDesc.scissorEnable = option->value.intValue > 0;
  1294. isDefault = false;
  1295. break;
  1296. case OT_Multisample:
  1297. desc.rasterizerDesc.multisampleEnable = option->value.intValue > 0;
  1298. isDefault = false;
  1299. break;
  1300. case OT_AALine:
  1301. desc.rasterizerDesc.antialiasedLineEnable = option->value.intValue > 0;
  1302. isDefault = false;
  1303. break;
  1304. default:
  1305. break;
  1306. }
  1307. }
  1308. return !isDefault;
  1309. }
  1310. bool BSLFXCompiler::parseDepthState(PassData& passData, ASTFXNode* depthNode)
  1311. {
  1312. if (depthNode == nullptr || depthNode->type != NT_Depth)
  1313. return false;
  1314. bool isDefault = true;
  1315. for (int i = 0; i < depthNode->options->count; i++)
  1316. {
  1317. NodeOption* option = &depthNode->options->entries[i];
  1318. switch (option->type)
  1319. {
  1320. case OT_DepthRead:
  1321. passData.depthStencilDesc.depthReadEnable = option->value.intValue > 0;
  1322. isDefault = false;
  1323. break;
  1324. case OT_DepthWrite:
  1325. passData.depthStencilDesc.depthWriteEnable = option->value.intValue > 0;
  1326. isDefault = false;
  1327. break;
  1328. case OT_CompareFunc:
  1329. passData.depthStencilDesc.depthComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1330. isDefault = false;
  1331. break;
  1332. default:
  1333. break;
  1334. }
  1335. }
  1336. return !isDefault;
  1337. }
  1338. bool BSLFXCompiler::parseStencilState(PassData& passData, ASTFXNode* stencilNode)
  1339. {
  1340. if (stencilNode == nullptr || stencilNode->type != NT_Stencil)
  1341. return false;
  1342. bool isDefault = true;
  1343. for (int i = 0; i < stencilNode->options->count; i++)
  1344. {
  1345. NodeOption* option = &stencilNode->options->entries[i];
  1346. switch (option->type)
  1347. {
  1348. case OT_Enabled:
  1349. passData.depthStencilDesc.stencilEnable = option->value.intValue > 0;
  1350. isDefault = false;
  1351. break;
  1352. case OT_StencilReadMask:
  1353. passData.depthStencilDesc.stencilReadMask = (UINT8)option->value.intValue;
  1354. isDefault = false;
  1355. break;
  1356. case OT_StencilWriteMask:
  1357. passData.depthStencilDesc.stencilWriteMask = (UINT8)option->value.intValue;
  1358. isDefault = false;
  1359. break;
  1360. case OT_StencilOpFront:
  1361. parseStencilFront(passData.depthStencilDesc, option->value.nodePtr);
  1362. isDefault = false;
  1363. break;
  1364. case OT_StencilOpBack:
  1365. parseStencilBack(passData.depthStencilDesc, option->value.nodePtr);
  1366. isDefault = false;
  1367. break;
  1368. case OT_StencilRef:
  1369. passData.stencilRefValue = option->value.intValue;
  1370. break;
  1371. default:
  1372. break;
  1373. }
  1374. }
  1375. return !isDefault;
  1376. }
  1377. void BSLFXCompiler::parseCodeBlock(ASTFXNode* codeNode, const Vector<String>& codeBlocks, PassData& passData)
  1378. {
  1379. if (codeNode == nullptr || (codeNode->type != NT_Code))
  1380. {
  1381. return;
  1382. }
  1383. UINT32 index = (UINT32)-1;
  1384. for (int j = 0; j < codeNode->options->count; j++)
  1385. {
  1386. if (codeNode->options->entries[j].type == OT_Index)
  1387. index = codeNode->options->entries[j].value.intValue;
  1388. }
  1389. if (index != (UINT32)-1 && index < (UINT32)codeBlocks.size())
  1390. {
  1391. switch (codeNode->type)
  1392. {
  1393. case NT_Code:
  1394. passData.code += codeBlocks[index];
  1395. break;
  1396. default:
  1397. break;
  1398. }
  1399. }
  1400. }
  1401. void BSLFXCompiler::parsePass(ASTFXNode* passNode, const Vector<String>& codeBlocks, PassData& passData)
  1402. {
  1403. if (passNode == nullptr || passNode->type != NT_Pass)
  1404. return;
  1405. for (int i = 0; i < passNode->options->count; i++)
  1406. {
  1407. NodeOption* option = &passNode->options->entries[i];
  1408. switch (option->type)
  1409. {
  1410. case OT_Blend:
  1411. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1412. break;
  1413. case OT_Raster:
  1414. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1415. break;
  1416. case OT_Depth:
  1417. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1418. break;
  1419. case OT_Stencil:
  1420. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1421. break;
  1422. case OT_Code:
  1423. parseCodeBlock(option->value.nodePtr, codeBlocks, passData);
  1424. break;
  1425. default:
  1426. break;
  1427. }
  1428. }
  1429. }
  1430. void BSLFXCompiler::parseTechnique(ASTFXNode* techniqueNode, const Vector<String>& codeBlocks, TechniqueData& techniqueData)
  1431. {
  1432. if (techniqueNode == nullptr || (techniqueNode->type != NT_Technique && techniqueNode->type != NT_Mixin))
  1433. return;
  1434. // There must always be at least one pass
  1435. if(techniqueData.passes.empty())
  1436. {
  1437. techniqueData.passes.push_back(PassData());
  1438. techniqueData.passes.back().seqIdx = 0;
  1439. }
  1440. PassData combinedCommonPassData;
  1441. UINT32 nextPassIdx = 0;
  1442. // Go in reverse because options are added in reverse order during parsing
  1443. for (int i = techniqueNode->options->count - 1; i >= 0; i--)
  1444. {
  1445. NodeOption* option = &techniqueNode->options->entries[i];
  1446. switch (option->type)
  1447. {
  1448. case OT_Pass:
  1449. {
  1450. UINT32 passIdx = nextPassIdx;
  1451. PassData* passData = nullptr;
  1452. for (auto& entry : techniqueData.passes)
  1453. {
  1454. if (entry.seqIdx == passIdx)
  1455. passData = &entry;
  1456. }
  1457. if (passData == nullptr)
  1458. {
  1459. techniqueData.passes.push_back(PassData());
  1460. passData = &techniqueData.passes.back();
  1461. passData->seqIdx = passIdx;
  1462. }
  1463. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  1464. passData->code = combinedCommonPassData.code + passData->code;
  1465. ASTFXNode* passNode = option->value.nodePtr;
  1466. parsePass(passNode, codeBlocks, *passData);
  1467. }
  1468. break;
  1469. case OT_Code:
  1470. {
  1471. PassData commonPassData;
  1472. parseCodeBlock(option->value.nodePtr, codeBlocks, commonPassData);
  1473. for (auto& passData : techniqueData.passes)
  1474. passData.code += commonPassData.code;
  1475. combinedCommonPassData.code += commonPassData.code;
  1476. }
  1477. break;
  1478. default:
  1479. break;
  1480. }
  1481. }
  1482. // Parse common pass states
  1483. for (int i = 0; i < techniqueNode->options->count; i++)
  1484. {
  1485. NodeOption* option = &techniqueNode->options->entries[i];
  1486. switch (option->type)
  1487. {
  1488. case OT_Blend:
  1489. for (auto& passData : techniqueData.passes)
  1490. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1491. break;
  1492. case OT_Raster:
  1493. for (auto& passData : techniqueData.passes)
  1494. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1495. break;
  1496. case OT_Depth:
  1497. for (auto& passData : techniqueData.passes)
  1498. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1499. break;
  1500. case OT_Stencil:
  1501. for (auto& passData : techniqueData.passes)
  1502. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1503. break;
  1504. default:
  1505. break;
  1506. }
  1507. }
  1508. }
  1509. void BSLFXCompiler::parseOptions(ASTFXNode* optionsNode, SHADER_DESC& shaderDesc)
  1510. {
  1511. if (optionsNode == nullptr || optionsNode->type != NT_Options)
  1512. return;
  1513. for (int i = optionsNode->options->count - 1; i >= 0; i--)
  1514. {
  1515. NodeOption* option = &optionsNode->options->entries[i];
  1516. switch (option->type)
  1517. {
  1518. case OT_Separable:
  1519. shaderDesc.separablePasses = option->value.intValue > 1;
  1520. break;
  1521. case OT_Sort:
  1522. shaderDesc.queueSortType = parseSortType((CullAndSortModeValue)option->value.intValue);
  1523. break;
  1524. case OT_Priority:
  1525. shaderDesc.queuePriority = option->value.intValue;
  1526. break;
  1527. case OT_Transparent:
  1528. shaderDesc.flags |= (UINT32)ShaderFlags::Transparent;
  1529. break;
  1530. default:
  1531. break;
  1532. }
  1533. }
  1534. }
  1535. BSLFXCompileResult BSLFXCompiler::parseTechniques(ParseState* parseState, const Vector<String>& codeBlocks,
  1536. const ShaderVariation& variation, Vector<SPtr<Technique>>& techniques, UnorderedSet<String>& includes,
  1537. SHADER_DESC& shaderDesc)
  1538. {
  1539. BSLFXCompileResult output;
  1540. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  1541. {
  1542. parseStateDelete(parseState);
  1543. output.errorMessage = "Root not is null or not a shader.";
  1544. return output;
  1545. }
  1546. Vector<pair<ASTFXNode*, TechniqueData>> techniqueData;
  1547. // Go in reverse because options are added in reverse order during parsing
  1548. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  1549. {
  1550. NodeOption* option = &parseState->rootNode->options->entries[i];
  1551. switch (option->type)
  1552. {
  1553. case OT_Technique:
  1554. {
  1555. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  1556. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  1557. techniqueData.push_back(std::make_pair(option->value.nodePtr, TechniqueData()));
  1558. TechniqueData& data = techniqueData.back().second;
  1559. data.metaData = metaData;
  1560. break;
  1561. }
  1562. default:
  1563. break;
  1564. }
  1565. }
  1566. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueData.size());
  1567. std::function<bool(const TechniqueMetaData&, TechniqueData&)> parseInherited =
  1568. [&](const TechniqueMetaData& metaData, TechniqueData& outTechnique)
  1569. {
  1570. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  1571. {
  1572. const String& includes = *riter;
  1573. UINT32 baseIdx = -1;
  1574. for(UINT32 i = 0; i < (UINT32)techniqueData.size(); i++)
  1575. {
  1576. auto& entry = techniqueData[i];
  1577. if (!entry.second.metaData.isMixin)
  1578. continue;
  1579. if (entry.second.metaData.name == includes)
  1580. {
  1581. bool matches =
  1582. (entry.second.metaData.language == metaData.language ||
  1583. entry.second.metaData.language == "Any") &&
  1584. (entry.second.metaData.renderer == metaData.renderer ||
  1585. entry.second.metaData.renderer == RendererAny);
  1586. // We want the last matching technique, in order to allow techniques to override each other
  1587. if (matches)
  1588. baseIdx = i;
  1589. }
  1590. }
  1591. if (baseIdx != (UINT32)-1)
  1592. {
  1593. auto& entry = techniqueData[baseIdx];
  1594. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  1595. // include the same mixin)
  1596. if (techniqueWasParsed[baseIdx])
  1597. continue;
  1598. if (!parseInherited(entry.second.metaData, outTechnique))
  1599. return false;
  1600. parseTechnique(entry.first, codeBlocks, outTechnique);
  1601. techniqueWasParsed[baseIdx] = true;
  1602. }
  1603. else
  1604. {
  1605. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  1606. return false;
  1607. }
  1608. }
  1609. return true;
  1610. };
  1611. // Actually parse techniques
  1612. for (auto& entry : techniqueData)
  1613. {
  1614. const TechniqueMetaData& metaData = entry.second.metaData;
  1615. if (metaData.isMixin)
  1616. continue;
  1617. bs_zero_out(techniqueWasParsed, techniqueData.size());
  1618. if (!parseInherited(metaData, entry.second))
  1619. {
  1620. parseStateDelete(parseState);
  1621. bs_stack_free(techniqueWasParsed);
  1622. return output;
  1623. }
  1624. parseTechnique(entry.first, codeBlocks, entry.second);
  1625. }
  1626. bs_stack_free(techniqueWasParsed);
  1627. IncludeLink* includeLink = parseState->includes;
  1628. while(includeLink != nullptr)
  1629. {
  1630. String includeFilename = includeLink->data->filename;
  1631. auto iterFind = std::find(includes.begin(), includes.end(), includeFilename);
  1632. if (iterFind == includes.end())
  1633. includes.insert(includeFilename);
  1634. includeLink = includeLink->next;
  1635. }
  1636. parseStateDelete(parseState);
  1637. // Parse extended HLSL code and generate per-program code, also convert to GLSL/VKSL
  1638. UINT32 end = (UINT32)techniqueData.size();
  1639. for(UINT32 i = 0; i < end; i++)
  1640. {
  1641. const TechniqueMetaData& metaData = techniqueData[i].second.metaData;
  1642. if (metaData.isMixin)
  1643. continue;
  1644. TechniqueData& hlslTechnique = techniqueData[i].second;
  1645. TechniqueData glslTechnique = techniqueData[i].second;
  1646. glslTechnique.metaData.language = "glsl";
  1647. TechniqueData vkslTechnique = techniqueData[i].second;
  1648. vkslTechnique.metaData.language = "vksl";
  1649. UINT32 numPasses = (UINT32)hlslTechnique.passes.size();
  1650. for(UINT32 j = 0; j < numPasses; j++)
  1651. {
  1652. PassData& hlslPassData = hlslTechnique.passes[j];
  1653. PassData& glslPassData = glslTechnique.passes[j];
  1654. PassData& vkslPassData = vkslTechnique.passes[j];
  1655. // Clean non-standard HLSL
  1656. static const std::regex regex("\\[\\s*layout\\s*\\(.*\\)\\s*\\]|\\[\\s*internal\\s*\\]|\\[\\s*color\\s*\\]|\\[\\s*alias\\s*\\(.*\\)\\s*\\]");
  1657. hlslPassData.code = regex_replace(hlslPassData.code, regex, "");
  1658. // Find valid entry points and parameters
  1659. // Note: XShaderCompiler needs to do a full pass when doing reflection, and for each individual program
  1660. // type. If performance is ever important here it could be good to update XShaderCompiler so it can
  1661. // somehow save the AST and then re-use it for multiple actions.
  1662. Vector<GpuProgramType> types;
  1663. reflectHLSL(glslPassData.code, shaderDesc, types);
  1664. UINT32 glslBinding = 0;
  1665. UINT32 vkslBinding = 0;
  1666. // Cross-compile for all detected shader types
  1667. // Note: I'm just copying HLSL code as-is. This code will contain all entry points which could have
  1668. // an effect on compile time. It would be ideal to remove dead code depending on program type. This would
  1669. // involve adding a HLSL code generator to XShaderCompiler.
  1670. for(auto& type : types)
  1671. {
  1672. switch(type)
  1673. {
  1674. case GPT_VERTEX_PROGRAM:
  1675. hlslPassData.vertexCode = hlslPassData.code;
  1676. glslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM, false, glslBinding);
  1677. vkslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM, true, vkslBinding);
  1678. break;
  1679. case GPT_FRAGMENT_PROGRAM:
  1680. hlslPassData.fragmentCode = hlslPassData.code;
  1681. glslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM, false, glslBinding);
  1682. vkslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM, true, vkslBinding);
  1683. break;
  1684. case GPT_GEOMETRY_PROGRAM:
  1685. hlslPassData.geometryCode = hlslPassData.code;
  1686. glslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM, false, glslBinding);
  1687. vkslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM, true, vkslBinding);
  1688. break;
  1689. case GPT_HULL_PROGRAM:
  1690. hlslPassData.hullCode = hlslPassData.code;
  1691. glslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM, false, glslBinding);
  1692. vkslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM, true, vkslBinding);
  1693. break;
  1694. case GPT_DOMAIN_PROGRAM:
  1695. hlslPassData.domainCode = hlslPassData.code;
  1696. glslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM, false, glslBinding);
  1697. vkslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM, true, vkslBinding);
  1698. break;
  1699. case GPT_COMPUTE_PROGRAM:
  1700. hlslPassData.computeCode = hlslPassData.code;
  1701. glslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM, false, glslBinding);
  1702. vkslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM, true, vkslBinding);
  1703. break;
  1704. default:
  1705. break;
  1706. }
  1707. }
  1708. }
  1709. techniqueData.push_back(std::make_pair(nullptr, glslTechnique));
  1710. techniqueData.push_back(std::make_pair(nullptr, vkslTechnique));
  1711. }
  1712. for(auto& entry : techniqueData)
  1713. {
  1714. const TechniqueMetaData& metaData = entry.second.metaData;
  1715. if (metaData.isMixin)
  1716. continue;
  1717. Map<UINT32, SPtr<Pass>, std::greater<UINT32>> passes;
  1718. for (auto& passData : entry.second.passes)
  1719. {
  1720. PASS_DESC passDesc;
  1721. if (!passData.blendIsDefault)
  1722. passDesc.blendState = BlendState::create(passData.blendDesc);
  1723. if (!passData.rasterizerIsDefault)
  1724. passDesc.rasterizerState = RasterizerState::create(passData.rasterizerDesc);
  1725. if (!passData.depthStencilIsDefault)
  1726. passDesc.depthStencilState = DepthStencilState::create(passData.depthStencilDesc);
  1727. auto createProgram =
  1728. [](const String& language, const String& entry, const String& code, GpuProgramType type) -> SPtr<GpuProgram>
  1729. {
  1730. if (code.empty())
  1731. return nullptr;
  1732. GPU_PROGRAM_DESC desc;
  1733. desc.language = language;
  1734. desc.entryPoint = entry;
  1735. desc.source = code;
  1736. desc.type = type;
  1737. return GpuProgram::create(desc);
  1738. };
  1739. bool isHLSL = metaData.language == "hlsl";
  1740. passDesc.vertexProgram = createProgram(
  1741. metaData.language,
  1742. isHLSL ? "vsmain" : "main",
  1743. passData.vertexCode,
  1744. GPT_VERTEX_PROGRAM);
  1745. passDesc.fragmentProgram = createProgram(
  1746. metaData.language,
  1747. isHLSL ? "fsmain" : "main",
  1748. passData.fragmentCode,
  1749. GPT_FRAGMENT_PROGRAM);
  1750. passDesc.geometryProgram = createProgram(
  1751. metaData.language,
  1752. isHLSL ? "gsmain" : "main",
  1753. passData.geometryCode,
  1754. GPT_GEOMETRY_PROGRAM);
  1755. passDesc.hullProgram = createProgram(
  1756. metaData.language,
  1757. isHLSL ? "hsmain" : "main",
  1758. passData.hullCode,
  1759. GPT_HULL_PROGRAM);
  1760. passDesc.domainProgram = createProgram(
  1761. metaData.language,
  1762. isHLSL ? "dsmain" : "main",
  1763. passData.domainCode,
  1764. GPT_DOMAIN_PROGRAM);
  1765. passDesc.computeProgram = createProgram(
  1766. metaData.language,
  1767. isHLSL ? "csmain" : "main",
  1768. passData.computeCode,
  1769. GPT_COMPUTE_PROGRAM);
  1770. passDesc.stencilRefValue = passData.stencilRefValue;
  1771. SPtr<Pass> pass = Pass::create(passDesc);
  1772. if (pass != nullptr)
  1773. passes[passData.seqIdx] = pass;
  1774. }
  1775. Vector<SPtr<Pass>> orderedPasses;
  1776. for (auto& KVP : passes)
  1777. orderedPasses.push_back(KVP.second);
  1778. if (orderedPasses.size() > 0)
  1779. {
  1780. SPtr<Technique> technique = Technique::create(metaData.language, metaData.renderer, metaData.tags,
  1781. variation, orderedPasses);
  1782. techniques.push_back(technique);
  1783. }
  1784. }
  1785. return output;
  1786. }
  1787. String BSLFXCompiler::removeQuotes(const char* input)
  1788. {
  1789. UINT32 len = (UINT32)strlen(input);
  1790. String output(len - 2, ' ');
  1791. for (UINT32 i = 0; i < (len - 2); i++)
  1792. output[i] = input[i + 1];
  1793. return output;
  1794. }
  1795. }