BsSLFXCompiler.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. #include "BsSLFXCompiler.h"
  2. #include "BsGpuProgram.h"
  3. #include <regex>
  4. #include "BsShader.h"
  5. #include "BsTechnique.h"
  6. #include "BsPass.h"
  7. #include "BsSamplerState.h"
  8. #include "BsRenderAPI.h"
  9. #include "BsDebug.h"
  10. #include "BsShaderManager.h"
  11. #include "BsShaderInclude.h"
  12. extern "C" {
  13. #include "BsMMAlloc.h"
  14. #include "BsParserFX.h"
  15. #include "BsLexerFX.h"
  16. }
  17. using namespace std;
  18. namespace BansheeEngine
  19. {
  20. // Print out the FX AST, only for debug purposes
  21. void SLFXDebugPrint(ASTFXNode* node, String indent)
  22. {
  23. LOGWRN(indent + "NODE " + toString(node->type));
  24. for (int i = 0; i < node->options->count; i++)
  25. {
  26. OptionDataType odt = OPTION_LOOKUP[(int)node->options->entries[i].type].dataType;
  27. if (odt == ODT_Complex)
  28. {
  29. LOGWRN(indent + toString(i) + ". " + toString(node->options->entries[i].type));
  30. SLFXDebugPrint(node->options->entries[i].value.nodePtr, indent + "\t");
  31. continue;
  32. }
  33. String value;
  34. switch (odt)
  35. {
  36. case ODT_Bool:
  37. value = toString(node->options->entries[i].value.intValue != 0);
  38. break;
  39. case ODT_Int:
  40. value = toString(node->options->entries[i].value.intValue);
  41. break;
  42. case ODT_Float:
  43. value = toString(node->options->entries[i].value.floatValue);
  44. break;
  45. case ODT_String:
  46. value = node->options->entries[i].value.strValue;
  47. break;
  48. case ODT_Matrix:
  49. {
  50. Matrix4 mat4 = *(Matrix4*)(node->options->entries[i].value.matrixValue);
  51. value = toString(mat4);
  52. }
  53. break;
  54. }
  55. LOGWRN(indent + toString(i) + ". " + toString(node->options->entries[i].type) + " = " + value);
  56. }
  57. }
  58. ShaderPtr BSLFXCompiler::compile(const String& source)
  59. {
  60. String parsedSource = source;
  61. ParseState* parseState = parseStateCreate();
  62. Vector<CodeBlock> codeBlocks = parseCodeBlocks(parsedSource);
  63. parseFX(parseState, parsedSource.c_str());
  64. ShaderPtr output;
  65. if (parseState->hasError > 0)
  66. {
  67. LOGERR("Error while parsing shader FX code: " + String(parseState->errorMessage) + ". Location: " +
  68. toString(parseState->errorLine) + " (" + toString(parseState->errorColumn) + ")");
  69. parseStateDelete(parseState);
  70. }
  71. else
  72. {
  73. // Only enable for debug purposes
  74. //SLFXDebugPrint(parseState->rootNode, "");
  75. output = parseShader("Shader", parseState, codeBlocks);
  76. StringStream gpuProgError;
  77. bool hasError = false;
  78. if (output != nullptr)
  79. {
  80. TechniquePtr bestTechnique = output->getBestTechnique();
  81. if (bestTechnique != nullptr)
  82. {
  83. UINT32 numPasses = bestTechnique->getNumPasses();
  84. for (UINT32 i = 0; i < numPasses; i++)
  85. {
  86. PassPtr pass = bestTechnique->getPass(i);
  87. auto checkCompileStatus = [&](const String& prefix, const GpuProgramPtr& prog)
  88. {
  89. if (prog != nullptr)
  90. {
  91. prog->blockUntilCoreInitialized();
  92. if (!prog->isCompiled())
  93. {
  94. hasError = true;
  95. gpuProgError << prefix <<": " << prog->getCompileErrorMessage() << std::endl;
  96. }
  97. }
  98. };
  99. checkCompileStatus("Vertex program", pass->getVertexProgram());
  100. checkCompileStatus("Fragment program", pass->getFragmentProgram());
  101. checkCompileStatus("Geometry program", pass->getGeometryProgram());
  102. checkCompileStatus("Hull program", pass->getHullProgram());
  103. checkCompileStatus("Domain program", pass->getDomainProgram());
  104. checkCompileStatus("Compute program", pass->getComputeProgram());
  105. }
  106. }
  107. }
  108. if (hasError)
  109. LOGERR("Failed compiling GPU program(s): " + gpuProgError.str());
  110. }
  111. return output;
  112. }
  113. void BSLFXCompiler::parseFX(ParseState* parseState, const char* source)
  114. {
  115. yyscan_t scanner;
  116. YY_BUFFER_STATE state;
  117. if (yylex_init_extra(parseState, &scanner))
  118. return;
  119. state = yy_scan_string(source, scanner);
  120. if (yyparse(parseState, scanner))
  121. return;
  122. yy_delete_buffer(state, scanner);
  123. yylex_destroy(scanner);
  124. }
  125. Vector<BSLFXCompiler::CodeBlock> BSLFXCompiler::parseCodeBlocks(String& source)
  126. {
  127. std::regex pattern = std::regex(R"((Vertex|Fragment|Geometry|Hull|Domain|Compute|Common)\s*=\s*\{)");
  128. std::smatch matches;
  129. Vector<CodeBlock> codeBlocks;
  130. UINT32 offset = 0;
  131. while (std::regex_search(source.cbegin() + offset, source.cend(), matches, pattern))
  132. {
  133. UINT32 idx = (UINT32)codeBlocks.size();
  134. codeBlocks.push_back(CodeBlock());
  135. CodeBlock& newBlock = codeBlocks.back();
  136. std::string type = matches[1].str();
  137. if (type == "Vertex")
  138. newBlock.type = CodeBlockType::Vertex;
  139. else if (type == "Fragment")
  140. newBlock.type = CodeBlockType::Fragment;
  141. else if (type == "Geometry")
  142. newBlock.type = CodeBlockType::Geometry;
  143. else if (type == "Hull")
  144. newBlock.type = CodeBlockType::Hull;
  145. else if (type == "Domain")
  146. newBlock.type = CodeBlockType::Domain;
  147. else if (type == "Compute")
  148. newBlock.type = CodeBlockType::Compute;
  149. else if (type == "Common")
  150. newBlock.type = CodeBlockType::Common;
  151. offset += (UINT32)matches.position() + (UINT32)matches.length();
  152. StringStream newDataStream;
  153. newDataStream << "Index = " + toString(idx) + ";";
  154. StringStream codeStream;
  155. UINT32 ummatchedBrackets = 1;
  156. for (UINT32 i = offset; i < (UINT32)source.length(); i++)
  157. {
  158. if (source[i] == '{')
  159. ummatchedBrackets++;
  160. if (source[i] == '}')
  161. ummatchedBrackets--;
  162. if (ummatchedBrackets == 0)
  163. break;
  164. if (source[i] == '\r' || source[i] == '\n')
  165. newDataStream << source[i];
  166. codeStream << source[i];
  167. }
  168. newBlock.code = codeStream.str();
  169. source.erase(source.cbegin() + offset, source.cbegin() + offset + (UINT32)newBlock.code.size());
  170. String newData = newDataStream.str();
  171. source.insert(offset, newData);
  172. offset += (UINT32)newData.size();
  173. }
  174. return codeBlocks;
  175. }
  176. void BSLFXCompiler::mergeBlocks(ParseState* mergeInto, ASTFXNode* blocksNode)
  177. {
  178. if (blocksNode == nullptr || blocksNode->type != NT_Blocks)
  179. return;
  180. ASTFXNode* destBlocksNode = nullptr;
  181. for (int i = 0; i < mergeInto->rootNode->options->count; i++)
  182. {
  183. NodeOption* option = &mergeInto->rootNode->options->entries[i];
  184. if (option->type == OT_Blocks)
  185. {
  186. destBlocksNode = option->value.nodePtr;
  187. break;
  188. }
  189. }
  190. if (destBlocksNode == nullptr)
  191. {
  192. destBlocksNode = nodeCreate(mergeInto->memContext, NT_Blocks);
  193. NodeOption blocksOption; blocksOption.type = OT_Blocks; blocksOption.value.nodePtr = destBlocksNode;
  194. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, &blocksOption);
  195. }
  196. for (int i = 0; i < blocksNode->options->count; i++)
  197. {
  198. NodeOption* option = &blocksNode->options->entries[i];
  199. if (option->type == OT_Block)
  200. {
  201. ASTFXNode* dstBlock = nodeCreate(mergeInto->memContext, NT_Block);
  202. NodeOption blockOption; blockOption.type = OT_Block; blockOption.value.nodePtr = dstBlock;
  203. nodeOptionsAdd(mergeInto->memContext, destBlocksNode->options, &blockOption);
  204. ASTFXNode* srcBlock = option->value.nodePtr;
  205. for (int j = 0; j < srcBlock->options->count; j++)
  206. nodeOptionsAdd(mergeInto->memContext, dstBlock->options, &srcBlock->options->entries[j]);
  207. }
  208. }
  209. }
  210. void BSLFXCompiler::mergeParameters(ParseState* mergeInto, ASTFXNode* paramsNode)
  211. {
  212. if (paramsNode == nullptr || paramsNode->type != NT_Parameters)
  213. return;
  214. ASTFXNode* destParamsNode = nullptr;
  215. for (int i = 0; i < mergeInto->rootNode->options->count; i++)
  216. {
  217. NodeOption* option = &mergeInto->rootNode->options->entries[i];
  218. if (option->type == OT_Parameters)
  219. {
  220. destParamsNode = option->value.nodePtr;
  221. break;
  222. }
  223. }
  224. if (destParamsNode == nullptr)
  225. {
  226. destParamsNode = nodeCreate(mergeInto->memContext, NT_Parameters);
  227. NodeOption paramsOption; paramsOption.type = OT_Parameters; paramsOption.value.nodePtr = destParamsNode;
  228. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, &paramsOption);
  229. }
  230. for (int i = 0; i < paramsNode->options->count; i++)
  231. {
  232. NodeOption* option = &paramsNode->options->entries[i];
  233. if (option->type == OT_Parameter)
  234. {
  235. ASTFXNode* dstParam = nodeCreate(mergeInto->memContext, NT_Parameter);
  236. NodeOption paramOption; paramOption.type = OT_Parameter; paramOption.value.nodePtr = dstParam;
  237. nodeOptionsAdd(mergeInto->memContext, destParamsNode->options, &paramOption);
  238. ASTFXNode* srcParam = option->value.nodePtr;
  239. for (int j = 0; j < srcParam->options->count; j++)
  240. nodeOptionsAdd(mergeInto->memContext, dstParam->options, &srcParam->options->entries[j]);
  241. }
  242. }
  243. }
  244. void BSLFXCompiler::getTechniqueIdentifier(ASTFXNode* technique, StringID& renderer, String& language)
  245. {
  246. renderer = RendererAny;
  247. language = "Any";
  248. for (int i = 0; i < technique->options->count; i++)
  249. {
  250. NodeOption* option = &technique->options->entries[i];
  251. switch (option->type)
  252. {
  253. case OT_Renderer:
  254. renderer = parseRenderer(removeQuotes(option->value.strValue));
  255. break;
  256. case OT_Language:
  257. language = removeQuotes(option->value.strValue);
  258. break;
  259. }
  260. }
  261. }
  262. bool BSLFXCompiler::isTechniqueMergeValid(ASTFXNode* into, ASTFXNode* from)
  263. {
  264. StringID intoRenderer = RendererAny;
  265. String intoLanguage = "Any";
  266. StringID fromRenderer = RendererAny;
  267. String fromLanguage = "Any";
  268. getTechniqueIdentifier(into, intoRenderer, intoLanguage);
  269. getTechniqueIdentifier(from, fromRenderer, fromLanguage);
  270. return (intoRenderer == fromRenderer || fromRenderer == RendererAny) && (intoLanguage == fromLanguage || fromLanguage == "Any");
  271. }
  272. void BSLFXCompiler::mergePass(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode, UINT32 codeBlockOffset)
  273. {
  274. if (mergeIntoNode == nullptr || mergeIntoNode->type != NT_Pass || mergeFromNode == nullptr || mergeFromNode->type != NT_Pass)
  275. return;
  276. mergeCode(mergeInto, mergeIntoNode, mergeFromNode, codeBlockOffset);
  277. mergePassStates(mergeInto, mergeIntoNode, mergeFromNode);
  278. }
  279. void BSLFXCompiler::mergeCode(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode, UINT32 codeBlockOffset)
  280. {
  281. for (int i = 0; i < mergeFromNode->options->count; i++)
  282. {
  283. NodeOption* option = &mergeFromNode->options->entries[i];
  284. if (option->type == OT_Code)
  285. {
  286. ASTFXNode* srcCodeNode = option->value.nodePtr;
  287. UINT32 origIndex = 0;
  288. for (int j = 0; j < srcCodeNode->options->count; j++)
  289. {
  290. NodeOption* codeOption = &srcCodeNode->options->entries[j];
  291. if (codeOption->type == OT_Index)
  292. origIndex = codeOption->value.intValue;
  293. }
  294. ASTFXNode* destCodeNode = nodeCreate(mergeInto->memContext, NT_Code);
  295. NodeOption index; index.type = OT_Index; index.value.intValue = codeBlockOffset + origIndex;
  296. nodeOptionsAdd(mergeInto->memContext, destCodeNode->options, &index);
  297. NodeOption code; code.type = OT_Code; code.value.nodePtr = destCodeNode;
  298. nodeOptionsAdd(mergeInto->memContext, mergeIntoNode->options, &code);
  299. }
  300. }
  301. }
  302. void BSLFXCompiler::mergePassStates(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode)
  303. {
  304. for (int i = 0; i < mergeFromNode->options->count; i++)
  305. {
  306. NodeOption* option = &mergeFromNode->options->entries[i];
  307. // Skip these as we handle them specially elsewhere
  308. if (option->type == OT_Code || option->type == OT_Pass || option->type == OT_Renderer || option->type == OT_Language)
  309. continue;
  310. OptionDataType dataType = OPTION_LOOKUP[(int)option->type].dataType;
  311. if (dataType == ODT_Complex)
  312. {
  313. ASTFXNode* newNode = nullptr;
  314. if (option->value.nodePtr != nullptr)
  315. {
  316. newNode = nodeCreate(mergeInto->memContext, option->value.nodePtr->type);
  317. mergePassStates(mergeInto, newNode, option->value.nodePtr);
  318. }
  319. NodeOption newOption;
  320. newOption.type = option->type;
  321. newOption.value.nodePtr = newNode;
  322. nodeOptionsAdd(mergeInto->memContext, mergeIntoNode->options, &newOption);
  323. }
  324. else if (dataType == ODT_String)
  325. {
  326. NodeOption newOption;
  327. newOption.type = option->type;
  328. newOption.value.strValue = mmalloc_strdup(mergeInto->memContext, option->value.strValue);
  329. nodeOptionsAdd(mergeInto->memContext, mergeIntoNode->options, &newOption);
  330. }
  331. else
  332. {
  333. nodeOptionsAdd(mergeInto->memContext, mergeIntoNode->options, option);
  334. }
  335. }
  336. }
  337. void BSLFXCompiler::mergeTechnique(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode, UINT32 codeBlockOffset)
  338. {
  339. if (mergeIntoNode == nullptr || mergeIntoNode->type != NT_Technique || mergeFromNode == nullptr || mergeFromNode->type != NT_Technique)
  340. return;
  341. mergeCode(mergeInto, mergeIntoNode, mergeFromNode, codeBlockOffset);
  342. mergePassStates(mergeInto, mergeIntoNode, mergeFromNode);
  343. Map<UINT32, ASTFXNode*, std::greater<UINT32>> fromPasses;
  344. UINT32 nextPassIdx = 0;
  345. for (int i = 0; i < mergeFromNode->options->count; i++)
  346. {
  347. NodeOption* option = &mergeFromNode->options->entries[i];
  348. if (option->type == OT_Pass)
  349. {
  350. ASTFXNode* passNode = option->value.nodePtr;
  351. UINT32 passIdx = nextPassIdx;
  352. for (int j = 0; j < passNode->options->count; j++)
  353. {
  354. NodeOption* passOption = &passNode->options->entries[i];
  355. if (passOption->type == OT_Index)
  356. passIdx = (UINT32)passOption->value.intValue;
  357. }
  358. fromPasses[passIdx] = passNode;
  359. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  360. }
  361. }
  362. Map<UINT32, ASTFXNode*, std::greater<UINT32>> intoPasses;
  363. nextPassIdx = 0;
  364. for (int i = 0; i < mergeIntoNode->options->count; i++)
  365. {
  366. NodeOption* option = &mergeIntoNode->options->entries[i];
  367. if (option->type == OT_Pass)
  368. {
  369. ASTFXNode* passNode = option->value.nodePtr;
  370. UINT32 passIdx = nextPassIdx;
  371. for (int j = 0; j < passNode->options->count; j++)
  372. {
  373. NodeOption* passOption = &passNode->options->entries[i];
  374. if (passOption->type == OT_Index)
  375. passIdx = (UINT32)passOption->value.intValue;
  376. }
  377. intoPasses[passIdx] = passNode;
  378. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  379. }
  380. }
  381. for (auto& fromPair : fromPasses)
  382. {
  383. auto iterFind = intoPasses.find(fromPair.first);
  384. if (iterFind != intoPasses.end())
  385. {
  386. mergePass(mergeInto, iterFind->second, fromPair.second, codeBlockOffset);
  387. }
  388. else
  389. {
  390. ASTFXNode* passNode = nodeCreate(mergeInto->memContext, NT_Pass);
  391. NodeOption passOption; passOption.type = OT_Pass; passOption.value.nodePtr = passNode;
  392. nodeOptionsAdd(mergeInto->memContext, mergeIntoNode->options, &passOption);
  393. mergePass(mergeInto, passNode, fromPair.second, codeBlockOffset);
  394. }
  395. }
  396. }
  397. void BSLFXCompiler::mergeTechniques(ParseState* mergeInto, ASTFXNode* techniqueNode, UINT32 codeBlockOffset)
  398. {
  399. if (techniqueNode == nullptr || techniqueNode->type != NT_Technique)
  400. return;
  401. bool anyMerged = false;
  402. for (int i = 0; i < mergeInto->rootNode->options->count; i++)
  403. {
  404. NodeOption* option = &mergeInto->rootNode->options->entries[i];
  405. if (option->type == OT_Technique)
  406. {
  407. if (isTechniqueMergeValid(option->value.nodePtr, techniqueNode))
  408. {
  409. mergeTechnique(mergeInto, option->value.nodePtr, techniqueNode, codeBlockOffset);
  410. anyMerged = true;
  411. break;
  412. }
  413. }
  414. }
  415. // If this is a language specific technique and it wasn't merged with anything, create a new technique node
  416. if (!anyMerged)
  417. {
  418. ASTFXNode* techniqueNode = nodeCreate(mergeInto->memContext, NT_Technique);
  419. NodeOption techniqueOption; techniqueOption.type = OT_Technique; techniqueOption.value.nodePtr = techniqueNode;
  420. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, &techniqueOption);
  421. mergeTechnique(mergeInto, techniqueNode, techniqueNode, codeBlockOffset);
  422. }
  423. }
  424. void BSLFXCompiler::mergeAST(ParseState* mergeInto, ASTFXNode* mergeFrom, UINT32 codeBlockOffset)
  425. {
  426. if (mergeInto->rootNode->type != NT_Shader || mergeFrom == nullptr || mergeFrom->type != NT_Shader)
  427. return;
  428. for (int i = 0; i < mergeFrom->options->count; i++)
  429. {
  430. NodeOption* option = &mergeFrom->options->entries[i];
  431. switch (option->type)
  432. {
  433. case OT_Separable:
  434. case OT_Queue:
  435. case OT_Priority:
  436. case OT_Transparent:
  437. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, option);
  438. break;
  439. case OT_Technique:
  440. mergeTechniques(mergeInto, option->value.nodePtr, codeBlockOffset);
  441. break;
  442. case OT_Parameters:
  443. mergeParameters(mergeInto, option->value.nodePtr);
  444. break;
  445. case OT_Blocks:
  446. mergeBlocks(mergeInto, option->value.nodePtr);
  447. break;
  448. }
  449. }
  450. }
  451. StringID BSLFXCompiler::parseRenderer(const String& name)
  452. {
  453. if (name == "Any")
  454. return RendererAny;
  455. else if (name == "Default")
  456. return RendererDefault;
  457. return RendererAny;
  458. }
  459. void BSLFXCompiler::parseLanguage(const String& name, StringID& renderAPI, String& language)
  460. {
  461. if (name == "HLSL" || name == "HLSL11")
  462. {
  463. renderAPI = RenderAPIDX11;
  464. language = "hlsl";
  465. }
  466. else if (name == "HLSL9")
  467. {
  468. renderAPI = RenderAPIDX9;
  469. language = "hlsl9";
  470. }
  471. else if (name == "GLSL")
  472. {
  473. renderAPI = RenderAPIOpenGL;
  474. language = "glsl";
  475. }
  476. else
  477. {
  478. renderAPI = RenderAPIAny;
  479. language = "";
  480. }
  481. }
  482. GpuParamBlockUsage BSLFXCompiler::parseBlockUsage(BufferUsageValue usage)
  483. {
  484. if (usage == BUV_Dynamic)
  485. return GPBU_DYNAMIC;
  486. return GPBU_STATIC;
  487. }
  488. UINT32 BSLFXCompiler::parseFilterMode(FilterValue filter)
  489. {
  490. switch (filter)
  491. {
  492. case FV_Point:
  493. return FO_POINT;
  494. case FV_Linear:
  495. return FO_LINEAR;
  496. case FV_Anisotropic:
  497. return FO_ANISOTROPIC;
  498. case FV_PointCmp:
  499. return FO_POINT | FO_USE_COMPARISON;
  500. case FV_LinearCmp:
  501. return FO_LINEAR | FO_USE_COMPARISON;
  502. case FV_AnisotropicCmp:
  503. return FO_ANISOTROPIC | FO_USE_COMPARISON;
  504. }
  505. return FO_NONE;
  506. }
  507. CompareFunction BSLFXCompiler::parseCompFunc(CompFuncValue compFunc)
  508. {
  509. switch (compFunc)
  510. {
  511. case CFV_Pass:
  512. return CMPF_ALWAYS_PASS;
  513. case CFV_Fail:
  514. return CMPF_ALWAYS_FAIL;
  515. case CFV_LT:
  516. return CMPF_LESS;
  517. case CFV_LTE:
  518. return CMPF_LESS_EQUAL;
  519. case CFV_EQ:
  520. return CMPF_EQUAL;
  521. case CFV_NEQ:
  522. return CMPF_NOT_EQUAL;
  523. case CFV_GT:
  524. return CMPF_GREATER;
  525. case CFV_GTE:
  526. return CMPF_GREATER_EQUAL;
  527. }
  528. return CMPF_ALWAYS_PASS;
  529. }
  530. TextureAddressingMode BSLFXCompiler::parseAddrMode(AddrModeValue addrMode)
  531. {
  532. switch (addrMode)
  533. {
  534. case AMV_Wrap:
  535. return TAM_WRAP;
  536. case AMV_Mirror:
  537. return TAM_MIRROR;
  538. case AMV_Clamp:
  539. return TAM_CLAMP;
  540. case AMV_Border:
  541. return TAM_BORDER;
  542. }
  543. return TAM_WRAP;
  544. }
  545. BlendFactor BSLFXCompiler::parseBlendFactor(OpValue factor)
  546. {
  547. switch (factor)
  548. {
  549. case OV_One:
  550. return BF_ONE;
  551. case OV_Zero:
  552. return BF_ZERO;
  553. case OV_DestColor:
  554. return BF_DEST_COLOR;
  555. case OV_SrcColor:
  556. return BF_SOURCE_COLOR;
  557. case OV_InvDestColor:
  558. return BF_INV_DEST_COLOR;
  559. case OV_InvSrcColor:
  560. return BF_INV_SOURCE_COLOR;
  561. case OV_DestAlpha:
  562. return BF_DEST_ALPHA;
  563. case OV_SrcAlpha:
  564. return BF_SOURCE_ALPHA;
  565. case OV_InvDestAlpha:
  566. return BF_INV_DEST_ALPHA;
  567. case OV_InvSrcAlpha:
  568. return BF_INV_SOURCE_ALPHA;
  569. }
  570. return BF_ONE;
  571. }
  572. BlendOperation BSLFXCompiler::parseBlendOp(BlendOpValue op)
  573. {
  574. switch (op)
  575. {
  576. case BOV_Add:
  577. return BO_ADD;
  578. case BOV_Max:
  579. return BO_MAX;
  580. case BOV_Min:
  581. return BO_MIN;
  582. case BOV_Subtract:
  583. return BO_SUBTRACT;
  584. case BOV_RevSubtract:
  585. return BO_REVERSE_SUBTRACT;
  586. }
  587. return BO_ADD;
  588. }
  589. void BSLFXCompiler::parseParamType(ParamType type, bool& isObjType, UINT32& typeId)
  590. {
  591. struct ParamData
  592. {
  593. UINT32 type;
  594. bool isObjType;
  595. };
  596. static bool initialized = false;
  597. static ParamData lookup[PT_Count];
  598. if (!initialized)
  599. {
  600. lookup[PT_Float] = { { GPDT_FLOAT1 }, false };
  601. lookup[PT_Float2] = { { GPDT_FLOAT2 }, false };
  602. lookup[PT_Float3] = { { GPDT_FLOAT3 }, false };
  603. lookup[PT_Float4] = { { GPDT_FLOAT4 }, false };
  604. lookup[PT_Mat2x2] = { { GPDT_MATRIX_2X2 }, false };
  605. lookup[PT_Mat2x3] = { { GPDT_MATRIX_2X3 }, false };
  606. lookup[PT_Mat2x4] = { { GPDT_MATRIX_2X4 }, false };
  607. lookup[PT_Mat3x2] = { { GPDT_MATRIX_3X2 }, false };
  608. lookup[PT_Mat3x3] = { { GPDT_MATRIX_3X3 }, false };
  609. lookup[PT_Mat3x4] = { { GPDT_MATRIX_3X4 }, false };
  610. lookup[PT_Mat4x2] = { { GPDT_MATRIX_4X2 }, false };
  611. lookup[PT_Mat4x3] = { { GPDT_MATRIX_4X3 }, false };
  612. lookup[PT_Mat4x4] = { { GPDT_MATRIX_4X4 }, false };
  613. lookup[PT_Sampler1D] = { { GPOT_SAMPLER1D }, true };
  614. lookup[PT_Sampler2D] = { { GPOT_SAMPLER2D }, true };
  615. lookup[PT_Sampler3D] = { { GPOT_SAMPLER3D }, true };
  616. lookup[PT_SamplerCUBE] = { { GPOT_SAMPLERCUBE }, true };
  617. lookup[PT_Sampler2DMS] = { { GPOT_SAMPLER2DMS }, true };
  618. lookup[PT_Texture1D] = { { GPOT_TEXTURE1D }, true };
  619. lookup[PT_Texture2D] = { { GPOT_TEXTURE2D }, true };
  620. lookup[PT_Texture3D] = { { GPOT_TEXTURE3D }, true };
  621. lookup[PT_TextureCUBE] = { { GPOT_TEXTURECUBE }, true };
  622. lookup[PT_Texture2DMS] = { { GPOT_TEXTURE2DMS }, true };
  623. lookup[PT_ByteBuffer] = { { GPOT_BYTE_BUFFER }, true };
  624. lookup[PT_StructBuffer] = { { GPOT_STRUCTURED_BUFFER }, true };
  625. lookup[PT_TypedBufferRW] = { { GPOT_RWTYPED_BUFFER }, true };
  626. lookup[PT_ByteBufferRW] = { { GPOT_RWBYTE_BUFFER }, true };
  627. lookup[PT_StructBufferRW] = { { GPOT_RWSTRUCTURED_BUFFER }, true };
  628. lookup[PT_AppendBuffer] = { { GPOT_RWAPPEND_BUFFER }, true };
  629. lookup[PT_ConsumeBuffer] = { { GPOT_RWCONSUME_BUFFER }, true };
  630. initialized = true;
  631. }
  632. isObjType = lookup[type].isObjType;
  633. typeId = lookup[type].type;
  634. }
  635. StencilOperation BSLFXCompiler::parseStencilOp(OpValue op)
  636. {
  637. switch (op)
  638. {
  639. case OV_Keep:
  640. return SOP_KEEP;
  641. case OV_Zero:
  642. return SOP_ZERO;
  643. case OV_Replace:
  644. return SOP_REPLACE;
  645. case OV_Incr:
  646. return SOP_INCREMENT;
  647. case OV_Decr:
  648. return SOP_DECREMENT;
  649. case OV_IncrWrap:
  650. return SOP_INCREMENT_WRAP;
  651. case OV_DecrWrap:
  652. return SOP_DECREMENT_WRAP;
  653. case OV_Invert:
  654. return SOP_INVERT;
  655. }
  656. return SOP_KEEP;
  657. }
  658. CullingMode BSLFXCompiler::parseCullMode(CullModeValue cm)
  659. {
  660. switch (cm)
  661. {
  662. case CMV_None:
  663. return CULL_NONE;
  664. case CMV_CW:
  665. return CULL_CLOCKWISE;
  666. case CMV_CCW:
  667. return CULL_COUNTERCLOCKWISE;
  668. }
  669. return CULL_COUNTERCLOCKWISE;
  670. }
  671. PolygonMode BSLFXCompiler::parseFillMode(FillModeValue fm)
  672. {
  673. if (fm == FMV_Wire)
  674. return PM_WIREFRAME;
  675. return PM_SOLID;
  676. }
  677. void BSLFXCompiler::parseStencilFront(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  678. {
  679. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  680. return;
  681. for (int i = 0; i < stencilOpNode->options->count; i++)
  682. {
  683. NodeOption* option = &stencilOpNode->options->entries[i];
  684. switch (option->type)
  685. {
  686. case OT_Fail:
  687. desc.frontStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  688. break;
  689. case OT_ZFail:
  690. desc.frontStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  691. break;
  692. case OT_PassOp:
  693. desc.frontStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  694. break;
  695. case OT_CompareFunc:
  696. desc.frontStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  697. break;
  698. }
  699. }
  700. }
  701. void BSLFXCompiler::parseStencilBack(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  702. {
  703. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  704. return;
  705. for (int i = 0; i < stencilOpNode->options->count; i++)
  706. {
  707. NodeOption* option = &stencilOpNode->options->entries[i];
  708. switch (option->type)
  709. {
  710. case OT_Fail:
  711. desc.backStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  712. break;
  713. case OT_ZFail:
  714. desc.backStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  715. break;
  716. case OT_PassOp:
  717. desc.backStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  718. break;
  719. case OT_CompareFunc:
  720. desc.backStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  721. break;
  722. }
  723. }
  724. }
  725. void BSLFXCompiler::parseAddrMode(SAMPLER_STATE_DESC& desc, ASTFXNode* addrModeNode)
  726. {
  727. if (addrModeNode == nullptr || addrModeNode->type != NT_AddrMode)
  728. return;
  729. for (int i = 0; i < addrModeNode->options->count; i++)
  730. {
  731. NodeOption* option = &addrModeNode->options->entries[i];
  732. switch (option->type)
  733. {
  734. case OT_U:
  735. desc.addressMode.u = parseAddrMode((AddrModeValue)option->value.intValue);
  736. break;
  737. case OT_V:
  738. desc.addressMode.v = parseAddrMode((AddrModeValue)option->value.intValue);
  739. break;
  740. case OT_W:
  741. desc.addressMode.w = parseAddrMode((AddrModeValue)option->value.intValue);
  742. break;
  743. }
  744. }
  745. }
  746. void BSLFXCompiler::parseColorBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  747. {
  748. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  749. return;
  750. for (int i = 0; i < blendDefNode->options->count; i++)
  751. {
  752. NodeOption* option = &blendDefNode->options->entries[i];
  753. switch (option->type)
  754. {
  755. case OT_Source:
  756. desc.srcBlend = parseBlendFactor((OpValue)option->value.intValue);
  757. break;
  758. case OT_Dest:
  759. desc.dstBlend = parseBlendFactor((OpValue)option->value.intValue);
  760. break;
  761. case OT_Op:
  762. desc.blendOp = parseBlendOp((BlendOpValue)option->value.intValue);
  763. break;
  764. }
  765. }
  766. }
  767. void BSLFXCompiler::parseAlphaBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  768. {
  769. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  770. return;
  771. for (int i = 0; i < blendDefNode->options->count; i++)
  772. {
  773. NodeOption* option = &blendDefNode->options->entries[i];
  774. switch (option->type)
  775. {
  776. case OT_Source:
  777. desc.srcBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  778. break;
  779. case OT_Dest:
  780. desc.dstBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  781. break;
  782. case OT_Op:
  783. desc.blendOpAlpha = parseBlendOp((BlendOpValue)option->value.intValue);
  784. break;
  785. }
  786. }
  787. }
  788. void BSLFXCompiler::parseRenderTargetBlendState(BLEND_STATE_DESC& desc, ASTFXNode* targetNode)
  789. {
  790. if (targetNode == nullptr || targetNode->type != NT_Target)
  791. return;
  792. UINT32 index = 0;
  793. for (int i = 0; i < targetNode->options->count; i++)
  794. {
  795. NodeOption* option = &targetNode->options->entries[i];
  796. switch (option->type)
  797. {
  798. case OT_Index:
  799. index = option->value.intValue;
  800. break;
  801. }
  802. }
  803. if (index >= BS_MAX_MULTIPLE_RENDER_TARGETS)
  804. return;
  805. RENDER_TARGET_BLEND_STATE_DESC& rtDesc = desc.renderTargetDesc[index];
  806. for (int i = 0; i < targetNode->options->count; i++)
  807. {
  808. NodeOption* option = &targetNode->options->entries[i];
  809. switch (option->type)
  810. {
  811. case OT_Blend:
  812. rtDesc.blendEnable = option->value.intValue > 0;
  813. break;
  814. case OT_Color:
  815. parseColorBlendDef(rtDesc, option->value.nodePtr);
  816. break;
  817. case OT_Alpha:
  818. parseAlphaBlendDef(rtDesc, option->value.nodePtr);
  819. break;
  820. case OT_WriteMask:
  821. rtDesc.renderTargetWriteMask = option->value.intValue;
  822. break;
  823. }
  824. }
  825. }
  826. bool BSLFXCompiler::parseBlendState(BLEND_STATE_DESC& desc, ASTFXNode* passNode)
  827. {
  828. if (passNode == nullptr || (passNode->type != NT_Pass && passNode->type != NT_Technique))
  829. return false;
  830. bool default = true;
  831. for (int i = 0; i < passNode->options->count; i++)
  832. {
  833. NodeOption* option = &passNode->options->entries[i];
  834. switch (option->type)
  835. {
  836. case OT_AlphaToCoverage:
  837. desc.alphaToCoverageEnable = option->value.intValue > 0;
  838. default = false;
  839. break;
  840. case OT_IndependantBlend:
  841. desc.independantBlendEnable = option->value.intValue > 0;
  842. default = false;
  843. break;
  844. case OT_Target:
  845. parseRenderTargetBlendState(desc, option->value.nodePtr);
  846. default = false;
  847. break;
  848. }
  849. }
  850. return !default;
  851. }
  852. bool BSLFXCompiler::parseRasterizerState(RASTERIZER_STATE_DESC& desc, ASTFXNode* passNode)
  853. {
  854. if (passNode == nullptr || (passNode->type != NT_Pass && passNode->type != NT_Technique))
  855. return false;
  856. bool default = true;
  857. for (int i = 0; i < passNode->options->count; i++)
  858. {
  859. NodeOption* option = &passNode->options->entries[i];
  860. switch (option->type)
  861. {
  862. case OT_FillMode:
  863. desc.polygonMode = parseFillMode((FillModeValue)option->value.intValue);
  864. default = false;
  865. break;
  866. case OT_CullMode:
  867. desc.cullMode = parseCullMode((CullModeValue)option->value.intValue);
  868. default = false;
  869. break;
  870. case OT_DepthBias:
  871. desc.depthBias = option->value.floatValue;
  872. default = false;
  873. break;
  874. case OT_SDepthBias:
  875. desc.slopeScaledDepthBias = option->value.floatValue;
  876. default = false;
  877. break;
  878. case OT_DepthClip:
  879. desc.depthClipEnable = option->value.intValue > 0;
  880. default = false;
  881. break;
  882. case OT_Scissor:
  883. desc.scissorEnable = option->value.intValue > 0;
  884. default = false;
  885. break;
  886. case OT_Multisample:
  887. desc.multisampleEnable = option->value.intValue > 0;
  888. default = false;
  889. break;
  890. case OT_AALine:
  891. desc.antialiasedLineEnable = option->value.intValue > 0;
  892. default = false;
  893. break;
  894. }
  895. }
  896. return !default;
  897. }
  898. bool BSLFXCompiler::parseDepthStencilState(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* passNode)
  899. {
  900. if (passNode == nullptr || (passNode->type != NT_Pass && passNode->type != NT_Technique))
  901. return false;
  902. bool default = true;
  903. for (int i = 0; i < passNode->options->count; i++)
  904. {
  905. NodeOption* option = &passNode->options->entries[i];
  906. switch (option->type)
  907. {
  908. case OT_DepthRead:
  909. desc.depthReadEnable = option->value.intValue > 0;
  910. default = false;
  911. break;
  912. case OT_DepthWrite:
  913. desc.depthWriteEnable = option->value.intValue > 0;
  914. default = false;
  915. break;
  916. case OT_CompareFunc:
  917. desc.depthComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  918. default = false;
  919. break;
  920. case OT_Stencil:
  921. desc.stencilEnable = option->value.intValue > 0;
  922. default = false;
  923. break;
  924. case OT_StencilReadMask:
  925. desc.stencilReadMask = (UINT8)option->value.intValue;
  926. default = false;
  927. break;
  928. case OT_StencilWriteMask:
  929. desc.stencilWriteMask = (UINT8)option->value.intValue;
  930. default = false;
  931. break;
  932. case OT_StencilOpFront:
  933. parseStencilFront(desc, option->value.nodePtr);
  934. default = false;
  935. break;
  936. case OT_StencilOpBack:
  937. parseStencilBack(desc, option->value.nodePtr);
  938. default = false;
  939. break;
  940. }
  941. }
  942. return !default;
  943. }
  944. SamplerStatePtr BSLFXCompiler::parseSamplerState(ASTFXNode* samplerStateNode)
  945. {
  946. if (samplerStateNode == nullptr || samplerStateNode->type != NT_SamplerState)
  947. return nullptr;
  948. SAMPLER_STATE_DESC desc;
  949. bool default = true;
  950. for (int i = 0; i < samplerStateNode->options->count; i++)
  951. {
  952. NodeOption* option = &samplerStateNode->options->entries[i];
  953. switch (option->type)
  954. {
  955. case OT_AddrMode:
  956. parseAddrMode(desc, option->value.nodePtr);
  957. default = false;
  958. break;
  959. case OT_MinFilter:
  960. desc.minFilter = (FilterOptions)parseFilterMode((FilterValue)option->value.intValue);
  961. default = false;
  962. break;
  963. case OT_MagFilter:
  964. desc.magFilter = (FilterOptions)parseFilterMode((FilterValue)option->value.intValue);
  965. default = false;
  966. break;
  967. case OT_MipFilter:
  968. desc.mipFilter = (FilterOptions)parseFilterMode((FilterValue)option->value.intValue);
  969. default = false;
  970. break;
  971. case OT_MaxAniso:
  972. desc.maxAniso = option->value.intValue;
  973. default = false;
  974. break;
  975. case OT_MipBias:
  976. desc.mipmapBias = option->value.floatValue;
  977. default = false;
  978. break;
  979. case OT_MipMin:
  980. desc.mipMin = option->value.floatValue;
  981. default = false;
  982. break;
  983. case OT_MipMax:
  984. desc.mipMax = option->value.floatValue;
  985. default = false;
  986. break;
  987. case OT_BorderColor:
  988. desc.borderColor = Color(option->value.matrixValue[0], option->value.matrixValue[1],
  989. option->value.matrixValue[2], option->value.matrixValue[3]);
  990. default = false;
  991. break;
  992. case OT_CompareFunc:
  993. desc.comparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  994. default = false;
  995. break;
  996. }
  997. }
  998. if (default)
  999. return nullptr;
  1000. return SamplerState::create(desc);
  1001. }
  1002. void BSLFXCompiler::parseCodeBlock(ASTFXNode* codeNode, const Vector<CodeBlock>& codeBlocks, PassData& passData)
  1003. {
  1004. if (codeNode == nullptr || codeNode->type != NT_Code)
  1005. return;
  1006. UINT32 index = (UINT32)-1;
  1007. for (int j = 0; j < codeNode->options->count; j++)
  1008. {
  1009. if (codeNode->options->entries[j].type == OT_Index)
  1010. index = codeNode->options->entries[j].value.intValue;
  1011. }
  1012. if (index != (UINT32)-1 && index < (UINT32)codeBlocks.size())
  1013. {
  1014. const CodeBlock& codeBlock = codeBlocks[index];
  1015. switch (codeBlock.type)
  1016. {
  1017. case CodeBlockType::Vertex:
  1018. passData.vertexCode += codeBlock.code;
  1019. break;
  1020. case CodeBlockType::Fragment:
  1021. passData.fragmentCode += codeBlock.code;
  1022. break;
  1023. case CodeBlockType::Geometry:
  1024. passData.geometryCode += codeBlock.code;
  1025. break;
  1026. case CodeBlockType::Hull:
  1027. passData.hullCode += codeBlock.code;
  1028. break;
  1029. case CodeBlockType::Domain:
  1030. passData.domainCode += codeBlock.code;
  1031. break;
  1032. case CodeBlockType::Compute:
  1033. passData.computeCode += codeBlock.code;
  1034. break;
  1035. case CodeBlockType::Common:
  1036. passData.commonCode += codeBlock.code;
  1037. break;
  1038. }
  1039. }
  1040. }
  1041. PassPtr BSLFXCompiler::parsePass(ASTFXNode* passNode, const Vector<CodeBlock>& codeBlocks, PassData& passData,
  1042. const StringID& renderAPI, const String& language, UINT32& seqIdx)
  1043. {
  1044. if (passNode == nullptr || passNode->type != NT_Pass)
  1045. return nullptr;
  1046. PASS_DESC passDesc;
  1047. passData.blendIsDefault &= !parseBlendState(passData.blendDesc, passNode);
  1048. passData.rasterizerIsDefault &= !parseRasterizerState(passData.rasterizerDesc, passNode);
  1049. passData.depthStencilIsDefault &= !parseDepthStencilState(passData.depthStencilDesc, passNode);
  1050. if (!passData.blendIsDefault)
  1051. passDesc.blendState = BlendState::create(passData.blendDesc);
  1052. if (!passData.rasterizerIsDefault)
  1053. passDesc.rasterizerState = RasterizerState::create(passData.rasterizerDesc);
  1054. if (!passData.depthStencilIsDefault)
  1055. passDesc.depthStencilState = DepthStencilState::create(passData.depthStencilDesc);
  1056. for (int i = 0; i < passNode->options->count; i++)
  1057. {
  1058. NodeOption* option = &passNode->options->entries[i];
  1059. switch (option->type)
  1060. {
  1061. case OT_Index:
  1062. seqIdx = option->value.intValue;
  1063. break;
  1064. case OT_StencilRef:
  1065. passDesc.stencilRefValue = option->value.intValue;
  1066. break;
  1067. case OT_Code:
  1068. parseCodeBlock(option->value.nodePtr, codeBlocks, passData);
  1069. break;
  1070. }
  1071. }
  1072. if (!passData.vertexCode.empty())
  1073. {
  1074. passDesc.vertexProgram = GpuProgram::create(passData.commonCode + passData.vertexCode, "main", language,
  1075. GPT_VERTEX_PROGRAM, getProfile(renderAPI, GPT_VERTEX_PROGRAM));
  1076. }
  1077. if (!passData.fragmentCode.empty())
  1078. {
  1079. passDesc.fragmentProgram = GpuProgram::create(passData.commonCode + passData.fragmentCode, "main", language,
  1080. GPT_FRAGMENT_PROGRAM, getProfile(renderAPI, GPT_FRAGMENT_PROGRAM));
  1081. }
  1082. if (!passData.geometryCode.empty())
  1083. {
  1084. passDesc.geometryProgram = GpuProgram::create(passData.commonCode + passData.geometryCode, "main", language,
  1085. GPT_GEOMETRY_PROGRAM, getProfile(renderAPI, GPT_GEOMETRY_PROGRAM));
  1086. }
  1087. if (!passData.hullCode.empty())
  1088. {
  1089. passDesc.hullProgram = GpuProgram::create(passData.commonCode + passData.hullCode, "main", language,
  1090. GPT_HULL_PROGRAM, getProfile(renderAPI, GPT_HULL_PROGRAM));
  1091. }
  1092. if (!passData.domainCode.empty())
  1093. {
  1094. passDesc.domainProgram = GpuProgram::create(passData.commonCode + passData.domainCode, "main", language,
  1095. GPT_DOMAIN_PROGRAM, getProfile(renderAPI, GPT_DOMAIN_PROGRAM));
  1096. }
  1097. if (!passData.computeCode.empty())
  1098. {
  1099. passDesc.computeProgram = GpuProgram::create(passData.commonCode + passData.computeCode, "main", language,
  1100. GPT_COMPUTE_PROGRAM, getProfile(renderAPI, GPT_COMPUTE_PROGRAM));
  1101. }
  1102. return Pass::create(passDesc);
  1103. }
  1104. TechniquePtr BSLFXCompiler::parseTechnique(ASTFXNode* techniqueNode, const Vector<CodeBlock>& codeBlocks)
  1105. {
  1106. if (techniqueNode == nullptr || techniqueNode->type != NT_Technique)
  1107. return nullptr;
  1108. Vector<ASTFXNode*> passNodes;
  1109. StringID renderer = RendererAny;
  1110. StringID renderAPI = RenderAPIAny;
  1111. String language;
  1112. PassData commonPassData;
  1113. for (int i = 0; i < techniqueNode->options->count; i++)
  1114. {
  1115. NodeOption* option = &techniqueNode->options->entries[i];
  1116. switch (option->type)
  1117. {
  1118. case OT_Pass:
  1119. passNodes.push_back(option->value.nodePtr);
  1120. break;
  1121. case OT_Renderer:
  1122. renderer = parseRenderer(removeQuotes(option->value.strValue));
  1123. break;
  1124. case OT_Language:
  1125. parseLanguage(removeQuotes(option->value.strValue), renderAPI, language);
  1126. break;
  1127. case OT_Code:
  1128. parseCodeBlock(option->value.nodePtr, codeBlocks, commonPassData);
  1129. break;
  1130. }
  1131. }
  1132. commonPassData.blendIsDefault = !parseBlendState(commonPassData.blendDesc, techniqueNode);
  1133. commonPassData.rasterizerIsDefault = !parseRasterizerState(commonPassData.rasterizerDesc, techniqueNode);
  1134. commonPassData.depthStencilIsDefault = !parseDepthStencilState(commonPassData.depthStencilDesc, techniqueNode);
  1135. UINT32 nextPassIdx = 0;
  1136. Map<UINT32, PassPtr, std::greater<UINT32>> passes;
  1137. for (auto& passNode : passNodes)
  1138. {
  1139. PassData passDataCopy = commonPassData;
  1140. UINT32 passIdx = nextPassIdx;
  1141. PassPtr pass = parsePass(passNode, codeBlocks, passDataCopy, renderAPI, language, passIdx);
  1142. if (pass != nullptr)
  1143. passes[passIdx] = pass;
  1144. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  1145. }
  1146. Vector<PassPtr> orderedPasses;
  1147. for (auto& KVP : passes)
  1148. orderedPasses.push_back(KVP.second);
  1149. if (orderedPasses.size() > 0)
  1150. return Technique::create(renderAPI, renderer, orderedPasses);
  1151. return nullptr;
  1152. }
  1153. void BSLFXCompiler::parseParameters(SHADER_DESC& desc, ASTFXNode* parametersNode)
  1154. {
  1155. if (parametersNode == nullptr || parametersNode->type != NT_Parameters)
  1156. return;
  1157. for (int i = 0; i < parametersNode->options->count; i++)
  1158. {
  1159. NodeOption* option = &parametersNode->options->entries[i];
  1160. if (option->type != OT_Parameter)
  1161. continue;
  1162. ASTFXNode* parameter = option->value.nodePtr;
  1163. String name;
  1164. String alias;
  1165. float defaultValue[16];
  1166. bool hasDefaultValue = false;
  1167. UINT32 typeId = 0;
  1168. bool isObjType = false;
  1169. StringID semantic;
  1170. SamplerStatePtr samplerState = nullptr;
  1171. for (int j = 0; j < parameter->options->count; j++)
  1172. {
  1173. NodeOption* paramOption = &parameter->options->entries[j];
  1174. switch (paramOption->type)
  1175. {
  1176. case OT_Identifier:
  1177. name = paramOption->value.strValue;
  1178. break;
  1179. case OT_Alias:
  1180. alias = removeQuotes(paramOption->value.strValue);
  1181. break;
  1182. case OT_ParamValue:
  1183. memcpy(defaultValue, paramOption->value.matrixValue, sizeof(defaultValue));
  1184. hasDefaultValue = true;
  1185. break;
  1186. case OT_ParamType:
  1187. parseParamType((ParamType)paramOption->value.intValue, isObjType, typeId);
  1188. break;
  1189. case OT_Auto:
  1190. semantic = removeQuotes(paramOption->value.strValue);
  1191. break;
  1192. case OT_SamplerState:
  1193. samplerState = parseSamplerState(paramOption->value.nodePtr);
  1194. break;
  1195. }
  1196. }
  1197. if (name.empty())
  1198. continue;
  1199. auto addParameter = [&](const String& paramName, const String& gpuVarName)
  1200. {
  1201. if (isObjType)
  1202. {
  1203. GpuParamObjectType objType = (GpuParamObjectType)typeId;
  1204. if (Shader::isSampler(objType) && hasDefaultValue)
  1205. desc.addParameter(paramName, gpuVarName, objType, samplerState, semantic);
  1206. else
  1207. desc.addParameter(paramName, gpuVarName, objType, semantic);
  1208. }
  1209. else
  1210. {
  1211. if (hasDefaultValue)
  1212. desc.addParameter(paramName, gpuVarName, (GpuParamDataType)typeId, semantic, 1, 0, (UINT8*)defaultValue);
  1213. else
  1214. desc.addParameter(paramName, gpuVarName, (GpuParamDataType)typeId, semantic);
  1215. }
  1216. };
  1217. addParameter(name, name);
  1218. if (!alias.empty())
  1219. addParameter(name, alias);
  1220. }
  1221. }
  1222. void BSLFXCompiler::parseBlocks(SHADER_DESC& desc, ASTFXNode* blocksNode)
  1223. {
  1224. if (blocksNode == nullptr || blocksNode->type != NT_Blocks)
  1225. return;
  1226. for (int i = 0; i < blocksNode->options->count; i++)
  1227. {
  1228. NodeOption* option = &blocksNode->options->entries[i];
  1229. if (option->type != OT_Block)
  1230. continue;
  1231. ASTFXNode* parameter = option->value.nodePtr;
  1232. String name;
  1233. bool shared = false;
  1234. GpuParamBlockUsage usage = GPBU_STATIC;
  1235. StringID semantic;
  1236. for (int j = 0; j < parameter->options->count; j++)
  1237. {
  1238. NodeOption* paramOption = &parameter->options->entries[j];
  1239. switch (paramOption->type)
  1240. {
  1241. case OT_Identifier:
  1242. name = paramOption->value.strValue;
  1243. break;
  1244. case OT_Shared:
  1245. shared = paramOption->value.intValue > 0;
  1246. break;
  1247. case OT_Usage:
  1248. usage = parseBlockUsage((BufferUsageValue)paramOption->value.intValue);
  1249. break;
  1250. case OT_Auto:
  1251. semantic = removeQuotes(paramOption->value.strValue);
  1252. break;
  1253. }
  1254. }
  1255. if (name.empty())
  1256. continue;
  1257. desc.setParamBlockAttribs(name, shared, usage, semantic);
  1258. }
  1259. }
  1260. ShaderPtr BSLFXCompiler::parseShader(const String& name, ParseState* parseState, Vector<CodeBlock>& codeBlocks)
  1261. {
  1262. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  1263. return nullptr;
  1264. // Merge all include ASTs
  1265. std::function<ParseState*(ParseState*, Vector<CodeBlock>&)> parseIncludes = [&](ParseState* parentParseState, Vector<CodeBlock>& parentCodeBlocks)
  1266. {
  1267. ASTFXNode* node = parentParseState->rootNode;
  1268. Vector<tuple<ParseState*, Vector<CodeBlock>>> toMerge;
  1269. for (int i = 0; i < node->options->count; i++)
  1270. {
  1271. NodeOption* option = &node->options->entries[i];
  1272. if (option->type == OT_Include)
  1273. {
  1274. String includePath = removeQuotes(option->value.strValue);
  1275. HShaderInclude include = ShaderManager::instance().findInclude(includePath);
  1276. if (include != nullptr)
  1277. {
  1278. include.blockUntilLoaded();
  1279. String includeSource = include->getString();
  1280. ParseState* includeParseState = parseStateCreate();
  1281. Vector<CodeBlock> includeCodeBlocks = parseCodeBlocks(includeSource);
  1282. parseFX(includeParseState, includeSource.c_str());
  1283. ShaderPtr output;
  1284. if (includeParseState->hasError > 0)
  1285. {
  1286. LOGERR("Error while parsing shader FX code: " + String(includeParseState->errorMessage) + ". Location: " +
  1287. toString(includeParseState->errorLine) + " (" + toString(includeParseState->errorColumn) + ")");
  1288. parseStateDelete(includeParseState);
  1289. }
  1290. else
  1291. {
  1292. ParseState* combinedIncludeParseState = parseIncludes(includeParseState, includeCodeBlocks);
  1293. toMerge.push_back(make_tuple(combinedIncludeParseState, includeCodeBlocks));
  1294. }
  1295. }
  1296. else
  1297. {
  1298. LOGERR("Cannot find shader include file: " + includePath);
  1299. }
  1300. }
  1301. }
  1302. UINT32 size = (UINT32)toMerge.size();
  1303. if (size > 0)
  1304. {
  1305. Vector<CodeBlock>& outputCodeBlocks = get<1>(toMerge[0]);
  1306. for (UINT32 i = 1; i < size; i++)
  1307. {
  1308. mergeAST(get<0>(toMerge[0]), get<0>(toMerge[i])->rootNode, (UINT32)outputCodeBlocks.size());
  1309. const Vector<CodeBlock>& curCodeBlocks = get<1>(toMerge[i]);
  1310. for (auto& codeBlock : curCodeBlocks)
  1311. outputCodeBlocks.push_back(codeBlock);
  1312. parseStateDelete(get<0>(toMerge[i]));
  1313. }
  1314. mergeAST(get<0>(toMerge[0]), node, (UINT32)outputCodeBlocks.size());
  1315. for (auto& codeBlock : parentCodeBlocks)
  1316. outputCodeBlocks.push_back(codeBlock);
  1317. parseStateDelete(parentParseState);
  1318. parentCodeBlocks = outputCodeBlocks;
  1319. return get<0>(toMerge[0]);
  1320. }
  1321. else
  1322. return parentParseState;
  1323. };
  1324. parseState = parseIncludes(parseState, codeBlocks);
  1325. Vector<String> topLevelIncludes;
  1326. SHADER_DESC shaderDesc;
  1327. Vector<TechniquePtr> techniques;
  1328. for (int i = 0; i < parseState->rootNode->options->count; i++)
  1329. {
  1330. NodeOption* option = &parseState->rootNode->options->entries[i];
  1331. switch (option->type)
  1332. {
  1333. case OT_Include:
  1334. {
  1335. String includePath = removeQuotes(option->value.strValue);
  1336. topLevelIncludes.push_back(includePath);
  1337. }
  1338. break;
  1339. case OT_Separable:
  1340. shaderDesc.separablePasses = option->value.intValue > 1;
  1341. break;
  1342. case OT_Queue:
  1343. shaderDesc.queuePriority = option->value.intValue;
  1344. break;
  1345. case OT_Priority:
  1346. shaderDesc.queuePriority = option->value.intValue;
  1347. break;
  1348. case OT_Transparent:
  1349. shaderDesc.flags |= (UINT32)ShaderFlags::Transparent;
  1350. break;
  1351. case OT_Technique:
  1352. {
  1353. TechniquePtr technique = parseTechnique(option->value.nodePtr, codeBlocks);
  1354. if (technique != nullptr)
  1355. techniques.push_back(technique);
  1356. break;
  1357. }
  1358. case OT_Parameters:
  1359. parseParameters(shaderDesc, option->value.nodePtr);
  1360. break;
  1361. case OT_Blocks:
  1362. parseBlocks(shaderDesc, option->value.nodePtr);
  1363. break;
  1364. }
  1365. }
  1366. parseStateDelete(parseState);
  1367. ShaderPtr output = Shader::_createPtr(name, shaderDesc, techniques);
  1368. output->setIncludeFiles(topLevelIncludes);
  1369. return output;
  1370. }
  1371. String BSLFXCompiler::removeQuotes(const char* input)
  1372. {
  1373. UINT32 len = (UINT32)strlen(input);
  1374. String output(len - 2, ' ');
  1375. for (UINT32 i = 0; i < (len - 2); i++)
  1376. output[i] = input[i + 1];
  1377. return output;
  1378. }
  1379. GpuProgramProfile BSLFXCompiler::getProfile(const StringID& renderAPI, GpuProgramType type)
  1380. {
  1381. StringID target = renderAPI;
  1382. if (target == RenderAPIAny)
  1383. target = RenderAPICore::instance().getName();
  1384. if (target == RenderAPIDX11 || target == RenderAPIOpenGL)
  1385. {
  1386. switch (type)
  1387. {
  1388. case GPT_VERTEX_PROGRAM:
  1389. return GPP_VS_5_0;
  1390. case GPT_FRAGMENT_PROGRAM:
  1391. return GPP_FS_5_0;
  1392. case GPT_GEOMETRY_PROGRAM:
  1393. return GPP_GS_5_0;
  1394. case GPT_HULL_PROGRAM:
  1395. return GPP_HS_5_0;
  1396. case GPT_DOMAIN_PROGRAM:
  1397. return GPP_DS_5_0;
  1398. case GPT_COMPUTE_PROGRAM:
  1399. return GPP_CS_5_0;
  1400. }
  1401. }
  1402. else if (target == RenderAPIDX9)
  1403. {
  1404. switch (type)
  1405. {
  1406. case GPT_VERTEX_PROGRAM:
  1407. return GPP_VS_3_0;
  1408. case GPT_FRAGMENT_PROGRAM:
  1409. return GPP_FS_3_0;
  1410. }
  1411. }
  1412. return GPP_NONE;
  1413. }
  1414. }