GlslDecompiler.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Ryujinx.Graphics.Gal.Shader
  7. {
  8. public class GlslDecompiler
  9. {
  10. private delegate string GetInstExpr(ShaderIrOp Op);
  11. private Dictionary<ShaderIrInst, GetInstExpr> InstsExpr;
  12. private enum OperType
  13. {
  14. Bool,
  15. F32,
  16. I32
  17. }
  18. private const string IdentationStr = " ";
  19. private static string[] ElemTypes = new string[] { "float", "vec2", "vec3", "vec4" };
  20. private GlslDecl Decl;
  21. private ShaderIrBlock[] Blocks;
  22. private StringBuilder SB;
  23. public GlslDecompiler()
  24. {
  25. InstsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  26. {
  27. { ShaderIrInst.Abs, GetAbsExpr },
  28. { ShaderIrInst.Add, GetAddExpr },
  29. { ShaderIrInst.And, GetAndExpr },
  30. { ShaderIrInst.Asr, GetAsrExpr },
  31. { ShaderIrInst.Band, GetBandExpr },
  32. { ShaderIrInst.Bnot, GetBnotExpr },
  33. { ShaderIrInst.Bor, GetBorExpr },
  34. { ShaderIrInst.Bxor, GetBxorExpr },
  35. { ShaderIrInst.Ceil, GetCeilExpr },
  36. { ShaderIrInst.Ceq, GetCeqExpr },
  37. { ShaderIrInst.Cge, GetCgeExpr },
  38. { ShaderIrInst.Cgt, GetCgtExpr },
  39. { ShaderIrInst.Clamps, GetClampsExpr },
  40. { ShaderIrInst.Clampu, GetClampuExpr },
  41. { ShaderIrInst.Cle, GetCleExpr },
  42. { ShaderIrInst.Clt, GetCltExpr },
  43. { ShaderIrInst.Cne, GetCneExpr },
  44. { ShaderIrInst.Exit, GetExitExpr },
  45. { ShaderIrInst.Fabs, GetAbsExpr },
  46. { ShaderIrInst.Fadd, GetAddExpr },
  47. { ShaderIrInst.Fceq, GetCeqExpr },
  48. { ShaderIrInst.Fcequ, GetCequExpr },
  49. { ShaderIrInst.Fcge, GetCgeExpr },
  50. { ShaderIrInst.Fcgeu, GetCgeuExpr },
  51. { ShaderIrInst.Fcgt, GetCgtExpr },
  52. { ShaderIrInst.Fcgtu, GetCgtuExpr },
  53. { ShaderIrInst.Fclamp, GetFclampExpr },
  54. { ShaderIrInst.Fcle, GetCleExpr },
  55. { ShaderIrInst.Fcleu, GetCleuExpr },
  56. { ShaderIrInst.Fclt, GetCltExpr },
  57. { ShaderIrInst.Fcltu, GetCltuExpr },
  58. { ShaderIrInst.Fcnan, GetCnanExpr },
  59. { ShaderIrInst.Fcne, GetCneExpr },
  60. { ShaderIrInst.Fcneu, GetCneuExpr },
  61. { ShaderIrInst.Fcnum, GetCnumExpr },
  62. { ShaderIrInst.Fcos, GetFcosExpr },
  63. { ShaderIrInst.Fex2, GetFex2Expr },
  64. { ShaderIrInst.Ffma, GetFfmaExpr },
  65. { ShaderIrInst.Flg2, GetFlg2Expr },
  66. { ShaderIrInst.Floor, GetFloorExpr },
  67. { ShaderIrInst.Fmax, GetMaxExpr },
  68. { ShaderIrInst.Fmin, GetMinExpr },
  69. { ShaderIrInst.Fmul, GetMulExpr },
  70. { ShaderIrInst.Fneg, GetNegExpr },
  71. { ShaderIrInst.Frcp, GetFrcpExpr },
  72. { ShaderIrInst.Frsq, GetFrsqExpr },
  73. { ShaderIrInst.Fsin, GetFsinExpr },
  74. { ShaderIrInst.Ftos, GetFtosExpr },
  75. { ShaderIrInst.Ftou, GetFtouExpr },
  76. { ShaderIrInst.Ipa, GetIpaExpr },
  77. { ShaderIrInst.Kil, GetKilExpr },
  78. { ShaderIrInst.Lsl, GetLslExpr },
  79. { ShaderIrInst.Lsr, GetLsrExpr },
  80. { ShaderIrInst.Max, GetMaxExpr },
  81. { ShaderIrInst.Min, GetMinExpr },
  82. { ShaderIrInst.Mul, GetMulExpr },
  83. { ShaderIrInst.Neg, GetNegExpr },
  84. { ShaderIrInst.Not, GetNotExpr },
  85. { ShaderIrInst.Or, GetOrExpr },
  86. { ShaderIrInst.Stof, GetStofExpr },
  87. { ShaderIrInst.Sub, GetSubExpr },
  88. { ShaderIrInst.Texq, GetTexqExpr },
  89. { ShaderIrInst.Texs, GetTexsExpr },
  90. { ShaderIrInst.Trunc, GetTruncExpr },
  91. { ShaderIrInst.Txlf, GetTxlfExpr },
  92. { ShaderIrInst.Utof, GetUtofExpr },
  93. { ShaderIrInst.Xor, GetXorExpr }
  94. };
  95. }
  96. public GlslProgram Decompile(IGalMemory Memory, long Position, GalShaderType ShaderType)
  97. {
  98. Blocks = ShaderDecoder.Decode(Memory, Position);
  99. Decl = new GlslDecl(Blocks, ShaderType);
  100. SB = new StringBuilder();
  101. SB.AppendLine("#version 410 core");
  102. PrintDeclTextures();
  103. PrintDeclUniforms();
  104. PrintDeclInAttributes();
  105. PrintDeclOutAttributes();
  106. PrintDeclGprs();
  107. PrintDeclPreds();
  108. PrintBlockScope(Blocks[0], null, null, "void main()", IdentationStr);
  109. string GlslCode = SB.ToString();
  110. return new GlslProgram(
  111. GlslCode,
  112. Decl.Textures.Values,
  113. Decl.Uniforms.Values);
  114. }
  115. private void PrintDeclTextures()
  116. {
  117. PrintDecls(Decl.Textures, "uniform sampler2D");
  118. }
  119. private void PrintDeclUniforms()
  120. {
  121. if (Decl.ShaderType == GalShaderType.Vertex)
  122. {
  123. SB.AppendLine("uniform vec2 " + GalConsts.FlipUniformName + ";");
  124. }
  125. foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector))
  126. {
  127. SB.AppendLine($"uniform {GetDecl(DeclInfo)}[{DeclInfo.Index + 1}];");
  128. }
  129. if (Decl.Uniforms.Count > 0)
  130. {
  131. SB.AppendLine();
  132. }
  133. }
  134. private void PrintDeclInAttributes()
  135. {
  136. if (Decl.ShaderType == GalShaderType.Fragment)
  137. {
  138. SB.AppendLine("in vec4 " + GlslDecl.PositionOutAttrName + ";");
  139. }
  140. PrintDeclAttributes(Decl.InAttributes.Values, "in");
  141. }
  142. private void PrintDeclOutAttributes()
  143. {
  144. if (Decl.ShaderType == GalShaderType.Vertex)
  145. {
  146. SB.AppendLine("out vec4 " + GlslDecl.PositionOutAttrName + ";");
  147. }
  148. PrintDeclAttributes(Decl.OutAttributes.Values, "out");
  149. }
  150. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> Decls, string InOut)
  151. {
  152. int Count = 0;
  153. foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector))
  154. {
  155. if (DeclInfo.Index >= 0)
  156. {
  157. SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " " + GetDecl(DeclInfo) + ";");
  158. Count++;
  159. }
  160. }
  161. if (Count > 0)
  162. {
  163. SB.AppendLine();
  164. }
  165. }
  166. private void PrintDeclGprs()
  167. {
  168. PrintDecls(Decl.Gprs);
  169. }
  170. private void PrintDeclPreds()
  171. {
  172. PrintDecls(Decl.Preds, "bool");
  173. }
  174. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, string CustomType = null)
  175. {
  176. foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector))
  177. {
  178. string Name;
  179. if (CustomType != null)
  180. {
  181. Name = CustomType + " " + DeclInfo.Name + ";";
  182. }
  183. else if (DeclInfo.Name == GlslDecl.FragmentOutputName)
  184. {
  185. Name = "layout (location = 0) out " + GetDecl(DeclInfo) + ";" + Environment.NewLine;
  186. }
  187. else
  188. {
  189. Name = GetDecl(DeclInfo) + ";";
  190. }
  191. SB.AppendLine(Name);
  192. }
  193. if (Dict.Count > 0)
  194. {
  195. SB.AppendLine();
  196. }
  197. }
  198. private int DeclKeySelector(ShaderDeclInfo DeclInfo)
  199. {
  200. return DeclInfo.Cbuf << 24 | DeclInfo.Index;
  201. }
  202. private string GetDecl(ShaderDeclInfo DeclInfo)
  203. {
  204. return ElemTypes[DeclInfo.Size - 1] + " " + DeclInfo.Name;
  205. }
  206. private void PrintBlockScope(
  207. ShaderIrBlock Block,
  208. ShaderIrBlock EndBlock,
  209. ShaderIrBlock LoopBlock,
  210. string ScopeName,
  211. string Identation,
  212. bool IsDoWhile = false)
  213. {
  214. string UpIdent = Identation.Substring(0, Identation.Length - IdentationStr.Length);
  215. if (IsDoWhile)
  216. {
  217. SB.AppendLine(UpIdent + "do {");
  218. }
  219. else
  220. {
  221. SB.AppendLine(UpIdent + ScopeName + " {");
  222. }
  223. while (Block != null && Block != EndBlock)
  224. {
  225. ShaderIrNode[] Nodes = Block.GetNodes();
  226. Block = PrintNodes(Block, EndBlock, LoopBlock, Identation, Nodes);
  227. }
  228. if (IsDoWhile)
  229. {
  230. SB.AppendLine(UpIdent + "} " + ScopeName + ";");
  231. }
  232. else
  233. {
  234. SB.AppendLine(UpIdent + "}");
  235. }
  236. }
  237. private ShaderIrBlock PrintNodes(
  238. ShaderIrBlock Block,
  239. ShaderIrBlock EndBlock,
  240. ShaderIrBlock LoopBlock,
  241. string Identation,
  242. params ShaderIrNode[] Nodes)
  243. {
  244. /*
  245. * Notes about control flow and if-else/loop generation:
  246. * The code assumes that the program has sane control flow,
  247. * that is, there's no jumps to a location after another jump or
  248. * jump target (except for the end of an if-else block), and backwards
  249. * jumps to a location before the last loop dominator.
  250. * Such cases needs to be transformed on a step before the GLSL code
  251. * generation to ensure that we have sane graphs to work with.
  252. * TODO: Such transformation is not yet implemented.
  253. */
  254. string NewIdent = Identation + IdentationStr;
  255. ShaderIrBlock LoopTail = GetLoopTailBlock(Block);
  256. if (LoopTail != null && LoopBlock != Block)
  257. {
  258. //Shoock! kuma shock! We have a loop here!
  259. //The entire sequence needs to be inside a do-while block.
  260. ShaderIrBlock LoopEnd = GetDownBlock(LoopTail);
  261. PrintBlockScope(Block, LoopEnd, Block, "while (false)", NewIdent, IsDoWhile: true);
  262. return LoopEnd;
  263. }
  264. foreach (ShaderIrNode Node in Nodes)
  265. {
  266. if (Node is ShaderIrCond Cond)
  267. {
  268. string IfExpr = GetSrcExpr(Cond.Pred, true);
  269. if (Cond.Not)
  270. {
  271. IfExpr = "!(" + IfExpr + ")";
  272. }
  273. if (Cond.Child is ShaderIrOp Op && Op.Inst == ShaderIrInst.Bra)
  274. {
  275. //Branch is a loop branch and would result in infinite recursion.
  276. if (Block.Branch.Position <= Block.Position)
  277. {
  278. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  279. SB.AppendLine(Identation + IdentationStr + "continue;");
  280. SB.AppendLine(Identation + "}");
  281. continue;
  282. }
  283. string SubScopeName = "if (!" + IfExpr + ")";
  284. PrintBlockScope(Block.Next, Block.Branch, LoopBlock, SubScopeName, NewIdent);
  285. ShaderIrBlock IfElseEnd = GetUpBlock(Block.Branch).Branch;
  286. if (IfElseEnd?.Position > Block.Branch.Position)
  287. {
  288. PrintBlockScope(Block.Branch, IfElseEnd, LoopBlock, "else", NewIdent);
  289. return IfElseEnd;
  290. }
  291. return Block.Branch;
  292. }
  293. else
  294. {
  295. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  296. PrintNodes(Block, EndBlock, LoopBlock, NewIdent, Cond.Child);
  297. SB.AppendLine(Identation + "}");
  298. }
  299. }
  300. else if (Node is ShaderIrAsg Asg)
  301. {
  302. if (IsValidOutOper(Asg.Dst))
  303. {
  304. string Expr = GetSrcExpr(Asg.Src, true);
  305. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  306. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  307. }
  308. }
  309. else if (Node is ShaderIrOp Op)
  310. {
  311. if (Op.Inst == ShaderIrInst.Bra)
  312. {
  313. if (Block.Branch.Position <= Block.Position)
  314. {
  315. SB.AppendLine(Identation + "continue;");
  316. }
  317. continue;
  318. }
  319. else if (Op.Inst == ShaderIrInst.Exit)
  320. {
  321. //Do everything that needs to be done before
  322. //the shader ends here.
  323. if (Decl.ShaderType == GalShaderType.Vertex)
  324. {
  325. SB.AppendLine(Identation + "gl_Position.xy *= flip;");
  326. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  327. }
  328. }
  329. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  330. }
  331. else if (Node is ShaderIrCmnt Cmnt)
  332. {
  333. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  334. }
  335. else
  336. {
  337. throw new InvalidOperationException();
  338. }
  339. }
  340. return Block.Next;
  341. }
  342. private ShaderIrBlock GetUpBlock(ShaderIrBlock Block)
  343. {
  344. return Blocks.FirstOrDefault(x => x.EndPosition == Block.Position);
  345. }
  346. private ShaderIrBlock GetDownBlock(ShaderIrBlock Block)
  347. {
  348. return Blocks.FirstOrDefault(x => x.Position == Block.EndPosition);
  349. }
  350. private ShaderIrBlock GetLoopTailBlock(ShaderIrBlock LoopHead)
  351. {
  352. ShaderIrBlock Tail = null;
  353. foreach (ShaderIrBlock Block in LoopHead.Sources)
  354. {
  355. if (Block.Position >= LoopHead.Position)
  356. {
  357. if (Tail == null || Tail.Position < Block.Position)
  358. {
  359. Tail = Block;
  360. }
  361. }
  362. }
  363. return Tail;
  364. }
  365. private bool IsValidOutOper(ShaderIrNode Node)
  366. {
  367. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  368. {
  369. return false;
  370. }
  371. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  372. {
  373. return false;
  374. }
  375. return true;
  376. }
  377. private string GetDstOperName(ShaderIrNode Node)
  378. {
  379. if (Node is ShaderIrOperAbuf Abuf)
  380. {
  381. return GetOutAbufName(Abuf);
  382. }
  383. else if (Node is ShaderIrOperGpr Gpr)
  384. {
  385. return GetName(Gpr);
  386. }
  387. else if (Node is ShaderIrOperPred Pred)
  388. {
  389. return GetName(Pred);
  390. }
  391. throw new ArgumentException(nameof(Node));
  392. }
  393. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  394. {
  395. switch (Node)
  396. {
  397. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  398. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  399. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  400. case ShaderIrOperImm Imm: return GetValue(Imm);
  401. case ShaderIrOperImmf Immf: return GetValue(Immf);
  402. case ShaderIrOperPred Pred: return GetName (Pred);
  403. case ShaderIrOp Op:
  404. string Expr;
  405. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  406. {
  407. Expr = GetExpr(Op);
  408. }
  409. else
  410. {
  411. throw new NotImplementedException(Op.Inst.ToString());
  412. }
  413. if (!Entry && NeedsParentheses(Op))
  414. {
  415. Expr = "(" + Expr + ")";
  416. }
  417. return Expr;
  418. default: throw new ArgumentException(nameof(Node));
  419. }
  420. }
  421. private static bool NeedsParentheses(ShaderIrOp Op)
  422. {
  423. switch (Op.Inst)
  424. {
  425. case ShaderIrInst.Frcp:
  426. return true;
  427. case ShaderIrInst.Ipa:
  428. case ShaderIrInst.Texq:
  429. case ShaderIrInst.Texs:
  430. case ShaderIrInst.Txlf:
  431. return false;
  432. }
  433. return Op.OperandB != null ||
  434. Op.OperandC != null;
  435. }
  436. private string GetName(ShaderIrOperCbuf Cbuf)
  437. {
  438. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  439. {
  440. throw new InvalidOperationException();
  441. }
  442. if (Cbuf.Offs != null)
  443. {
  444. //Note: We assume that the register value is always a multiple of 4.
  445. //This may not be aways the case.
  446. string Offset = "(floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ") >> 2)";
  447. return DeclInfo.Name + "[" + Cbuf.Pos + " + " + Offset + "]";
  448. }
  449. else
  450. {
  451. return DeclInfo.Name + "[" + Cbuf.Pos + "]";
  452. }
  453. }
  454. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  455. {
  456. return GetName(Decl.OutAttributes, Abuf);
  457. }
  458. private string GetName(ShaderIrOperAbuf Abuf)
  459. {
  460. if (Decl.ShaderType == GalShaderType.Vertex)
  461. {
  462. switch (Abuf.Offs)
  463. {
  464. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  465. case GlslDecl.InstanceIdAttr: return "gl_InstanceID";
  466. }
  467. }
  468. else if (Decl.ShaderType == GalShaderType.TessEvaluation)
  469. {
  470. switch (Abuf.Offs)
  471. {
  472. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  473. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  474. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  475. }
  476. }
  477. return GetName(Decl.InAttributes, Abuf);
  478. }
  479. private string GetName(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, ShaderIrOperAbuf Abuf)
  480. {
  481. int Index = Abuf.Offs >> 4;
  482. int Elem = (Abuf.Offs >> 2) & 3;
  483. if (!Dict.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  484. {
  485. throw new InvalidOperationException();
  486. }
  487. return DeclInfo.Size > 1 ? DeclInfo.Name + "." + GetAttrSwizzle(Elem) : DeclInfo.Name;
  488. }
  489. private string GetName(ShaderIrOperGpr Gpr)
  490. {
  491. return Gpr.IsConst ? "0" : GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  492. }
  493. private string GetValue(ShaderIrOperImm Imm)
  494. {
  495. //Only use hex is the value is too big and would likely be hard to read as int.
  496. if (Imm.Value > 0xfff ||
  497. Imm.Value < -0xfff)
  498. {
  499. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  500. }
  501. else
  502. {
  503. return Imm.Value.ToString(CultureInfo.InvariantCulture);
  504. }
  505. }
  506. private string GetValue(ShaderIrOperImmf Immf)
  507. {
  508. return Immf.Value.ToString(CultureInfo.InvariantCulture);
  509. }
  510. private string GetName(ShaderIrOperPred Pred)
  511. {
  512. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  513. }
  514. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  515. {
  516. int VecIndex = Index >> 2;
  517. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  518. {
  519. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  520. {
  521. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  522. }
  523. }
  524. if (!Dict.TryGetValue(Index, out DeclInfo))
  525. {
  526. throw new InvalidOperationException();
  527. }
  528. return DeclInfo.Name;
  529. }
  530. private string GetAttrSwizzle(int Elem)
  531. {
  532. return "xyzw".Substring(Elem, 1);
  533. }
  534. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  535. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  536. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  537. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  538. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  539. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  540. private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||");
  541. private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^");
  542. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  543. private string GetClampsExpr(ShaderIrOp Op)
  544. {
  545. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  546. GetOperExpr(Op, Op.OperandB) + ", " +
  547. GetOperExpr(Op, Op.OperandC) + ")";
  548. }
  549. private string GetClampuExpr(ShaderIrOp Op)
  550. {
  551. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  552. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  553. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  554. }
  555. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  556. private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "==");
  557. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  558. private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">=");
  559. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  560. private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">");
  561. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  562. private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<=");
  563. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  564. private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<");
  565. private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan");
  566. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  567. private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!=");
  568. private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan");
  569. private string GetExitExpr(ShaderIrOp Op) => "return";
  570. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  571. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  572. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  573. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  574. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  575. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  576. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  577. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  578. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  579. private string GetFtosExpr(ShaderIrOp Op)
  580. {
  581. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  582. }
  583. private string GetFtouExpr(ShaderIrOp Op)
  584. {
  585. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  586. }
  587. private string GetIpaExpr(ShaderIrOp Op) => GetSrcExpr(Op.OperandA);
  588. private string GetKilExpr(ShaderIrOp Op) => "discard";
  589. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  590. private string GetLsrExpr(ShaderIrOp Op)
  591. {
  592. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  593. GetOperExpr(Op, Op.OperandB) + ")";
  594. }
  595. private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  596. private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  597. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  598. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  599. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  600. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  601. private string GetStofExpr(ShaderIrOp Op)
  602. {
  603. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  604. }
  605. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  606. private string GetTexqExpr(ShaderIrOp Op)
  607. {
  608. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  609. string Ch = "xyzw".Substring(Meta.Elem, 1);
  610. if (Meta.Info == ShaderTexqInfo.Dimension)
  611. {
  612. string Sampler = GetTexSamplerName(Op);
  613. string Lod = GetOperExpr(Op, Op.OperandA); //???
  614. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  615. }
  616. else
  617. {
  618. throw new NotImplementedException(Meta.Info.ToString());
  619. }
  620. }
  621. private string GetTexsExpr(ShaderIrOp Op)
  622. {
  623. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  624. string Sampler = GetTexSamplerName(Op);
  625. string Coords = GetTexSamplerCoords(Op);
  626. string Ch = "rgba".Substring(Meta.Elem, 1);
  627. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  628. }
  629. private string GetTxlfExpr(ShaderIrOp Op)
  630. {
  631. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  632. string Sampler = GetTexSamplerName(Op);
  633. string Coords = GetITexSamplerCoords(Op);
  634. string Ch = "rgba".Substring(Meta.Elem, 1);
  635. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  636. }
  637. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  638. private string GetUtofExpr(ShaderIrOp Op)
  639. {
  640. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  641. }
  642. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  643. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  644. {
  645. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  646. }
  647. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  648. {
  649. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  650. GetOperExpr(Op, Op.OperandB) + ")";
  651. }
  652. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  653. {
  654. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  655. GetOperExpr(Op, Op.OperandB) + ", " +
  656. GetOperExpr(Op, Op.OperandC) + ")";
  657. }
  658. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  659. {
  660. return Opr + GetOperExpr(Op, Op.OperandA);
  661. }
  662. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  663. {
  664. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  665. GetOperExpr(Op, Op.OperandB);
  666. }
  667. private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr)
  668. {
  669. string A = GetOperExpr(Op, Op.OperandA);
  670. string B = GetOperExpr(Op, Op.OperandB);
  671. string NaNCheck =
  672. " || isnan(" + A + ")" +
  673. " || isnan(" + B + ")";
  674. return A + " " + Opr + " " + B + NaNCheck;
  675. }
  676. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  677. {
  678. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  679. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  680. GetOperExpr(Op, Op.OperandC);
  681. }
  682. private string GetTexSamplerName(ShaderIrOp Op)
  683. {
  684. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  685. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  686. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  687. {
  688. throw new InvalidOperationException();
  689. }
  690. return DeclInfo.Name;
  691. }
  692. private string GetTexSamplerCoords(ShaderIrOp Op)
  693. {
  694. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  695. GetOperExpr(Op, Op.OperandB) + ")";
  696. }
  697. private string GetITexSamplerCoords(ShaderIrOp Op)
  698. {
  699. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  700. GetOperExpr(Op, Op.OperandB) + ")";
  701. }
  702. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  703. {
  704. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  705. }
  706. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  707. {
  708. //Note: The "DstType" (of the cast) is the type that the operation
  709. //uses on the source operands, while the "SrcType" is the destination
  710. //type of the operand result (if it is a operation) or just the type
  711. //of the variable for registers/uniforms/attributes.
  712. OperType DstType = GetSrcNodeType(Dst);
  713. OperType SrcType = GetDstNodeType(Src);
  714. if (DstType != SrcType)
  715. {
  716. //Check for invalid casts
  717. //(like bool to int/float and others).
  718. if (SrcType != OperType.F32 &&
  719. SrcType != OperType.I32)
  720. {
  721. throw new InvalidOperationException();
  722. }
  723. switch (Src)
  724. {
  725. case ShaderIrOperGpr Gpr:
  726. {
  727. //When the Gpr is ZR, just return the 0 value directly,
  728. //since the float encoding for 0 is 0.
  729. if (Gpr.IsConst)
  730. {
  731. return "0";
  732. }
  733. break;
  734. }
  735. case ShaderIrOperImm Imm:
  736. {
  737. //For integer immediates being used as float,
  738. //it's better (for readability) to just return the float value.
  739. if (DstType == OperType.F32)
  740. {
  741. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  742. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  743. {
  744. return Value.ToString(CultureInfo.InvariantCulture);
  745. }
  746. }
  747. break;
  748. }
  749. }
  750. switch (DstType)
  751. {
  752. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  753. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  754. }
  755. }
  756. return Expr;
  757. }
  758. private static OperType GetDstNodeType(ShaderIrNode Node)
  759. {
  760. //Special case instructions with the result type different
  761. //from the input types (like integer <-> float conversion) here.
  762. if (Node is ShaderIrOp Op)
  763. {
  764. switch (Op.Inst)
  765. {
  766. case ShaderIrInst.Stof:
  767. case ShaderIrInst.Txlf:
  768. case ShaderIrInst.Utof:
  769. return OperType.F32;
  770. case ShaderIrInst.Ftos:
  771. case ShaderIrInst.Ftou:
  772. return OperType.I32;
  773. }
  774. }
  775. return GetSrcNodeType(Node);
  776. }
  777. private static OperType GetSrcNodeType(ShaderIrNode Node)
  778. {
  779. switch (Node)
  780. {
  781. case ShaderIrOperAbuf Abuf:
  782. return Abuf.Offs == GlslDecl.VertexIdAttr
  783. ? OperType.I32
  784. : OperType.F32;
  785. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  786. case ShaderIrOperGpr Gpr: return OperType.F32;
  787. case ShaderIrOperImm Imm: return OperType.I32;
  788. case ShaderIrOperImmf Immf: return OperType.F32;
  789. case ShaderIrOperPred Pred: return OperType.Bool;
  790. case ShaderIrOp Op:
  791. if (Op.Inst > ShaderIrInst.B_Start &&
  792. Op.Inst < ShaderIrInst.B_End)
  793. {
  794. return OperType.Bool;
  795. }
  796. else if (Op.Inst > ShaderIrInst.F_Start &&
  797. Op.Inst < ShaderIrInst.F_End)
  798. {
  799. return OperType.F32;
  800. }
  801. else if (Op.Inst > ShaderIrInst.I_Start &&
  802. Op.Inst < ShaderIrInst.I_End)
  803. {
  804. return OperType.I32;
  805. }
  806. break;
  807. }
  808. throw new ArgumentException(nameof(Node));
  809. }
  810. }
  811. }