BsSLFXCompiler.cpp 48 KB

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