GlslDecompiler.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + ".w = 1;");
  328. }
  329. }
  330. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  331. }
  332. else if (Node is ShaderIrCmnt Cmnt)
  333. {
  334. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  335. }
  336. else
  337. {
  338. throw new InvalidOperationException();
  339. }
  340. }
  341. return Block.Next;
  342. }
  343. private ShaderIrBlock GetUpBlock(ShaderIrBlock Block)
  344. {
  345. return Blocks.FirstOrDefault(x => x.EndPosition == Block.Position);
  346. }
  347. private ShaderIrBlock GetDownBlock(ShaderIrBlock Block)
  348. {
  349. return Blocks.FirstOrDefault(x => x.Position == Block.EndPosition);
  350. }
  351. private ShaderIrBlock GetLoopTailBlock(ShaderIrBlock LoopHead)
  352. {
  353. ShaderIrBlock Tail = null;
  354. foreach (ShaderIrBlock Block in LoopHead.Sources)
  355. {
  356. if (Block.Position >= LoopHead.Position)
  357. {
  358. if (Tail == null || Tail.Position < Block.Position)
  359. {
  360. Tail = Block;
  361. }
  362. }
  363. }
  364. return Tail;
  365. }
  366. private bool IsValidOutOper(ShaderIrNode Node)
  367. {
  368. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  369. {
  370. return false;
  371. }
  372. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  373. {
  374. return false;
  375. }
  376. return true;
  377. }
  378. private string GetDstOperName(ShaderIrNode Node)
  379. {
  380. if (Node is ShaderIrOperAbuf Abuf)
  381. {
  382. return GetOutAbufName(Abuf);
  383. }
  384. else if (Node is ShaderIrOperGpr Gpr)
  385. {
  386. return GetName(Gpr);
  387. }
  388. else if (Node is ShaderIrOperPred Pred)
  389. {
  390. return GetName(Pred);
  391. }
  392. throw new ArgumentException(nameof(Node));
  393. }
  394. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  395. {
  396. switch (Node)
  397. {
  398. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  399. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  400. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  401. case ShaderIrOperImm Imm: return GetValue(Imm);
  402. case ShaderIrOperImmf Immf: return GetValue(Immf);
  403. case ShaderIrOperPred Pred: return GetName (Pred);
  404. case ShaderIrOp Op:
  405. string Expr;
  406. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  407. {
  408. Expr = GetExpr(Op);
  409. }
  410. else
  411. {
  412. throw new NotImplementedException(Op.Inst.ToString());
  413. }
  414. if (!Entry && NeedsParentheses(Op))
  415. {
  416. Expr = "(" + Expr + ")";
  417. }
  418. return Expr;
  419. default: throw new ArgumentException(nameof(Node));
  420. }
  421. }
  422. private static bool NeedsParentheses(ShaderIrOp Op)
  423. {
  424. switch (Op.Inst)
  425. {
  426. case ShaderIrInst.Frcp:
  427. return true;
  428. case ShaderIrInst.Ipa:
  429. case ShaderIrInst.Texq:
  430. case ShaderIrInst.Texs:
  431. case ShaderIrInst.Txlf:
  432. return false;
  433. }
  434. return Op.OperandB != null ||
  435. Op.OperandC != null;
  436. }
  437. private string GetName(ShaderIrOperCbuf Cbuf)
  438. {
  439. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  440. {
  441. throw new InvalidOperationException();
  442. }
  443. if (Cbuf.Offs != null)
  444. {
  445. //Note: We assume that the register value is always a multiple of 4.
  446. //This may not be aways the case.
  447. string Offset = "(floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ") >> 2)";
  448. return DeclInfo.Name + "[" + Cbuf.Pos + " + " + Offset + "]";
  449. }
  450. else
  451. {
  452. return DeclInfo.Name + "[" + Cbuf.Pos + "]";
  453. }
  454. }
  455. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  456. {
  457. return GetName(Decl.OutAttributes, Abuf);
  458. }
  459. private string GetName(ShaderIrOperAbuf Abuf)
  460. {
  461. if (Decl.ShaderType == GalShaderType.Vertex)
  462. {
  463. switch (Abuf.Offs)
  464. {
  465. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  466. case GlslDecl.InstanceIdAttr: return "gl_InstanceID";
  467. }
  468. }
  469. else if (Decl.ShaderType == GalShaderType.TessEvaluation)
  470. {
  471. switch (Abuf.Offs)
  472. {
  473. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  474. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  475. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  476. }
  477. }
  478. return GetName(Decl.InAttributes, Abuf);
  479. }
  480. private string GetName(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, ShaderIrOperAbuf Abuf)
  481. {
  482. int Index = Abuf.Offs >> 4;
  483. int Elem = (Abuf.Offs >> 2) & 3;
  484. if (!Dict.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  485. {
  486. throw new InvalidOperationException();
  487. }
  488. return DeclInfo.Size > 1 ? DeclInfo.Name + "." + GetAttrSwizzle(Elem) : DeclInfo.Name;
  489. }
  490. private string GetName(ShaderIrOperGpr Gpr)
  491. {
  492. return Gpr.IsConst ? "0" : GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  493. }
  494. private string GetValue(ShaderIrOperImm Imm)
  495. {
  496. //Only use hex is the value is too big and would likely be hard to read as int.
  497. if (Imm.Value > 0xfff ||
  498. Imm.Value < -0xfff)
  499. {
  500. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  501. }
  502. else
  503. {
  504. return Imm.Value.ToString(CultureInfo.InvariantCulture);
  505. }
  506. }
  507. private string GetValue(ShaderIrOperImmf Immf)
  508. {
  509. return Immf.Value.ToString(CultureInfo.InvariantCulture);
  510. }
  511. private string GetName(ShaderIrOperPred Pred)
  512. {
  513. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  514. }
  515. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  516. {
  517. int VecIndex = Index >> 2;
  518. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  519. {
  520. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  521. {
  522. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  523. }
  524. }
  525. if (!Dict.TryGetValue(Index, out DeclInfo))
  526. {
  527. throw new InvalidOperationException();
  528. }
  529. return DeclInfo.Name;
  530. }
  531. private string GetAttrSwizzle(int Elem)
  532. {
  533. return "xyzw".Substring(Elem, 1);
  534. }
  535. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  536. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  537. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  538. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  539. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  540. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  541. private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||");
  542. private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^");
  543. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  544. private string GetClampsExpr(ShaderIrOp Op)
  545. {
  546. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  547. GetOperExpr(Op, Op.OperandB) + ", " +
  548. GetOperExpr(Op, Op.OperandC) + ")";
  549. }
  550. private string GetClampuExpr(ShaderIrOp Op)
  551. {
  552. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  553. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  554. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  555. }
  556. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  557. private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "==");
  558. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  559. private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">=");
  560. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  561. private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">");
  562. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  563. private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<=");
  564. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  565. private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<");
  566. private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan");
  567. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  568. private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!=");
  569. private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan");
  570. private string GetExitExpr(ShaderIrOp Op) => "return";
  571. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  572. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  573. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  574. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  575. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  576. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  577. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  578. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  579. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  580. private string GetFtosExpr(ShaderIrOp Op)
  581. {
  582. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  583. }
  584. private string GetFtouExpr(ShaderIrOp Op)
  585. {
  586. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  587. }
  588. private string GetIpaExpr(ShaderIrOp Op) => GetSrcExpr(Op.OperandA);
  589. private string GetKilExpr(ShaderIrOp Op) => "discard";
  590. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  591. private string GetLsrExpr(ShaderIrOp Op)
  592. {
  593. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  594. GetOperExpr(Op, Op.OperandB) + ")";
  595. }
  596. private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  597. private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  598. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  599. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  600. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  601. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  602. private string GetStofExpr(ShaderIrOp Op)
  603. {
  604. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  605. }
  606. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  607. private string GetTexqExpr(ShaderIrOp Op)
  608. {
  609. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  610. string Ch = "xyzw".Substring(Meta.Elem, 1);
  611. if (Meta.Info == ShaderTexqInfo.Dimension)
  612. {
  613. string Sampler = GetTexSamplerName(Op);
  614. string Lod = GetOperExpr(Op, Op.OperandA); //???
  615. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  616. }
  617. else
  618. {
  619. throw new NotImplementedException(Meta.Info.ToString());
  620. }
  621. }
  622. private string GetTexsExpr(ShaderIrOp Op)
  623. {
  624. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  625. string Sampler = GetTexSamplerName(Op);
  626. string Coords = GetTexSamplerCoords(Op);
  627. string Ch = "rgba".Substring(Meta.Elem, 1);
  628. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  629. }
  630. private string GetTxlfExpr(ShaderIrOp Op)
  631. {
  632. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  633. string Sampler = GetTexSamplerName(Op);
  634. string Coords = GetITexSamplerCoords(Op);
  635. string Ch = "rgba".Substring(Meta.Elem, 1);
  636. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  637. }
  638. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  639. private string GetUtofExpr(ShaderIrOp Op)
  640. {
  641. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  642. }
  643. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  644. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  645. {
  646. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  647. }
  648. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  649. {
  650. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  651. GetOperExpr(Op, Op.OperandB) + ")";
  652. }
  653. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  654. {
  655. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  656. GetOperExpr(Op, Op.OperandB) + ", " +
  657. GetOperExpr(Op, Op.OperandC) + ")";
  658. }
  659. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  660. {
  661. return Opr + GetOperExpr(Op, Op.OperandA);
  662. }
  663. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  664. {
  665. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  666. GetOperExpr(Op, Op.OperandB);
  667. }
  668. private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr)
  669. {
  670. string A = GetOperExpr(Op, Op.OperandA);
  671. string B = GetOperExpr(Op, Op.OperandB);
  672. string NaNCheck =
  673. " || isnan(" + A + ")" +
  674. " || isnan(" + B + ")";
  675. return A + " " + Opr + " " + B + NaNCheck;
  676. }
  677. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  678. {
  679. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  680. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  681. GetOperExpr(Op, Op.OperandC);
  682. }
  683. private string GetTexSamplerName(ShaderIrOp Op)
  684. {
  685. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  686. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  687. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  688. {
  689. throw new InvalidOperationException();
  690. }
  691. return DeclInfo.Name;
  692. }
  693. private string GetTexSamplerCoords(ShaderIrOp Op)
  694. {
  695. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  696. GetOperExpr(Op, Op.OperandB) + ")";
  697. }
  698. private string GetITexSamplerCoords(ShaderIrOp Op)
  699. {
  700. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  701. GetOperExpr(Op, Op.OperandB) + ")";
  702. }
  703. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  704. {
  705. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  706. }
  707. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  708. {
  709. //Note: The "DstType" (of the cast) is the type that the operation
  710. //uses on the source operands, while the "SrcType" is the destination
  711. //type of the operand result (if it is a operation) or just the type
  712. //of the variable for registers/uniforms/attributes.
  713. OperType DstType = GetSrcNodeType(Dst);
  714. OperType SrcType = GetDstNodeType(Src);
  715. if (DstType != SrcType)
  716. {
  717. //Check for invalid casts
  718. //(like bool to int/float and others).
  719. if (SrcType != OperType.F32 &&
  720. SrcType != OperType.I32)
  721. {
  722. throw new InvalidOperationException();
  723. }
  724. switch (Src)
  725. {
  726. case ShaderIrOperGpr Gpr:
  727. {
  728. //When the Gpr is ZR, just return the 0 value directly,
  729. //since the float encoding for 0 is 0.
  730. if (Gpr.IsConst)
  731. {
  732. return "0";
  733. }
  734. break;
  735. }
  736. case ShaderIrOperImm Imm:
  737. {
  738. //For integer immediates being used as float,
  739. //it's better (for readability) to just return the float value.
  740. if (DstType == OperType.F32)
  741. {
  742. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  743. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  744. {
  745. return Value.ToString(CultureInfo.InvariantCulture);
  746. }
  747. }
  748. break;
  749. }
  750. }
  751. switch (DstType)
  752. {
  753. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  754. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  755. }
  756. }
  757. return Expr;
  758. }
  759. private static OperType GetDstNodeType(ShaderIrNode Node)
  760. {
  761. //Special case instructions with the result type different
  762. //from the input types (like integer <-> float conversion) here.
  763. if (Node is ShaderIrOp Op)
  764. {
  765. switch (Op.Inst)
  766. {
  767. case ShaderIrInst.Stof:
  768. case ShaderIrInst.Txlf:
  769. case ShaderIrInst.Utof:
  770. return OperType.F32;
  771. case ShaderIrInst.Ftos:
  772. case ShaderIrInst.Ftou:
  773. return OperType.I32;
  774. }
  775. }
  776. return GetSrcNodeType(Node);
  777. }
  778. private static OperType GetSrcNodeType(ShaderIrNode Node)
  779. {
  780. switch (Node)
  781. {
  782. case ShaderIrOperAbuf Abuf:
  783. return Abuf.Offs == GlslDecl.VertexIdAttr ||
  784. Abuf.Offs == GlslDecl.InstanceIdAttr
  785. ? OperType.I32
  786. : OperType.F32;
  787. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  788. case ShaderIrOperGpr Gpr: return OperType.F32;
  789. case ShaderIrOperImm Imm: return OperType.I32;
  790. case ShaderIrOperImmf Immf: return OperType.F32;
  791. case ShaderIrOperPred Pred: return OperType.Bool;
  792. case ShaderIrOp Op:
  793. if (Op.Inst > ShaderIrInst.B_Start &&
  794. Op.Inst < ShaderIrInst.B_End)
  795. {
  796. return OperType.Bool;
  797. }
  798. else if (Op.Inst > ShaderIrInst.F_Start &&
  799. Op.Inst < ShaderIrInst.F_End)
  800. {
  801. return OperType.F32;
  802. }
  803. else if (Op.Inst > ShaderIrInst.I_Start &&
  804. Op.Inst < ShaderIrInst.I_End)
  805. {
  806. return OperType.I32;
  807. }
  808. break;
  809. }
  810. throw new ArgumentException(nameof(Node));
  811. }
  812. }
  813. }