BsSLFXCompiler.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100
  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. // Ignore parameters that were already registered in some previous variation. Note that this implies
  382. // you cannot have same names for different parameters in different variations.
  383. if (desc.textureParams.find(ident) != desc.textureParams.end())
  384. continue;
  385. if (entry.defaultValue == -1)
  386. desc.addParameter(ident, ident, objType);
  387. else
  388. desc.addParameter(ident, ident, objType, getBuiltinTexture(entry.defaultValue));
  389. }
  390. else
  391. {
  392. // Ignore parameters that were already registered in some previous variation. Note that this implies
  393. // you cannot have same names for different parameters in different variations.
  394. if (desc.bufferParams.find(ident) != desc.bufferParams.end())
  395. continue;
  396. objType = ReflTypeToBufferType((Xsc::Reflection::BufferType)entry.baseType);
  397. desc.addParameter(ident, ident, objType);
  398. }
  399. }
  400. break;
  401. case Xsc::Reflection::UniformType::Sampler:
  402. {
  403. auto findIter = reflData.samplerStates.find(entry.ident);
  404. if (findIter != reflData.samplerStates.end())
  405. {
  406. // Ignore parameters that were already registered in some previous variation. Note that this implies
  407. // you cannot have same names for different parameters in different variations.
  408. if(desc.samplerParams.find(ident) != desc.samplerParams.end())
  409. continue;
  410. String alias = findIter->second.alias.c_str();
  411. if(findIter->second.isNonDefault)
  412. {
  413. SPtr<SamplerState> defaultVal = parseSamplerState(findIter->second);
  414. desc.addParameter(ident, ident, GPOT_SAMPLER2D, defaultVal);
  415. if (!alias.empty())
  416. desc.addParameter(ident, alias, GPOT_SAMPLER2D, defaultVal);
  417. }
  418. else
  419. {
  420. desc.addParameter(ident, ident, GPOT_SAMPLER2D);
  421. if (!alias.empty())
  422. desc.addParameter(ident, alias, GPOT_SAMPLER2D);
  423. }
  424. }
  425. else
  426. {
  427. desc.addParameter(ident, ident, GPOT_SAMPLER2D);
  428. }
  429. break;
  430. }
  431. case Xsc::Reflection::UniformType::Variable:
  432. {
  433. bool isBlockInternal = false;
  434. if(entry.uniformBlock != -1)
  435. {
  436. std::string blockName = reflData.constantBuffers[entry.uniformBlock].ident;
  437. for (auto& uniform : reflData.uniforms)
  438. {
  439. if (uniform.type == Xsc::Reflection::UniformType::UniformBuffer && uniform.ident == blockName)
  440. {
  441. isBlockInternal = (uniform.flags & Xsc::Reflection::Uniform::Flags::Internal) != 0;
  442. break;
  443. }
  444. }
  445. }
  446. if (!isBlockInternal)
  447. {
  448. GpuParamDataType type = ReflTypeToDataType((Xsc::Reflection::DataType)entry.baseType);
  449. if ((entry.flags & Xsc::Reflection::Uniform::Flags::Color) != 0 &&
  450. (type == GPDT_FLOAT3 || type == GPDT_FLOAT4))
  451. {
  452. type = GPDT_COLOR;
  453. }
  454. if (entry.defaultValue == -1)
  455. desc.addParameter(ident, ident, type);
  456. else
  457. {
  458. const Xsc::Reflection::DefaultValue& defVal = reflData.defaultValues[entry.defaultValue];
  459. desc.addParameter(ident, ident, type, StringID::NONE, 1, 0, (UINT8*)defVal.matrix);
  460. }
  461. }
  462. }
  463. break;
  464. case Xsc::Reflection::UniformType::Struct:
  465. break;
  466. default: ;
  467. }
  468. }
  469. }
  470. String crossCompile(const String& hlsl, GpuProgramType type, bool vulkan, bool optionalEntry, UINT32& startBindingSlot,
  471. SHADER_DESC* shaderDesc = nullptr, Vector<GpuProgramType>* detectedTypes = nullptr)
  472. {
  473. SPtr<StringStream> input = bs_shared_ptr_new<StringStream>();
  474. if (vulkan)
  475. *input << "#define VULKAN 1" << std::endl;
  476. else
  477. *input << "#define OPENGL 1" << std::endl;
  478. *input << hlsl;
  479. Xsc::ShaderInput inputDesc;
  480. inputDesc.shaderVersion = Xsc::InputShaderVersion::HLSL5;
  481. inputDesc.sourceCode = input;
  482. inputDesc.extensions = Xsc::Extensions::LayoutAttribute;
  483. switch (type)
  484. {
  485. case GPT_VERTEX_PROGRAM:
  486. inputDesc.shaderTarget = Xsc::ShaderTarget::VertexShader;
  487. inputDesc.entryPoint = "vsmain";
  488. break;
  489. case GPT_GEOMETRY_PROGRAM:
  490. inputDesc.shaderTarget = Xsc::ShaderTarget::GeometryShader;
  491. inputDesc.entryPoint = "gsmain";
  492. break;
  493. case GPT_HULL_PROGRAM:
  494. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationControlShader;
  495. inputDesc.entryPoint = "hsmain";
  496. break;
  497. case GPT_DOMAIN_PROGRAM:
  498. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationEvaluationShader;
  499. inputDesc.entryPoint = "dsmain";
  500. break;
  501. case GPT_FRAGMENT_PROGRAM:
  502. inputDesc.shaderTarget = Xsc::ShaderTarget::FragmentShader;
  503. inputDesc.entryPoint = "fsmain";
  504. break;
  505. case GPT_COMPUTE_PROGRAM:
  506. inputDesc.shaderTarget = Xsc::ShaderTarget::ComputeShader;
  507. inputDesc.entryPoint = "csmain";
  508. break;
  509. default:
  510. break;
  511. }
  512. StringStream output;
  513. Xsc::ShaderOutput outputDesc;
  514. outputDesc.sourceCode = &output;
  515. outputDesc.options.autoBinding = vulkan;
  516. outputDesc.options.autoBindingStartSlot = startBindingSlot;
  517. outputDesc.options.separateShaders = true;
  518. outputDesc.options.separateSamplers = false;
  519. outputDesc.nameMangling.inputPrefix = "bs_";
  520. outputDesc.nameMangling.outputPrefix = "bs_";
  521. outputDesc.nameMangling.useAlwaysSemantics = true;
  522. outputDesc.nameMangling.renameBufferFields = true;
  523. if (vulkan)
  524. outputDesc.shaderVersion = Xsc::OutputShaderVersion::VKSL450;
  525. else
  526. outputDesc.shaderVersion = Xsc::OutputShaderVersion::GLSL450;
  527. XscLog log;
  528. Xsc::Reflection::ReflectionData reflectionData;
  529. bool compileSuccess = Xsc::CompileShader(inputDesc, outputDesc, &log, &reflectionData);
  530. if (!compileSuccess)
  531. {
  532. // If enabled, don't fail if entry point isn't found
  533. bool done = true;
  534. if(optionalEntry)
  535. {
  536. bool entryFound = false;
  537. for (auto& entry : reflectionData.functions)
  538. {
  539. if(entry.ident == inputDesc.entryPoint)
  540. {
  541. entryFound = true;
  542. break;
  543. }
  544. }
  545. if (!entryFound)
  546. done = false;
  547. }
  548. if (done)
  549. {
  550. StringStream logOutput;
  551. log.getMessages(logOutput);
  552. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  553. return "";
  554. }
  555. }
  556. for (auto& entry : reflectionData.constantBuffers)
  557. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  558. for (auto& entry : reflectionData.textures)
  559. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  560. for (auto& entry : reflectionData.storageBuffers)
  561. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  562. if(detectedTypes != nullptr)
  563. {
  564. for(auto& entry : reflectionData.functions)
  565. {
  566. if (entry.ident == "vsmain")
  567. detectedTypes->push_back(GPT_VERTEX_PROGRAM);
  568. else if (entry.ident == "fsmain")
  569. detectedTypes->push_back(GPT_FRAGMENT_PROGRAM);
  570. else if (entry.ident == "gsmain")
  571. detectedTypes->push_back(GPT_GEOMETRY_PROGRAM);
  572. else if (entry.ident == "dsmain")
  573. detectedTypes->push_back(GPT_DOMAIN_PROGRAM);
  574. else if (entry.ident == "hsmain")
  575. detectedTypes->push_back(GPT_HULL_PROGRAM);
  576. else if (entry.ident == "csmain")
  577. detectedTypes->push_back(GPT_COMPUTE_PROGRAM);
  578. }
  579. // If no entry points found, and error occurred, report error
  580. if(!compileSuccess && detectedTypes->size() == 0)
  581. {
  582. StringStream logOutput;
  583. log.getMessages(logOutput);
  584. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  585. return "";
  586. }
  587. }
  588. if (shaderDesc != nullptr)
  589. parseParameters(reflectionData, *shaderDesc);
  590. return output.str();
  591. }
  592. // Convert HLSL code to GLSL
  593. String HLSLtoGLSL(const String& hlsl, GpuProgramType type, bool vulkan, UINT32& startBindingSlot)
  594. {
  595. return crossCompile(hlsl, type, vulkan, false, startBindingSlot);
  596. }
  597. void reflectHLSL(const String& hlsl, SHADER_DESC& shaderDesc, Vector<GpuProgramType>& entryPoints)
  598. {
  599. UINT32 dummy = 0;
  600. crossCompile(hlsl, GPT_VERTEX_PROGRAM, false, true, dummy, &shaderDesc, &entryPoints);
  601. }
  602. BSLFXCompileResult BSLFXCompiler::compile(const String& name, const String& source,
  603. const UnorderedMap<String, String>& defines)
  604. {
  605. String parsedSource = source;
  606. // Run the lexer/parser and generate the AST
  607. ParseState* parseState = parseStateCreate();
  608. BSLFXCompileResult output = parseFX(parseState, parsedSource.c_str(), defines);
  609. if(!output.errorMessage.empty())
  610. parseStateDelete(parseState);
  611. else
  612. {
  613. // Only enable for debug purposes
  614. //SLFXDebugPrint(parseState->rootNode, "");
  615. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  616. {
  617. parseStateDelete(parseState);
  618. output.errorMessage = "Root not is null or not a shader.";
  619. return output;
  620. }
  621. // Parse global shader options & technique meta-data
  622. SHADER_DESC shaderDesc;
  623. Vector<pair<ASTFXNode*, TechniqueMetaData>> techniqueMetaData;
  624. //// Go in reverse because options are added in reverse order during parsing
  625. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  626. {
  627. NodeOption* option = &parseState->rootNode->options->entries[i];
  628. switch (option->type)
  629. {
  630. case OT_Options:
  631. parseOptions(option->value.nodePtr, shaderDesc);
  632. break;
  633. case OT_Technique:
  634. {
  635. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  636. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  637. techniqueMetaData.push_back(std::make_pair(option->value.nodePtr, metaData));
  638. break;
  639. }
  640. default:
  641. break;
  642. }
  643. }
  644. // Inherit variations from mixins
  645. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueMetaData.size());
  646. std::function<bool(const TechniqueMetaData&, TechniqueMetaData&)> parseInherited =
  647. [&](const TechniqueMetaData& metaData, TechniqueMetaData& combinedMetaData)
  648. {
  649. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  650. {
  651. const String& includes = *riter;
  652. UINT32 baseIdx = -1;
  653. for (UINT32 i = 0; i < (UINT32)techniqueMetaData.size(); i++)
  654. {
  655. auto& entry = techniqueMetaData[i];
  656. if (!entry.second.isMixin)
  657. continue;
  658. if (entry.second.name == includes)
  659. {
  660. bool matches =
  661. (entry.second.language == metaData.language ||
  662. entry.second.language == "Any") &&
  663. (entry.second.renderer == metaData.renderer ||
  664. entry.second.renderer == RendererAny);
  665. // We want the last matching technique, in order to allow techniques to override each other
  666. if (matches)
  667. baseIdx = i;
  668. }
  669. }
  670. if (baseIdx != (UINT32)-1)
  671. {
  672. auto& entry = techniqueMetaData[baseIdx];
  673. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  674. // include the same mixin)
  675. if (techniqueWasParsed[baseIdx])
  676. continue;
  677. if (!parseInherited(entry.second, combinedMetaData))
  678. return false;
  679. for(auto& variation : entry.second.variations)
  680. combinedMetaData.variations.push_back(variation);
  681. techniqueWasParsed[baseIdx] = true;
  682. }
  683. else
  684. {
  685. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  686. return false;
  687. }
  688. }
  689. return true;
  690. };
  691. for (auto& entry : techniqueMetaData)
  692. {
  693. TechniqueMetaData& metaData = entry.second;
  694. if (metaData.isMixin)
  695. continue;
  696. bs_zero_out(techniqueWasParsed, techniqueMetaData.size());
  697. TechniqueMetaData combinedMetaData = metaData;
  698. if (!parseInherited(metaData, combinedMetaData))
  699. {
  700. parseStateDelete(parseState);
  701. bs_stack_free(techniqueWasParsed);
  702. return output;
  703. }
  704. entry.second = combinedMetaData;
  705. }
  706. bs_stack_free(techniqueWasParsed);
  707. parseStateDelete(parseState);
  708. // Build a list of different variations and re-parse the source using the relevant defines
  709. Vector<SPtr<Technique>> techniques;
  710. UnorderedSet<String> includes;
  711. for (auto& entry : techniqueMetaData)
  712. {
  713. TechniqueMetaData& metaData = entry.second;
  714. if (metaData.isMixin)
  715. continue;
  716. // Generate a list of variations
  717. Vector<ShaderVariation> variations;
  718. if (metaData.variations.empty())
  719. variations.push_back(ShaderVariation());
  720. else
  721. {
  722. Vector<const VariationData*> todo;
  723. for (UINT32 i = 0; i < (UINT32)metaData.variations.size(); i++)
  724. todo.push_back(&metaData.variations[i]);
  725. while (!todo.empty())
  726. {
  727. const VariationData* current = todo.back();
  728. todo.erase(todo.end() - 1);
  729. // Variation parameter that's either defined or isn't
  730. if (current->values.empty())
  731. {
  732. // This is the first variation parameter, register new variations
  733. if (variations.empty())
  734. {
  735. ShaderVariation a;
  736. ShaderVariation b;
  737. b.addParam(ShaderVariation::Param(current->identifier, 1));
  738. variations.push_back(a);
  739. variations.push_back(b);
  740. }
  741. else // Duplicate existing variations, and add the parameter
  742. {
  743. UINT32 numVariations = (UINT32)variations.size();
  744. for (UINT32 i = 0; i < numVariations; i++)
  745. {
  746. // Make a copy
  747. variations.push_back(variations[i]);
  748. // Add the parameter to existing variation
  749. variations[i].addParam(ShaderVariation::Param(current->identifier, 1));
  750. }
  751. }
  752. }
  753. else // Variation parameter with multiple values
  754. {
  755. // This is the first variation parameter, register new variations
  756. if (variations.empty())
  757. {
  758. for (UINT32 i = 0; i < (UINT32)current->values.size(); i++)
  759. {
  760. ShaderVariation variation;
  761. variation.addParam(ShaderVariation::Param(current->identifier, current->values[i]));
  762. variations.push_back(variation);
  763. }
  764. }
  765. else // Duplicate existing variations, and add the parameter
  766. {
  767. UINT32 numVariations = (UINT32)variations.size();
  768. for (UINT32 i = 0; i < numVariations; i++)
  769. {
  770. for (UINT32 j = 1; j < (UINT32)current->values.size(); j++)
  771. {
  772. ShaderVariation copy = variations[i];
  773. copy.addParam(ShaderVariation::Param(current->identifier, current->values[j]));
  774. variations.push_back(copy);
  775. }
  776. variations[i].addParam(ShaderVariation::Param(current->identifier, current->values[0]));
  777. }
  778. }
  779. }
  780. }
  781. }
  782. // For every variation, re-parse the file with relevant defines
  783. for(auto& variation : variations)
  784. {
  785. UnorderedMap<String, String> globalDefines = defines;
  786. UnorderedMap<String, String> variationDefines = variation.getDefines().getAll();
  787. for(auto& define : variationDefines)
  788. globalDefines[define.first] = define.second;
  789. ParseState* variationParseState = parseStateCreate();
  790. output = parseFX(variationParseState, parsedSource.c_str(), globalDefines);
  791. if (!output.errorMessage.empty())
  792. parseStateDelete(variationParseState);
  793. else
  794. {
  795. Vector<String> codeBlocks;
  796. CodeString* codeString = variationParseState->codeStrings;
  797. while (codeString != nullptr)
  798. {
  799. while ((INT32)codeBlocks.size() <= codeString->index)
  800. codeBlocks.push_back(String());
  801. codeBlocks[codeString->index] = String(codeString->code, codeString->size);
  802. codeString = codeString->next;
  803. }
  804. output = parseTechnique(variationParseState, entry.second.name, codeBlocks, variation, techniques,
  805. includes, shaderDesc);
  806. if(!output.errorMessage.empty())
  807. return output;
  808. }
  809. }
  810. }
  811. // Generate a shader from the parsed techniques
  812. Vector<String> includeArray;
  813. for (auto& entry : includes)
  814. includeArray.push_back(entry);
  815. output.shader = Shader::_createPtr(name, shaderDesc, techniques);
  816. output.shader->setIncludeFiles(includeArray);
  817. // Verify GPU programs compile correctly
  818. StringStream gpuProgError;
  819. bool hasError = false;
  820. if (output.shader != nullptr)
  821. {
  822. Vector<SPtr<Technique>> techniques = output.shader->getCompatibleTechniques();
  823. for (auto& technique : techniques)
  824. {
  825. UINT32 numPasses = technique->getNumPasses();
  826. for (UINT32 i = 0; i < numPasses; i++)
  827. {
  828. SPtr<Pass> pass = technique->getPass(i);
  829. auto checkCompileStatus = [&](const String& prefix, const SPtr<GpuProgram>& prog)
  830. {
  831. if (prog != nullptr)
  832. {
  833. prog->blockUntilCoreInitialized();
  834. if (!prog->isCompiled())
  835. {
  836. hasError = true;
  837. gpuProgError << prefix << ": " << prog->getCompileErrorMessage() << std::endl;
  838. }
  839. }
  840. };
  841. checkCompileStatus("Vertex program", pass->getVertexProgram());
  842. checkCompileStatus("Fragment program", pass->getFragmentProgram());
  843. checkCompileStatus("Geometry program", pass->getGeometryProgram());
  844. checkCompileStatus("Hull program", pass->getHullProgram());
  845. checkCompileStatus("Domain program", pass->getDomainProgram());
  846. checkCompileStatus("Compute program", pass->getComputeProgram());
  847. }
  848. }
  849. }
  850. if (hasError)
  851. {
  852. output.errorMessage = "Failed compiling GPU program(s): " + gpuProgError.str();
  853. output.errorLine = 0;
  854. output.errorColumn = 0;
  855. }
  856. }
  857. return output;
  858. }
  859. BSLFXCompileResult BSLFXCompiler::parseFX(ParseState* parseState, const char* source, const UnorderedMap<String, String>& defines)
  860. {
  861. for(auto& define : defines)
  862. {
  863. if (define.first.size() == 0)
  864. continue;
  865. addDefine(parseState, define.first.c_str());
  866. if(define.second.size() > 0)
  867. addDefineExpr(parseState, define.second.c_str());
  868. }
  869. yyscan_t scanner;
  870. YY_BUFFER_STATE state;
  871. BSLFXCompileResult output;
  872. if (yylex_init_extra(parseState, &scanner))
  873. {
  874. output.errorMessage = "Internal error: Lexer failed to initialize.";
  875. return output;
  876. }
  877. // If debug output from lexer is needed uncomment this and add %debug option to lexer file
  878. //yyset_debug(true, scanner);
  879. // If debug output from parser is needed uncomment this and add %debug option to parser file
  880. //yydebug = true;
  881. state = yy_scan_string(source, scanner);
  882. if (yyparse(parseState, scanner))
  883. {
  884. if (parseState->hasError > 0)
  885. {
  886. output.errorMessage = parseState->errorMessage;
  887. output.errorLine = parseState->errorLine;
  888. output.errorColumn = parseState->errorColumn;
  889. if (parseState->errorFile != nullptr)
  890. output.errorFile = parseState->errorFile;
  891. }
  892. else
  893. output.errorMessage = "Internal error: Parsing failed.";
  894. return output;
  895. }
  896. yy_delete_buffer(state, scanner);
  897. yylex_destroy(scanner);
  898. return output;
  899. }
  900. BSLFXCompiler::TechniqueMetaData BSLFXCompiler::parseTechniqueMetaData(ASTFXNode* technique)
  901. {
  902. TechniqueMetaData metaData;
  903. metaData.renderer = RendererAny;
  904. metaData.language = "hlsl";
  905. metaData.isMixin = technique->type == NT_Mixin;
  906. for (int i = 0; i < technique->options->count; i++)
  907. {
  908. NodeOption* option = &technique->options->entries[i];
  909. switch (option->type)
  910. {
  911. case OT_Renderer:
  912. metaData.renderer = parseRenderer(removeQuotes(option->value.strValue));
  913. break;
  914. case OT_Tags:
  915. {
  916. ASTFXNode* tagsNode = option->value.nodePtr;
  917. for (int j = 0; j < tagsNode->options->count; j++)
  918. {
  919. NodeOption* tagOption = &tagsNode->options->entries[j];
  920. if (tagOption->type == OT_TagValue)
  921. metaData.tags.push_back(removeQuotes(tagOption->value.strValue));
  922. }
  923. }
  924. break;
  925. case OT_Variations:
  926. {
  927. ASTFXNode* variationsNode = option->value.nodePtr;
  928. for (int j = 0; j < variationsNode->options->count; j++)
  929. {
  930. NodeOption* variationOption = &variationsNode->options->entries[j];
  931. if(variationOption->type == OT_Variation)
  932. parseVariations(metaData, variationOption->value.nodePtr);
  933. }
  934. }
  935. break;
  936. case OT_Identifier:
  937. metaData.name = option->value.strValue;
  938. break;
  939. case OT_Mixin:
  940. metaData.includes.push_back(option->value.strValue);
  941. break;
  942. default:
  943. break;
  944. }
  945. }
  946. return metaData;
  947. }
  948. void BSLFXCompiler::parseVariations(TechniqueMetaData& metaData, ASTFXNode* variations)
  949. {
  950. assert(variations->type == NT_Variation);
  951. VariationData variationData;
  952. for (int i = 0; i < variations->options->count; i++)
  953. {
  954. NodeOption* option = &variations->options->entries[i];
  955. switch (option->type)
  956. {
  957. case OT_Identifier:
  958. variationData.identifier = option->value.strValue;
  959. break;
  960. case OT_VariationValue:
  961. variationData.values.push_back(option->value.intValue);
  962. break;
  963. default:
  964. break;
  965. }
  966. }
  967. if (!variationData.identifier.empty())
  968. metaData.variations.push_back(variationData);
  969. }
  970. StringID BSLFXCompiler::parseRenderer(const String& name)
  971. {
  972. if (name == "Any")
  973. return RendererAny;
  974. else if (name == "Default")
  975. return RendererDefault;
  976. return RendererAny;
  977. }
  978. QueueSortType BSLFXCompiler::parseSortType(CullAndSortModeValue sortType)
  979. {
  980. switch (sortType)
  981. {
  982. case CASV_BackToFront:
  983. return QueueSortType::BackToFront;
  984. case CASV_FrontToBack:
  985. return QueueSortType::FrontToBack;
  986. case CASV_None:
  987. return QueueSortType::None;
  988. default:
  989. break;
  990. }
  991. return QueueSortType::None;
  992. }
  993. CompareFunction BSLFXCompiler::parseCompFunc(CompFuncValue compFunc)
  994. {
  995. switch (compFunc)
  996. {
  997. case CFV_Pass:
  998. return CMPF_ALWAYS_PASS;
  999. case CFV_Fail:
  1000. return CMPF_ALWAYS_FAIL;
  1001. case CFV_LT:
  1002. return CMPF_LESS;
  1003. case CFV_LTE:
  1004. return CMPF_LESS_EQUAL;
  1005. case CFV_EQ:
  1006. return CMPF_EQUAL;
  1007. case CFV_NEQ:
  1008. return CMPF_NOT_EQUAL;
  1009. case CFV_GT:
  1010. return CMPF_GREATER;
  1011. case CFV_GTE:
  1012. return CMPF_GREATER_EQUAL;
  1013. }
  1014. return CMPF_ALWAYS_PASS;
  1015. }
  1016. BlendFactor BSLFXCompiler::parseBlendFactor(OpValue factor)
  1017. {
  1018. switch (factor)
  1019. {
  1020. case OV_One:
  1021. return BF_ONE;
  1022. case OV_Zero:
  1023. return BF_ZERO;
  1024. case OV_DestColor:
  1025. return BF_DEST_COLOR;
  1026. case OV_SrcColor:
  1027. return BF_SOURCE_COLOR;
  1028. case OV_InvDestColor:
  1029. return BF_INV_DEST_COLOR;
  1030. case OV_InvSrcColor:
  1031. return BF_INV_SOURCE_COLOR;
  1032. case OV_DestAlpha:
  1033. return BF_DEST_ALPHA;
  1034. case OV_SrcAlpha:
  1035. return BF_SOURCE_ALPHA;
  1036. case OV_InvDestAlpha:
  1037. return BF_INV_DEST_ALPHA;
  1038. case OV_InvSrcAlpha:
  1039. return BF_INV_SOURCE_ALPHA;
  1040. default:
  1041. break;
  1042. }
  1043. return BF_ONE;
  1044. }
  1045. BlendOperation BSLFXCompiler::parseBlendOp(BlendOpValue op)
  1046. {
  1047. switch (op)
  1048. {
  1049. case BOV_Add:
  1050. return BO_ADD;
  1051. case BOV_Max:
  1052. return BO_MAX;
  1053. case BOV_Min:
  1054. return BO_MIN;
  1055. case BOV_Subtract:
  1056. return BO_SUBTRACT;
  1057. case BOV_RevSubtract:
  1058. return BO_REVERSE_SUBTRACT;
  1059. }
  1060. return BO_ADD;
  1061. }
  1062. StencilOperation BSLFXCompiler::parseStencilOp(OpValue op)
  1063. {
  1064. switch (op)
  1065. {
  1066. case OV_Keep:
  1067. return SOP_KEEP;
  1068. case OV_Zero:
  1069. return SOP_ZERO;
  1070. case OV_Replace:
  1071. return SOP_REPLACE;
  1072. case OV_Incr:
  1073. return SOP_INCREMENT;
  1074. case OV_Decr:
  1075. return SOP_DECREMENT;
  1076. case OV_IncrWrap:
  1077. return SOP_INCREMENT_WRAP;
  1078. case OV_DecrWrap:
  1079. return SOP_DECREMENT_WRAP;
  1080. case OV_Invert:
  1081. return SOP_INVERT;
  1082. default:
  1083. break;
  1084. }
  1085. return SOP_KEEP;
  1086. }
  1087. CullingMode BSLFXCompiler::parseCullMode(CullAndSortModeValue cm)
  1088. {
  1089. switch (cm)
  1090. {
  1091. case CASV_None:
  1092. return CULL_NONE;
  1093. case CASV_CW:
  1094. return CULL_CLOCKWISE;
  1095. case CASV_CCW:
  1096. return CULL_COUNTERCLOCKWISE;
  1097. default:
  1098. break;
  1099. }
  1100. return CULL_COUNTERCLOCKWISE;
  1101. }
  1102. PolygonMode BSLFXCompiler::parseFillMode(FillModeValue fm)
  1103. {
  1104. if (fm == FMV_Wire)
  1105. return PM_WIREFRAME;
  1106. return PM_SOLID;
  1107. }
  1108. void BSLFXCompiler::parseStencilFront(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1109. {
  1110. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1111. return;
  1112. for (int i = 0; i < stencilOpNode->options->count; i++)
  1113. {
  1114. NodeOption* option = &stencilOpNode->options->entries[i];
  1115. switch (option->type)
  1116. {
  1117. case OT_Fail:
  1118. desc.frontStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1119. break;
  1120. case OT_ZFail:
  1121. desc.frontStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1122. break;
  1123. case OT_PassOp:
  1124. desc.frontStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1125. break;
  1126. case OT_CompareFunc:
  1127. desc.frontStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1128. break;
  1129. default:
  1130. break;
  1131. }
  1132. }
  1133. }
  1134. void BSLFXCompiler::parseStencilBack(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1135. {
  1136. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1137. return;
  1138. for (int i = 0; i < stencilOpNode->options->count; i++)
  1139. {
  1140. NodeOption* option = &stencilOpNode->options->entries[i];
  1141. switch (option->type)
  1142. {
  1143. case OT_Fail:
  1144. desc.backStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1145. break;
  1146. case OT_ZFail:
  1147. desc.backStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1148. break;
  1149. case OT_PassOp:
  1150. desc.backStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1151. break;
  1152. case OT_CompareFunc:
  1153. desc.backStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1154. break;
  1155. default:
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. void BSLFXCompiler::parseColorBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1161. {
  1162. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1163. return;
  1164. for (int i = 0; i < blendDefNode->options->count; i++)
  1165. {
  1166. NodeOption* option = &blendDefNode->options->entries[i];
  1167. switch (option->type)
  1168. {
  1169. case OT_Source:
  1170. desc.srcBlend = parseBlendFactor((OpValue)option->value.intValue);
  1171. break;
  1172. case OT_Dest:
  1173. desc.dstBlend = parseBlendFactor((OpValue)option->value.intValue);
  1174. break;
  1175. case OT_Op:
  1176. desc.blendOp = parseBlendOp((BlendOpValue)option->value.intValue);
  1177. break;
  1178. default:
  1179. break;
  1180. }
  1181. }
  1182. }
  1183. void BSLFXCompiler::parseAlphaBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1184. {
  1185. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1186. return;
  1187. for (int i = 0; i < blendDefNode->options->count; i++)
  1188. {
  1189. NodeOption* option = &blendDefNode->options->entries[i];
  1190. switch (option->type)
  1191. {
  1192. case OT_Source:
  1193. desc.srcBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1194. break;
  1195. case OT_Dest:
  1196. desc.dstBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1197. break;
  1198. case OT_Op:
  1199. desc.blendOpAlpha = parseBlendOp((BlendOpValue)option->value.intValue);
  1200. break;
  1201. default:
  1202. break;
  1203. }
  1204. }
  1205. }
  1206. void BSLFXCompiler::parseRenderTargetBlendState(BLEND_STATE_DESC& desc, ASTFXNode* targetNode)
  1207. {
  1208. if (targetNode == nullptr || targetNode->type != NT_Target)
  1209. return;
  1210. UINT32 index = 0;
  1211. for (int i = 0; i < targetNode->options->count; i++)
  1212. {
  1213. NodeOption* option = &targetNode->options->entries[i];
  1214. switch (option->type)
  1215. {
  1216. case OT_Index:
  1217. index = option->value.intValue;
  1218. break;
  1219. default:
  1220. break;
  1221. }
  1222. }
  1223. if (index >= BS_MAX_MULTIPLE_RENDER_TARGETS)
  1224. return;
  1225. RENDER_TARGET_BLEND_STATE_DESC& rtDesc = desc.renderTargetDesc[index];
  1226. for (int i = 0; i < targetNode->options->count; i++)
  1227. {
  1228. NodeOption* option = &targetNode->options->entries[i];
  1229. switch (option->type)
  1230. {
  1231. case OT_Enabled:
  1232. rtDesc.blendEnable = option->value.intValue > 0;
  1233. break;
  1234. case OT_Color:
  1235. parseColorBlendDef(rtDesc, option->value.nodePtr);
  1236. break;
  1237. case OT_Alpha:
  1238. parseAlphaBlendDef(rtDesc, option->value.nodePtr);
  1239. break;
  1240. case OT_WriteMask:
  1241. rtDesc.renderTargetWriteMask = option->value.intValue;
  1242. break;
  1243. default:
  1244. break;
  1245. }
  1246. }
  1247. }
  1248. bool BSLFXCompiler::parseBlendState(PassData& desc, ASTFXNode* blendNode)
  1249. {
  1250. if (blendNode == nullptr || blendNode->type != NT_Blend)
  1251. return false;
  1252. bool isDefault = true;
  1253. for (int i = 0; i < blendNode->options->count; i++)
  1254. {
  1255. NodeOption* option = &blendNode->options->entries[i];
  1256. switch (option->type)
  1257. {
  1258. case OT_AlphaToCoverage:
  1259. desc.blendDesc.alphaToCoverageEnable = option->value.intValue > 0;
  1260. isDefault = false;
  1261. break;
  1262. case OT_IndependantBlend:
  1263. desc.blendDesc.independantBlendEnable = option->value.intValue > 0;
  1264. isDefault = false;
  1265. break;
  1266. case OT_Target:
  1267. parseRenderTargetBlendState(desc.blendDesc, option->value.nodePtr);
  1268. isDefault = false;
  1269. break;
  1270. default:
  1271. break;
  1272. }
  1273. }
  1274. return !isDefault;
  1275. }
  1276. bool BSLFXCompiler::parseRasterizerState(PassData& desc, ASTFXNode* rasterNode)
  1277. {
  1278. if (rasterNode == nullptr || rasterNode->type != NT_Raster)
  1279. return false;
  1280. bool isDefault = true;
  1281. for (int i = 0; i < rasterNode->options->count; i++)
  1282. {
  1283. NodeOption* option = &rasterNode->options->entries[i];
  1284. switch (option->type)
  1285. {
  1286. case OT_FillMode:
  1287. desc.rasterizerDesc.polygonMode = parseFillMode((FillModeValue)option->value.intValue);
  1288. isDefault = false;
  1289. break;
  1290. case OT_CullMode:
  1291. desc.rasterizerDesc.cullMode = parseCullMode((CullAndSortModeValue)option->value.intValue);
  1292. isDefault = false;
  1293. break;
  1294. case OT_DepthBias:
  1295. desc.rasterizerDesc.depthBias = option->value.floatValue;
  1296. isDefault = false;
  1297. break;
  1298. case OT_SDepthBias:
  1299. desc.rasterizerDesc.slopeScaledDepthBias = option->value.floatValue;
  1300. isDefault = false;
  1301. break;
  1302. case OT_DepthClip:
  1303. desc.rasterizerDesc.depthClipEnable = option->value.intValue > 0;
  1304. isDefault = false;
  1305. break;
  1306. case OT_Scissor:
  1307. desc.rasterizerDesc.scissorEnable = option->value.intValue > 0;
  1308. isDefault = false;
  1309. break;
  1310. case OT_Multisample:
  1311. desc.rasterizerDesc.multisampleEnable = option->value.intValue > 0;
  1312. isDefault = false;
  1313. break;
  1314. case OT_AALine:
  1315. desc.rasterizerDesc.antialiasedLineEnable = option->value.intValue > 0;
  1316. isDefault = false;
  1317. break;
  1318. default:
  1319. break;
  1320. }
  1321. }
  1322. return !isDefault;
  1323. }
  1324. bool BSLFXCompiler::parseDepthState(PassData& passData, ASTFXNode* depthNode)
  1325. {
  1326. if (depthNode == nullptr || depthNode->type != NT_Depth)
  1327. return false;
  1328. bool isDefault = true;
  1329. for (int i = 0; i < depthNode->options->count; i++)
  1330. {
  1331. NodeOption* option = &depthNode->options->entries[i];
  1332. switch (option->type)
  1333. {
  1334. case OT_DepthRead:
  1335. passData.depthStencilDesc.depthReadEnable = option->value.intValue > 0;
  1336. isDefault = false;
  1337. break;
  1338. case OT_DepthWrite:
  1339. passData.depthStencilDesc.depthWriteEnable = option->value.intValue > 0;
  1340. isDefault = false;
  1341. break;
  1342. case OT_CompareFunc:
  1343. passData.depthStencilDesc.depthComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1344. isDefault = false;
  1345. break;
  1346. default:
  1347. break;
  1348. }
  1349. }
  1350. return !isDefault;
  1351. }
  1352. bool BSLFXCompiler::parseStencilState(PassData& passData, ASTFXNode* stencilNode)
  1353. {
  1354. if (stencilNode == nullptr || stencilNode->type != NT_Stencil)
  1355. return false;
  1356. bool isDefault = true;
  1357. for (int i = 0; i < stencilNode->options->count; i++)
  1358. {
  1359. NodeOption* option = &stencilNode->options->entries[i];
  1360. switch (option->type)
  1361. {
  1362. case OT_Enabled:
  1363. passData.depthStencilDesc.stencilEnable = option->value.intValue > 0;
  1364. isDefault = false;
  1365. break;
  1366. case OT_StencilReadMask:
  1367. passData.depthStencilDesc.stencilReadMask = (UINT8)option->value.intValue;
  1368. isDefault = false;
  1369. break;
  1370. case OT_StencilWriteMask:
  1371. passData.depthStencilDesc.stencilWriteMask = (UINT8)option->value.intValue;
  1372. isDefault = false;
  1373. break;
  1374. case OT_StencilOpFront:
  1375. parseStencilFront(passData.depthStencilDesc, option->value.nodePtr);
  1376. isDefault = false;
  1377. break;
  1378. case OT_StencilOpBack:
  1379. parseStencilBack(passData.depthStencilDesc, option->value.nodePtr);
  1380. isDefault = false;
  1381. break;
  1382. case OT_StencilRef:
  1383. passData.stencilRefValue = option->value.intValue;
  1384. break;
  1385. default:
  1386. break;
  1387. }
  1388. }
  1389. return !isDefault;
  1390. }
  1391. void BSLFXCompiler::parseCodeBlock(ASTFXNode* codeNode, const Vector<String>& codeBlocks, PassData& passData)
  1392. {
  1393. if (codeNode == nullptr || (codeNode->type != NT_Code))
  1394. {
  1395. return;
  1396. }
  1397. UINT32 index = (UINT32)-1;
  1398. for (int j = 0; j < codeNode->options->count; j++)
  1399. {
  1400. if (codeNode->options->entries[j].type == OT_Index)
  1401. index = codeNode->options->entries[j].value.intValue;
  1402. }
  1403. if (index != (UINT32)-1 && index < (UINT32)codeBlocks.size())
  1404. {
  1405. switch (codeNode->type)
  1406. {
  1407. case NT_Code:
  1408. passData.code += codeBlocks[index];
  1409. break;
  1410. default:
  1411. break;
  1412. }
  1413. }
  1414. }
  1415. void BSLFXCompiler::parsePass(ASTFXNode* passNode, const Vector<String>& codeBlocks, PassData& passData)
  1416. {
  1417. if (passNode == nullptr || passNode->type != NT_Pass)
  1418. return;
  1419. for (int i = 0; i < passNode->options->count; i++)
  1420. {
  1421. NodeOption* option = &passNode->options->entries[i];
  1422. switch (option->type)
  1423. {
  1424. case OT_Blend:
  1425. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1426. break;
  1427. case OT_Raster:
  1428. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1429. break;
  1430. case OT_Depth:
  1431. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1432. break;
  1433. case OT_Stencil:
  1434. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1435. break;
  1436. case OT_Code:
  1437. parseCodeBlock(option->value.nodePtr, codeBlocks, passData);
  1438. break;
  1439. default:
  1440. break;
  1441. }
  1442. }
  1443. }
  1444. void BSLFXCompiler::parseTechnique(ASTFXNode* techniqueNode, const Vector<String>& codeBlocks, TechniqueData& techniqueData)
  1445. {
  1446. if (techniqueNode == nullptr || (techniqueNode->type != NT_Technique && techniqueNode->type != NT_Mixin))
  1447. return;
  1448. // There must always be at least one pass
  1449. if(techniqueData.passes.empty())
  1450. {
  1451. techniqueData.passes.push_back(PassData());
  1452. techniqueData.passes.back().seqIdx = 0;
  1453. }
  1454. PassData combinedCommonPassData;
  1455. UINT32 nextPassIdx = 0;
  1456. // Go in reverse because options are added in reverse order during parsing
  1457. for (int i = techniqueNode->options->count - 1; i >= 0; i--)
  1458. {
  1459. NodeOption* option = &techniqueNode->options->entries[i];
  1460. switch (option->type)
  1461. {
  1462. case OT_Pass:
  1463. {
  1464. UINT32 passIdx = nextPassIdx;
  1465. PassData* passData = nullptr;
  1466. for (auto& entry : techniqueData.passes)
  1467. {
  1468. if (entry.seqIdx == passIdx)
  1469. passData = &entry;
  1470. }
  1471. if (passData == nullptr)
  1472. {
  1473. techniqueData.passes.push_back(PassData());
  1474. passData = &techniqueData.passes.back();
  1475. passData->seqIdx = passIdx;
  1476. }
  1477. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  1478. passData->code = combinedCommonPassData.code + passData->code;
  1479. ASTFXNode* passNode = option->value.nodePtr;
  1480. parsePass(passNode, codeBlocks, *passData);
  1481. }
  1482. break;
  1483. case OT_Code:
  1484. {
  1485. PassData commonPassData;
  1486. parseCodeBlock(option->value.nodePtr, codeBlocks, commonPassData);
  1487. for (auto& passData : techniqueData.passes)
  1488. passData.code += commonPassData.code;
  1489. combinedCommonPassData.code += commonPassData.code;
  1490. }
  1491. break;
  1492. default:
  1493. break;
  1494. }
  1495. }
  1496. // Parse common pass states
  1497. for (int i = 0; i < techniqueNode->options->count; i++)
  1498. {
  1499. NodeOption* option = &techniqueNode->options->entries[i];
  1500. switch (option->type)
  1501. {
  1502. case OT_Blend:
  1503. for (auto& passData : techniqueData.passes)
  1504. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1505. break;
  1506. case OT_Raster:
  1507. for (auto& passData : techniqueData.passes)
  1508. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1509. break;
  1510. case OT_Depth:
  1511. for (auto& passData : techniqueData.passes)
  1512. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1513. break;
  1514. case OT_Stencil:
  1515. for (auto& passData : techniqueData.passes)
  1516. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1517. break;
  1518. default:
  1519. break;
  1520. }
  1521. }
  1522. }
  1523. void BSLFXCompiler::parseOptions(ASTFXNode* optionsNode, SHADER_DESC& shaderDesc)
  1524. {
  1525. if (optionsNode == nullptr || optionsNode->type != NT_Options)
  1526. return;
  1527. for (int i = optionsNode->options->count - 1; i >= 0; i--)
  1528. {
  1529. NodeOption* option = &optionsNode->options->entries[i];
  1530. switch (option->type)
  1531. {
  1532. case OT_Separable:
  1533. shaderDesc.separablePasses = option->value.intValue > 1;
  1534. break;
  1535. case OT_Sort:
  1536. shaderDesc.queueSortType = parseSortType((CullAndSortModeValue)option->value.intValue);
  1537. break;
  1538. case OT_Priority:
  1539. shaderDesc.queuePriority = option->value.intValue;
  1540. break;
  1541. case OT_Transparent:
  1542. shaderDesc.flags |= (UINT32)ShaderFlags::Transparent;
  1543. break;
  1544. default:
  1545. break;
  1546. }
  1547. }
  1548. }
  1549. BSLFXCompileResult BSLFXCompiler::parseTechnique(ParseState* parseState, const String& name,
  1550. const Vector<String>& codeBlocks, const ShaderVariation& variation, Vector<SPtr<Technique>>& techniques,
  1551. UnorderedSet<String>& includes, SHADER_DESC& shaderDesc)
  1552. {
  1553. BSLFXCompileResult output;
  1554. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  1555. {
  1556. parseStateDelete(parseState);
  1557. output.errorMessage = "Root not is null or not a shader.";
  1558. return output;
  1559. }
  1560. Vector<pair<ASTFXNode*, TechniqueData>> techniqueData;
  1561. // Go in reverse because options are added in reverse order during parsing
  1562. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  1563. {
  1564. NodeOption* option = &parseState->rootNode->options->entries[i];
  1565. switch (option->type)
  1566. {
  1567. case OT_Technique:
  1568. {
  1569. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  1570. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  1571. // Skip all techniques except the one we're parsing
  1572. if(metaData.name != name && !metaData.isMixin)
  1573. continue;
  1574. techniqueData.push_back(std::make_pair(option->value.nodePtr, TechniqueData()));
  1575. TechniqueData& data = techniqueData.back().second;
  1576. data.metaData = metaData;
  1577. break;
  1578. }
  1579. default:
  1580. break;
  1581. }
  1582. }
  1583. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueData.size());
  1584. std::function<bool(const TechniqueMetaData&, TechniqueData&)> parseInherited =
  1585. [&](const TechniqueMetaData& metaData, TechniqueData& outTechnique)
  1586. {
  1587. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  1588. {
  1589. const String& includes = *riter;
  1590. UINT32 baseIdx = -1;
  1591. for(UINT32 i = 0; i < (UINT32)techniqueData.size(); i++)
  1592. {
  1593. auto& entry = techniqueData[i];
  1594. if (!entry.second.metaData.isMixin)
  1595. continue;
  1596. if (entry.second.metaData.name == includes)
  1597. {
  1598. bool matches =
  1599. (entry.second.metaData.language == metaData.language ||
  1600. entry.second.metaData.language == "Any") &&
  1601. (entry.second.metaData.renderer == metaData.renderer ||
  1602. entry.second.metaData.renderer == RendererAny);
  1603. // We want the last matching technique, in order to allow techniques to override each other
  1604. if (matches)
  1605. baseIdx = i;
  1606. }
  1607. }
  1608. if (baseIdx != (UINT32)-1)
  1609. {
  1610. auto& entry = techniqueData[baseIdx];
  1611. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  1612. // include the same mixin)
  1613. if (techniqueWasParsed[baseIdx])
  1614. continue;
  1615. if (!parseInherited(entry.second.metaData, outTechnique))
  1616. return false;
  1617. parseTechnique(entry.first, codeBlocks, outTechnique);
  1618. techniqueWasParsed[baseIdx] = true;
  1619. }
  1620. else
  1621. {
  1622. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  1623. return false;
  1624. }
  1625. }
  1626. return true;
  1627. };
  1628. // Actually parse techniques
  1629. for (auto& entry : techniqueData)
  1630. {
  1631. const TechniqueMetaData& metaData = entry.second.metaData;
  1632. if (metaData.isMixin)
  1633. continue;
  1634. bs_zero_out(techniqueWasParsed, techniqueData.size());
  1635. if (!parseInherited(metaData, entry.second))
  1636. {
  1637. parseStateDelete(parseState);
  1638. bs_stack_free(techniqueWasParsed);
  1639. return output;
  1640. }
  1641. parseTechnique(entry.first, codeBlocks, entry.second);
  1642. }
  1643. bs_stack_free(techniqueWasParsed);
  1644. IncludeLink* includeLink = parseState->includes;
  1645. while(includeLink != nullptr)
  1646. {
  1647. String includeFilename = includeLink->data->filename;
  1648. auto iterFind = std::find(includes.begin(), includes.end(), includeFilename);
  1649. if (iterFind == includes.end())
  1650. includes.insert(includeFilename);
  1651. includeLink = includeLink->next;
  1652. }
  1653. parseStateDelete(parseState);
  1654. // Parse extended HLSL code and generate per-program code, also convert to GLSL/VKSL
  1655. UINT32 end = (UINT32)techniqueData.size();
  1656. for(UINT32 i = 0; i < end; i++)
  1657. {
  1658. const TechniqueMetaData& metaData = techniqueData[i].second.metaData;
  1659. if (metaData.isMixin)
  1660. continue;
  1661. TechniqueData& hlslTechnique = techniqueData[i].second;
  1662. TechniqueData glslTechnique = techniqueData[i].second;
  1663. glslTechnique.metaData.language = "glsl";
  1664. TechniqueData vkslTechnique = techniqueData[i].second;
  1665. vkslTechnique.metaData.language = "vksl";
  1666. UINT32 numPasses = (UINT32)hlslTechnique.passes.size();
  1667. for(UINT32 j = 0; j < numPasses; j++)
  1668. {
  1669. PassData& hlslPassData = hlslTechnique.passes[j];
  1670. PassData& glslPassData = glslTechnique.passes[j];
  1671. PassData& vkslPassData = vkslTechnique.passes[j];
  1672. // Clean non-standard HLSL
  1673. static const std::regex regex("\\[\\s*layout\\s*\\(.*\\)\\s*\\]|\\[\\s*internal\\s*\\]|\\[\\s*color\\s*\\]|\\[\\s*alias\\s*\\(.*\\)\\s*\\]");
  1674. hlslPassData.code = regex_replace(hlslPassData.code, regex, "");
  1675. // Find valid entry points and parameters
  1676. // Note: XShaderCompiler needs to do a full pass when doing reflection, and for each individual program
  1677. // type. If performance is ever important here it could be good to update XShaderCompiler so it can
  1678. // somehow save the AST and then re-use it for multiple actions.
  1679. Vector<GpuProgramType> types;
  1680. reflectHLSL(glslPassData.code, shaderDesc, types);
  1681. UINT32 glslBinding = 0;
  1682. UINT32 vkslBinding = 0;
  1683. // Cross-compile for all detected shader types
  1684. // Note: I'm just copying HLSL code as-is. This code will contain all entry points which could have
  1685. // an effect on compile time. It would be ideal to remove dead code depending on program type. This would
  1686. // involve adding a HLSL code generator to XShaderCompiler.
  1687. for(auto& type : types)
  1688. {
  1689. switch(type)
  1690. {
  1691. case GPT_VERTEX_PROGRAM:
  1692. hlslPassData.vertexCode = hlslPassData.code;
  1693. glslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM, false, glslBinding);
  1694. vkslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM, true, vkslBinding);
  1695. break;
  1696. case GPT_FRAGMENT_PROGRAM:
  1697. hlslPassData.fragmentCode = hlslPassData.code;
  1698. glslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM, false, glslBinding);
  1699. vkslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM, true, vkslBinding);
  1700. break;
  1701. case GPT_GEOMETRY_PROGRAM:
  1702. hlslPassData.geometryCode = hlslPassData.code;
  1703. glslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM, false, glslBinding);
  1704. vkslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM, true, vkslBinding);
  1705. break;
  1706. case GPT_HULL_PROGRAM:
  1707. hlslPassData.hullCode = hlslPassData.code;
  1708. glslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM, false, glslBinding);
  1709. vkslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM, true, vkslBinding);
  1710. break;
  1711. case GPT_DOMAIN_PROGRAM:
  1712. hlslPassData.domainCode = hlslPassData.code;
  1713. glslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM, false, glslBinding);
  1714. vkslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM, true, vkslBinding);
  1715. break;
  1716. case GPT_COMPUTE_PROGRAM:
  1717. hlslPassData.computeCode = hlslPassData.code;
  1718. glslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM, false, glslBinding);
  1719. vkslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM, true, vkslBinding);
  1720. break;
  1721. default:
  1722. break;
  1723. }
  1724. }
  1725. }
  1726. techniqueData.push_back(std::make_pair(nullptr, glslTechnique));
  1727. techniqueData.push_back(std::make_pair(nullptr, vkslTechnique));
  1728. }
  1729. for(auto& entry : techniqueData)
  1730. {
  1731. const TechniqueMetaData& metaData = entry.second.metaData;
  1732. if (metaData.isMixin)
  1733. continue;
  1734. Map<UINT32, SPtr<Pass>, std::greater<UINT32>> passes;
  1735. for (auto& passData : entry.second.passes)
  1736. {
  1737. PASS_DESC passDesc;
  1738. if (!passData.blendIsDefault)
  1739. passDesc.blendState = BlendState::create(passData.blendDesc);
  1740. if (!passData.rasterizerIsDefault)
  1741. passDesc.rasterizerState = RasterizerState::create(passData.rasterizerDesc);
  1742. if (!passData.depthStencilIsDefault)
  1743. passDesc.depthStencilState = DepthStencilState::create(passData.depthStencilDesc);
  1744. auto createProgram =
  1745. [](const String& language, const String& entry, const String& code, GpuProgramType type) -> SPtr<GpuProgram>
  1746. {
  1747. if (code.empty())
  1748. return nullptr;
  1749. GPU_PROGRAM_DESC desc;
  1750. desc.language = language;
  1751. desc.entryPoint = entry;
  1752. desc.source = code;
  1753. desc.type = type;
  1754. return GpuProgram::create(desc);
  1755. };
  1756. bool isHLSL = metaData.language == "hlsl";
  1757. passDesc.vertexProgram = createProgram(
  1758. metaData.language,
  1759. isHLSL ? "vsmain" : "main",
  1760. passData.vertexCode,
  1761. GPT_VERTEX_PROGRAM);
  1762. passDesc.fragmentProgram = createProgram(
  1763. metaData.language,
  1764. isHLSL ? "fsmain" : "main",
  1765. passData.fragmentCode,
  1766. GPT_FRAGMENT_PROGRAM);
  1767. passDesc.geometryProgram = createProgram(
  1768. metaData.language,
  1769. isHLSL ? "gsmain" : "main",
  1770. passData.geometryCode,
  1771. GPT_GEOMETRY_PROGRAM);
  1772. passDesc.hullProgram = createProgram(
  1773. metaData.language,
  1774. isHLSL ? "hsmain" : "main",
  1775. passData.hullCode,
  1776. GPT_HULL_PROGRAM);
  1777. passDesc.domainProgram = createProgram(
  1778. metaData.language,
  1779. isHLSL ? "dsmain" : "main",
  1780. passData.domainCode,
  1781. GPT_DOMAIN_PROGRAM);
  1782. passDesc.computeProgram = createProgram(
  1783. metaData.language,
  1784. isHLSL ? "csmain" : "main",
  1785. passData.computeCode,
  1786. GPT_COMPUTE_PROGRAM);
  1787. passDesc.stencilRefValue = passData.stencilRefValue;
  1788. SPtr<Pass> pass = Pass::create(passDesc);
  1789. if (pass != nullptr)
  1790. passes[passData.seqIdx] = pass;
  1791. }
  1792. Vector<SPtr<Pass>> orderedPasses;
  1793. for (auto& KVP : passes)
  1794. orderedPasses.push_back(KVP.second);
  1795. if (orderedPasses.size() > 0)
  1796. {
  1797. SPtr<Technique> technique = Technique::create(metaData.language, metaData.renderer, metaData.tags,
  1798. variation, orderedPasses);
  1799. techniques.push_back(technique);
  1800. }
  1801. }
  1802. return output;
  1803. }
  1804. String BSLFXCompiler::removeQuotes(const char* input)
  1805. {
  1806. UINT32 len = (UINT32)strlen(input);
  1807. String output(len - 2, ' ');
  1808. for (UINT32 i = 0; i < (len - 2); i++)
  1809. output[i] = input[i + 1];
  1810. return output;
  1811. }
  1812. }