BsSLFXCompiler.cpp 47 KB

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