GlslDecompiler.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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 const int MaxVertexInput = 3;
  20. private GlslDecl Decl;
  21. private ShaderHeader Header, HeaderB;
  22. private ShaderIrBlock[] Blocks, BlocksB;
  23. private StringBuilder SB;
  24. public GlslDecompiler()
  25. {
  26. InstsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  27. {
  28. { ShaderIrInst.Abs, GetAbsExpr },
  29. { ShaderIrInst.Add, GetAddExpr },
  30. { ShaderIrInst.And, GetAndExpr },
  31. { ShaderIrInst.Asr, GetAsrExpr },
  32. { ShaderIrInst.Band, GetBandExpr },
  33. { ShaderIrInst.Bnot, GetBnotExpr },
  34. { ShaderIrInst.Bor, GetBorExpr },
  35. { ShaderIrInst.Bxor, GetBxorExpr },
  36. { ShaderIrInst.Ceil, GetCeilExpr },
  37. { ShaderIrInst.Ceq, GetCeqExpr },
  38. { ShaderIrInst.Cge, GetCgeExpr },
  39. { ShaderIrInst.Cgt, GetCgtExpr },
  40. { ShaderIrInst.Clamps, GetClampsExpr },
  41. { ShaderIrInst.Clampu, GetClampuExpr },
  42. { ShaderIrInst.Cle, GetCleExpr },
  43. { ShaderIrInst.Clt, GetCltExpr },
  44. { ShaderIrInst.Cne, GetCneExpr },
  45. { ShaderIrInst.Cut, GetCutExpr },
  46. { ShaderIrInst.Exit, GetExitExpr },
  47. { ShaderIrInst.Fabs, GetAbsExpr },
  48. { ShaderIrInst.Fadd, GetAddExpr },
  49. { ShaderIrInst.Fceq, GetCeqExpr },
  50. { ShaderIrInst.Fcequ, GetCequExpr },
  51. { ShaderIrInst.Fcge, GetCgeExpr },
  52. { ShaderIrInst.Fcgeu, GetCgeuExpr },
  53. { ShaderIrInst.Fcgt, GetCgtExpr },
  54. { ShaderIrInst.Fcgtu, GetCgtuExpr },
  55. { ShaderIrInst.Fclamp, GetFclampExpr },
  56. { ShaderIrInst.Fcle, GetCleExpr },
  57. { ShaderIrInst.Fcleu, GetCleuExpr },
  58. { ShaderIrInst.Fclt, GetCltExpr },
  59. { ShaderIrInst.Fcltu, GetCltuExpr },
  60. { ShaderIrInst.Fcnan, GetCnanExpr },
  61. { ShaderIrInst.Fcne, GetCneExpr },
  62. { ShaderIrInst.Fcneu, GetCneuExpr },
  63. { ShaderIrInst.Fcnum, GetCnumExpr },
  64. { ShaderIrInst.Fcos, GetFcosExpr },
  65. { ShaderIrInst.Fex2, GetFex2Expr },
  66. { ShaderIrInst.Ffma, GetFfmaExpr },
  67. { ShaderIrInst.Flg2, GetFlg2Expr },
  68. { ShaderIrInst.Floor, GetFloorExpr },
  69. { ShaderIrInst.Fmax, GetMaxExpr },
  70. { ShaderIrInst.Fmin, GetMinExpr },
  71. { ShaderIrInst.Fmul, GetMulExpr },
  72. { ShaderIrInst.Fneg, GetNegExpr },
  73. { ShaderIrInst.Frcp, GetFrcpExpr },
  74. { ShaderIrInst.Frsq, GetFrsqExpr },
  75. { ShaderIrInst.Fsin, GetFsinExpr },
  76. { ShaderIrInst.Fsqrt, GetFsqrtExpr },
  77. { ShaderIrInst.Ftos, GetFtosExpr },
  78. { ShaderIrInst.Ftou, GetFtouExpr },
  79. { ShaderIrInst.Ipa, GetIpaExpr },
  80. { ShaderIrInst.Kil, GetKilExpr },
  81. { ShaderIrInst.Lsl, GetLslExpr },
  82. { ShaderIrInst.Lsr, GetLsrExpr },
  83. { ShaderIrInst.Max, GetMaxExpr },
  84. { ShaderIrInst.Min, GetMinExpr },
  85. { ShaderIrInst.Mul, GetMulExpr },
  86. { ShaderIrInst.Neg, GetNegExpr },
  87. { ShaderIrInst.Not, GetNotExpr },
  88. { ShaderIrInst.Or, GetOrExpr },
  89. { ShaderIrInst.Stof, GetStofExpr },
  90. { ShaderIrInst.Sub, GetSubExpr },
  91. { ShaderIrInst.Texb, GetTexbExpr },
  92. { ShaderIrInst.Texq, GetTexqExpr },
  93. { ShaderIrInst.Texs, GetTexsExpr },
  94. { ShaderIrInst.Trunc, GetTruncExpr },
  95. { ShaderIrInst.Txlf, GetTxlfExpr },
  96. { ShaderIrInst.Utof, GetUtofExpr },
  97. { ShaderIrInst.Xor, GetXorExpr }
  98. };
  99. }
  100. public GlslProgram Decompile(
  101. IGalMemory Memory,
  102. long VpAPosition,
  103. long VpBPosition,
  104. GalShaderType ShaderType)
  105. {
  106. Header = new ShaderHeader(Memory, VpAPosition);
  107. HeaderB = new ShaderHeader(Memory, VpBPosition);
  108. Blocks = ShaderDecoder.Decode(Memory, VpAPosition);
  109. BlocksB = ShaderDecoder.Decode(Memory, VpBPosition);
  110. GlslDecl DeclVpA = new GlslDecl(Blocks, ShaderType, Header);
  111. GlslDecl DeclVpB = new GlslDecl(BlocksB, ShaderType, HeaderB);
  112. Decl = GlslDecl.Merge(DeclVpA, DeclVpB);
  113. return Decompile();
  114. }
  115. public GlslProgram Decompile(IGalMemory Memory, long Position, GalShaderType ShaderType)
  116. {
  117. Header = new ShaderHeader(Memory, Position);
  118. HeaderB = null;
  119. Blocks = ShaderDecoder.Decode(Memory, Position);
  120. BlocksB = null;
  121. Decl = new GlslDecl(Blocks, ShaderType, Header);
  122. return Decompile();
  123. }
  124. private GlslProgram Decompile()
  125. {
  126. SB = new StringBuilder();
  127. SB.AppendLine("#version 410 core");
  128. PrintDeclHeader();
  129. PrintDeclTextures();
  130. PrintDeclUniforms();
  131. PrintDeclAttributes();
  132. PrintDeclInAttributes();
  133. PrintDeclOutAttributes();
  134. PrintDeclGprs();
  135. PrintDeclPreds();
  136. if (BlocksB != null)
  137. {
  138. PrintBlockScope(Blocks[0], null, null, "void " + GlslDecl.ProgramAName + "()", IdentationStr);
  139. SB.AppendLine();
  140. PrintBlockScope(BlocksB[0], null, null, "void " + GlslDecl.ProgramBName + "()", IdentationStr);
  141. }
  142. else
  143. {
  144. PrintBlockScope(Blocks[0], null, null, "void " + GlslDecl.ProgramName + "()", IdentationStr);
  145. }
  146. SB.AppendLine();
  147. PrintMain();
  148. string GlslCode = SB.ToString();
  149. List<ShaderDeclInfo> TextureInfo = new List<ShaderDeclInfo>();
  150. TextureInfo.AddRange(Decl.Textures.Values);
  151. TextureInfo.AddRange(IterateCbTextures());
  152. return new GlslProgram(GlslCode, TextureInfo, Decl.Uniforms.Values);
  153. }
  154. private void PrintDeclHeader()
  155. {
  156. if (Decl.ShaderType == GalShaderType.Geometry)
  157. {
  158. int MaxVertices = Header.MaxOutputVertexCount;
  159. string OutputTopology;
  160. switch (Header.OutputTopology)
  161. {
  162. case ShaderHeader.PointList: OutputTopology = "points"; break;
  163. case ShaderHeader.LineStrip: OutputTopology = "line_strip"; break;
  164. case ShaderHeader.TriangleStrip: OutputTopology = "triangle_strip"; break;
  165. default: throw new InvalidOperationException();
  166. }
  167. SB.AppendLine("#extension GL_ARB_enhanced_layouts : require");
  168. SB.AppendLine();
  169. SB.AppendLine("// Stubbed. Maxwell geometry shaders don't inform input geometry type");
  170. SB.AppendLine("layout(triangles) in;" + Environment.NewLine);
  171. SB.AppendLine($"layout({OutputTopology}, max_vertices = {MaxVertices}) out;");
  172. SB.AppendLine();
  173. }
  174. }
  175. private void PrintDeclTextures()
  176. {
  177. foreach (ShaderDeclInfo DeclInfo in IterateCbTextures())
  178. {
  179. SB.AppendLine("uniform sampler2D " + DeclInfo.Name + ";");
  180. }
  181. PrintDecls(Decl.Textures, "uniform sampler2D");
  182. }
  183. private IEnumerable<ShaderDeclInfo> IterateCbTextures()
  184. {
  185. HashSet<string> Names = new HashSet<string>();
  186. foreach (ShaderDeclInfo DeclInfo in Decl.CbTextures.Values.OrderBy(DeclKeySelector))
  187. {
  188. if (Names.Add(DeclInfo.Name))
  189. {
  190. yield return DeclInfo;
  191. }
  192. }
  193. }
  194. private void PrintDeclUniforms()
  195. {
  196. if (Decl.ShaderType == GalShaderType.Vertex)
  197. {
  198. SB.AppendLine("layout (std140) uniform " + GlslDecl.ExtraUniformBlockName + "{");
  199. SB.AppendLine(IdentationStr + "vec2 " + GlslDecl.FlipUniformName + ";");
  200. SB.AppendLine("};");
  201. }
  202. SB.AppendLine();
  203. foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector))
  204. {
  205. SB.AppendLine($"layout (std140) uniform {DeclInfo.Name} {{");
  206. SB.AppendLine($"{IdentationStr}vec4 {DeclInfo.Name}_data[{GlslDecl.MaxUboSize}];");
  207. SB.AppendLine("};");
  208. }
  209. if (Decl.Uniforms.Count > 0)
  210. {
  211. SB.AppendLine();
  212. }
  213. }
  214. private void PrintDeclAttributes()
  215. {
  216. string GeometryArray = (Decl.ShaderType == GalShaderType.Geometry) ? "[" + MaxVertexInput + "]" : "";
  217. PrintDecls(Decl.Attributes, Suffix: GeometryArray);
  218. }
  219. private void PrintDeclInAttributes()
  220. {
  221. if (Decl.ShaderType == GalShaderType.Fragment)
  222. {
  223. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";");
  224. }
  225. if (Decl.ShaderType == GalShaderType.Geometry)
  226. {
  227. if (Decl.InAttributes.Count > 0)
  228. {
  229. SB.AppendLine("in Vertex {");
  230. foreach (ShaderDeclInfo DeclInfo in Decl.InAttributes.Values.OrderBy(DeclKeySelector))
  231. {
  232. if (DeclInfo.Index >= 0)
  233. {
  234. SB.AppendLine(IdentationStr + "layout (location = " + DeclInfo.Index + ") vec4 " + DeclInfo.Name + "; ");
  235. }
  236. }
  237. SB.AppendLine("} block_in[];" + Environment.NewLine);
  238. }
  239. }
  240. else
  241. {
  242. PrintDeclAttributes(Decl.InAttributes.Values, "in");
  243. }
  244. }
  245. private void PrintDeclOutAttributes()
  246. {
  247. if (Decl.ShaderType == GalShaderType.Fragment)
  248. {
  249. for (int Attachment = 0; Attachment < 8; Attachment++)
  250. {
  251. if (Header.OmapTargets[Attachment].Enabled)
  252. {
  253. SB.AppendLine("layout (location = " + Attachment + ") out vec4 " + GlslDecl.FragmentOutputName + Attachment + ";");
  254. }
  255. }
  256. }
  257. else
  258. {
  259. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") out vec4 " + GlslDecl.PositionOutAttrName + ";");
  260. }
  261. PrintDeclAttributes(Decl.OutAttributes.Values, "out");
  262. }
  263. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> Decls, string InOut)
  264. {
  265. int Count = 0;
  266. foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector))
  267. {
  268. if (DeclInfo.Index >= 0)
  269. {
  270. SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " vec4 " + DeclInfo.Name + ";");
  271. Count++;
  272. }
  273. }
  274. if (Count > 0)
  275. {
  276. SB.AppendLine();
  277. }
  278. }
  279. private void PrintDeclGprs()
  280. {
  281. PrintDecls(Decl.Gprs);
  282. }
  283. private void PrintDeclPreds()
  284. {
  285. PrintDecls(Decl.Preds, "bool");
  286. }
  287. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, string CustomType = null, string Suffix = "")
  288. {
  289. foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector))
  290. {
  291. string Name;
  292. if (CustomType != null)
  293. {
  294. Name = CustomType + " " + DeclInfo.Name + Suffix + ";";
  295. }
  296. else if (DeclInfo.Name.Contains(GlslDecl.FragmentOutputName))
  297. {
  298. Name = "layout (location = " + DeclInfo.Index / 4 + ") out vec4 " + DeclInfo.Name + Suffix + ";";
  299. }
  300. else
  301. {
  302. Name = GetDecl(DeclInfo) + Suffix + ";";
  303. }
  304. SB.AppendLine(Name);
  305. }
  306. if (Dict.Count > 0)
  307. {
  308. SB.AppendLine();
  309. }
  310. }
  311. private int DeclKeySelector(ShaderDeclInfo DeclInfo)
  312. {
  313. return DeclInfo.Cbuf << 24 | DeclInfo.Index;
  314. }
  315. private string GetDecl(ShaderDeclInfo DeclInfo)
  316. {
  317. if (DeclInfo.Size == 4)
  318. {
  319. return "vec4 " + DeclInfo.Name;
  320. }
  321. else
  322. {
  323. return "float " + DeclInfo.Name;
  324. }
  325. }
  326. private void PrintMain()
  327. {
  328. SB.AppendLine("void main() {");
  329. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.InAttributes)
  330. {
  331. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  332. {
  333. continue;
  334. }
  335. ShaderDeclInfo DeclInfo = KV.Value;
  336. if (Decl.ShaderType == GalShaderType.Geometry)
  337. {
  338. for (int Vertex = 0; Vertex < MaxVertexInput; Vertex++)
  339. {
  340. string Dst = Attr.Name + "[" + Vertex + "]";
  341. string Src = "block_in[" + Vertex + "]." + DeclInfo.Name;
  342. SB.AppendLine(IdentationStr + Dst + " = " + Src + ";");
  343. }
  344. }
  345. else
  346. {
  347. SB.AppendLine(IdentationStr + Attr.Name + " = " + DeclInfo.Name + ";");
  348. }
  349. }
  350. if (BlocksB != null)
  351. {
  352. SB.AppendLine(IdentationStr + GlslDecl.ProgramAName + "();");
  353. SB.AppendLine(IdentationStr + GlslDecl.ProgramBName + "();");
  354. }
  355. else
  356. {
  357. SB.AppendLine(IdentationStr + GlslDecl.ProgramName + "();");
  358. }
  359. if (Decl.ShaderType != GalShaderType.Geometry)
  360. {
  361. PrintAttrToOutput();
  362. }
  363. if (Decl.ShaderType == GalShaderType.Fragment)
  364. {
  365. if (Header.OmapDepth)
  366. {
  367. SB.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(Header.DepthRegister) + ";");
  368. }
  369. int GprIndex = 0;
  370. for (int Attachment = 0; Attachment < 8; Attachment++)
  371. {
  372. string Output = GlslDecl.FragmentOutputName + Attachment;
  373. OmapTarget Target = Header.OmapTargets[Attachment];
  374. for (int Component = 0; Component < 4; Component++)
  375. {
  376. if (Target.ComponentEnabled(Component))
  377. {
  378. SB.AppendLine(IdentationStr + Output + "[" + Component + "] = " + GlslDecl.GetGprName(GprIndex) + ";");
  379. GprIndex++;
  380. }
  381. }
  382. }
  383. }
  384. SB.AppendLine("}");
  385. }
  386. private void PrintAttrToOutput(string Identation = IdentationStr)
  387. {
  388. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.OutAttributes)
  389. {
  390. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  391. {
  392. continue;
  393. }
  394. ShaderDeclInfo DeclInfo = KV.Value;
  395. string Name = Attr.Name;
  396. if (Decl.ShaderType == GalShaderType.Geometry)
  397. {
  398. Name += "[0]";
  399. }
  400. SB.AppendLine(Identation + DeclInfo.Name + " = " + Name + ";");
  401. }
  402. if (Decl.ShaderType == GalShaderType.Vertex)
  403. {
  404. SB.AppendLine(Identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";");
  405. }
  406. if (Decl.ShaderType != GalShaderType.Fragment)
  407. {
  408. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  409. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + ".w = 1;");
  410. }
  411. }
  412. private void PrintBlockScope(
  413. ShaderIrBlock Block,
  414. ShaderIrBlock EndBlock,
  415. ShaderIrBlock LoopBlock,
  416. string ScopeName,
  417. string Identation,
  418. bool IsDoWhile = false)
  419. {
  420. string UpIdent = Identation.Substring(0, Identation.Length - IdentationStr.Length);
  421. if (IsDoWhile)
  422. {
  423. SB.AppendLine(UpIdent + "do {");
  424. }
  425. else
  426. {
  427. SB.AppendLine(UpIdent + ScopeName + " {");
  428. }
  429. while (Block != null && Block != EndBlock)
  430. {
  431. ShaderIrNode[] Nodes = Block.GetNodes();
  432. Block = PrintNodes(Block, EndBlock, LoopBlock, Identation, Nodes);
  433. }
  434. if (IsDoWhile)
  435. {
  436. SB.AppendLine(UpIdent + "} " + ScopeName + ";");
  437. }
  438. else
  439. {
  440. SB.AppendLine(UpIdent + "}");
  441. }
  442. }
  443. private ShaderIrBlock PrintNodes(
  444. ShaderIrBlock Block,
  445. ShaderIrBlock EndBlock,
  446. ShaderIrBlock LoopBlock,
  447. string Identation,
  448. params ShaderIrNode[] Nodes)
  449. {
  450. /*
  451. * Notes about control flow and if-else/loop generation:
  452. * The code assumes that the program has sane control flow,
  453. * that is, there's no jumps to a location after another jump or
  454. * jump target (except for the end of an if-else block), and backwards
  455. * jumps to a location before the last loop dominator.
  456. * Such cases needs to be transformed on a step before the GLSL code
  457. * generation to ensure that we have sane graphs to work with.
  458. * TODO: Such transformation is not yet implemented.
  459. */
  460. string NewIdent = Identation + IdentationStr;
  461. ShaderIrBlock LoopTail = GetLoopTailBlock(Block);
  462. if (LoopTail != null && LoopBlock != Block)
  463. {
  464. //Shoock! kuma shock! We have a loop here!
  465. //The entire sequence needs to be inside a do-while block.
  466. ShaderIrBlock LoopEnd = GetDownBlock(LoopTail);
  467. PrintBlockScope(Block, LoopEnd, Block, "while (false)", NewIdent, IsDoWhile: true);
  468. return LoopEnd;
  469. }
  470. foreach (ShaderIrNode Node in Nodes)
  471. {
  472. if (Node is ShaderIrCond Cond)
  473. {
  474. string IfExpr = GetSrcExpr(Cond.Pred, true);
  475. if (Cond.Not)
  476. {
  477. IfExpr = "!(" + IfExpr + ")";
  478. }
  479. if (Cond.Child is ShaderIrOp Op && Op.Inst == ShaderIrInst.Bra)
  480. {
  481. //Branch is a loop branch and would result in infinite recursion.
  482. if (Block.Branch.Position <= Block.Position)
  483. {
  484. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  485. SB.AppendLine(Identation + IdentationStr + "continue;");
  486. SB.AppendLine(Identation + "}");
  487. continue;
  488. }
  489. string SubScopeName = "if (!" + IfExpr + ")";
  490. PrintBlockScope(Block.Next, Block.Branch, LoopBlock, SubScopeName, NewIdent);
  491. ShaderIrBlock IfElseEnd = GetUpBlock(Block.Branch).Branch;
  492. if (IfElseEnd?.Position > Block.Branch.Position)
  493. {
  494. PrintBlockScope(Block.Branch, IfElseEnd, LoopBlock, "else", NewIdent);
  495. return IfElseEnd;
  496. }
  497. return Block.Branch;
  498. }
  499. else
  500. {
  501. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  502. PrintNodes(Block, EndBlock, LoopBlock, NewIdent, Cond.Child);
  503. SB.AppendLine(Identation + "}");
  504. }
  505. }
  506. else if (Node is ShaderIrAsg Asg)
  507. {
  508. if (IsValidOutOper(Asg.Dst))
  509. {
  510. string Expr = GetSrcExpr(Asg.Src, true);
  511. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  512. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  513. }
  514. }
  515. else if (Node is ShaderIrOp Op)
  516. {
  517. if (Op.Inst == ShaderIrInst.Bra)
  518. {
  519. if (Block.Branch.Position <= Block.Position)
  520. {
  521. SB.AppendLine(Identation + "continue;");
  522. }
  523. }
  524. else if (Op.Inst == ShaderIrInst.Emit)
  525. {
  526. PrintAttrToOutput(Identation);
  527. SB.AppendLine(Identation + "EmitVertex();");
  528. }
  529. else
  530. {
  531. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  532. }
  533. }
  534. else if (Node is ShaderIrCmnt Cmnt)
  535. {
  536. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  537. }
  538. else
  539. {
  540. throw new InvalidOperationException();
  541. }
  542. }
  543. return Block.Next;
  544. }
  545. private ShaderIrBlock GetUpBlock(ShaderIrBlock Block)
  546. {
  547. return Blocks.FirstOrDefault(x => x.EndPosition == Block.Position);
  548. }
  549. private ShaderIrBlock GetDownBlock(ShaderIrBlock Block)
  550. {
  551. return Blocks.FirstOrDefault(x => x.Position == Block.EndPosition);
  552. }
  553. private ShaderIrBlock GetLoopTailBlock(ShaderIrBlock LoopHead)
  554. {
  555. ShaderIrBlock Tail = null;
  556. foreach (ShaderIrBlock Block in LoopHead.Sources)
  557. {
  558. if (Block.Position >= LoopHead.Position)
  559. {
  560. if (Tail == null || Tail.Position < Block.Position)
  561. {
  562. Tail = Block;
  563. }
  564. }
  565. }
  566. return Tail;
  567. }
  568. private bool IsValidOutOper(ShaderIrNode Node)
  569. {
  570. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  571. {
  572. return false;
  573. }
  574. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  575. {
  576. return false;
  577. }
  578. return true;
  579. }
  580. private string GetDstOperName(ShaderIrNode Node)
  581. {
  582. if (Node is ShaderIrOperAbuf Abuf)
  583. {
  584. return GetOutAbufName(Abuf);
  585. }
  586. else if (Node is ShaderIrOperGpr Gpr)
  587. {
  588. return GetName(Gpr);
  589. }
  590. else if (Node is ShaderIrOperPred Pred)
  591. {
  592. return GetName(Pred);
  593. }
  594. throw new ArgumentException(nameof(Node));
  595. }
  596. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  597. {
  598. switch (Node)
  599. {
  600. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  601. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  602. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  603. case ShaderIrOperImm Imm: return GetValue(Imm);
  604. case ShaderIrOperImmf Immf: return GetValue(Immf);
  605. case ShaderIrOperPred Pred: return GetName (Pred);
  606. case ShaderIrOp Op:
  607. string Expr;
  608. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  609. {
  610. Expr = GetExpr(Op);
  611. }
  612. else
  613. {
  614. throw new NotImplementedException(Op.Inst.ToString());
  615. }
  616. if (!Entry && NeedsParentheses(Op))
  617. {
  618. Expr = "(" + Expr + ")";
  619. }
  620. return Expr;
  621. default: throw new ArgumentException(nameof(Node));
  622. }
  623. }
  624. private static bool NeedsParentheses(ShaderIrOp Op)
  625. {
  626. switch (Op.Inst)
  627. {
  628. case ShaderIrInst.Ipa:
  629. case ShaderIrInst.Texq:
  630. case ShaderIrInst.Texs:
  631. case ShaderIrInst.Txlf:
  632. return false;
  633. }
  634. return true;
  635. }
  636. private string GetName(ShaderIrOperCbuf Cbuf)
  637. {
  638. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  639. {
  640. throw new InvalidOperationException();
  641. }
  642. if (Cbuf.Offs != null)
  643. {
  644. string Offset = "floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ")";
  645. string Index = "(" + Cbuf.Pos * 4 + " + " + Offset + ")";
  646. return $"{DeclInfo.Name}_data[{Index} / 16][({Index} / 4) % 4]";
  647. }
  648. else
  649. {
  650. return $"{DeclInfo.Name}_data[{Cbuf.Pos / 4}][{Cbuf.Pos % 4}]";
  651. }
  652. }
  653. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  654. {
  655. if (Decl.ShaderType == GalShaderType.Geometry)
  656. {
  657. switch (Abuf.Offs)
  658. {
  659. case GlslDecl.LayerAttr: return "gl_Layer";
  660. }
  661. }
  662. return GetAttrTempName(Abuf);
  663. }
  664. private string GetName(ShaderIrOperAbuf Abuf)
  665. {
  666. //Handle special scalar read-only attributes here.
  667. if (Decl.ShaderType == GalShaderType.Vertex)
  668. {
  669. switch (Abuf.Offs)
  670. {
  671. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  672. case GlslDecl.InstanceIdAttr: return "gl_InstanceID";
  673. }
  674. }
  675. else if (Decl.ShaderType == GalShaderType.TessEvaluation)
  676. {
  677. switch (Abuf.Offs)
  678. {
  679. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  680. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  681. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  682. }
  683. }
  684. else if (Decl.ShaderType == GalShaderType.Fragment)
  685. {
  686. switch (Abuf.Offs)
  687. {
  688. case GlslDecl.PointCoordAttrX: return "gl_PointCoord.x";
  689. case GlslDecl.PointCoordAttrY: return "gl_PointCoord.y";
  690. //Note: It's a guess that Maxwell's face is 1 when gl_FrontFacing == true
  691. case GlslDecl.FaceAttr: return "(gl_FrontFacing ? 1 : 0)";
  692. }
  693. }
  694. return GetAttrTempName(Abuf);
  695. }
  696. private string GetAttrTempName(ShaderIrOperAbuf Abuf)
  697. {
  698. int Index = Abuf.Offs >> 4;
  699. int Elem = (Abuf.Offs >> 2) & 3;
  700. string Swizzle = "." + GetAttrSwizzle(Elem);
  701. if (!Decl.Attributes.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  702. {
  703. //Handle special vec4 attributes here
  704. //(for example, index 7 is always gl_Position).
  705. if (Index == GlslDecl.GlPositionVec4Index)
  706. {
  707. string Name =
  708. Decl.ShaderType != GalShaderType.Vertex &&
  709. Decl.ShaderType != GalShaderType.Geometry ? GlslDecl.PositionOutAttrName : "gl_Position";
  710. return Name + Swizzle;
  711. }
  712. else if (Abuf.Offs == GlslDecl.PointSizeAttr)
  713. {
  714. return "gl_PointSize";
  715. }
  716. }
  717. if (DeclInfo.Index >= 16)
  718. {
  719. throw new InvalidOperationException($"Shader attribute offset {Abuf.Offs} is invalid.");
  720. }
  721. if (Decl.ShaderType == GalShaderType.Geometry)
  722. {
  723. string Vertex = "floatBitsToInt(" + GetSrcExpr(Abuf.Vertex) + ")";
  724. return DeclInfo.Name + "[" + Vertex + "]" + Swizzle;
  725. }
  726. else
  727. {
  728. return DeclInfo.Name + Swizzle;
  729. }
  730. }
  731. private string GetName(ShaderIrOperGpr Gpr)
  732. {
  733. return Gpr.IsConst ? "0" : GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  734. }
  735. private string GetValue(ShaderIrOperImm Imm)
  736. {
  737. //Only use hex is the value is too big and would likely be hard to read as int.
  738. if (Imm.Value > 0xfff ||
  739. Imm.Value < -0xfff)
  740. {
  741. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  742. }
  743. else
  744. {
  745. return GetIntConst(Imm.Value);
  746. }
  747. }
  748. private string GetValue(ShaderIrOperImmf Immf)
  749. {
  750. return GetFloatConst(Immf.Value);
  751. }
  752. private string GetName(ShaderIrOperPred Pred)
  753. {
  754. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  755. }
  756. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  757. {
  758. int VecIndex = Index & ~3;
  759. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  760. {
  761. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  762. {
  763. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  764. }
  765. }
  766. if (!Dict.TryGetValue(Index, out DeclInfo))
  767. {
  768. throw new InvalidOperationException();
  769. }
  770. return DeclInfo.Name;
  771. }
  772. private string GetAttrSwizzle(int Elem)
  773. {
  774. return "xyzw".Substring(Elem, 1);
  775. }
  776. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  777. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  778. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  779. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  780. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  781. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  782. private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||");
  783. private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^");
  784. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  785. private string GetClampsExpr(ShaderIrOp Op)
  786. {
  787. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  788. GetOperExpr(Op, Op.OperandB) + ", " +
  789. GetOperExpr(Op, Op.OperandC) + ")";
  790. }
  791. private string GetClampuExpr(ShaderIrOp Op)
  792. {
  793. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  794. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  795. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  796. }
  797. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  798. private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "==");
  799. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  800. private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">=");
  801. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  802. private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">");
  803. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  804. private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<=");
  805. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  806. private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<");
  807. private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan");
  808. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  809. private string GetCutExpr(ShaderIrOp Op) => "EndPrimitive()";
  810. private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!=");
  811. private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan");
  812. private string GetExitExpr(ShaderIrOp Op) => "return";
  813. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  814. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  815. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  816. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  817. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  818. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  819. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  820. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  821. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  822. private string GetFsqrtExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sqrt");
  823. private string GetFtosExpr(ShaderIrOp Op)
  824. {
  825. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  826. }
  827. private string GetFtouExpr(ShaderIrOp Op)
  828. {
  829. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  830. }
  831. private string GetIpaExpr(ShaderIrOp Op) => GetSrcExpr(Op.OperandA);
  832. private string GetKilExpr(ShaderIrOp Op) => "discard";
  833. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  834. private string GetLsrExpr(ShaderIrOp Op)
  835. {
  836. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  837. GetOperExpr(Op, Op.OperandB) + ")";
  838. }
  839. private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  840. private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  841. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  842. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  843. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  844. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  845. private string GetStofExpr(ShaderIrOp Op)
  846. {
  847. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  848. }
  849. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  850. private string GetTexbExpr(ShaderIrOp Op)
  851. {
  852. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  853. if (!Decl.CbTextures.TryGetValue(Op, out ShaderDeclInfo DeclInfo))
  854. {
  855. throw new InvalidOperationException();
  856. }
  857. string Coords = GetTexSamplerCoords(Op);
  858. string Ch = "rgba".Substring(Meta.Elem, 1);
  859. return "texture(" + DeclInfo.Name + ", " + Coords + ")." + Ch;
  860. }
  861. private string GetTexqExpr(ShaderIrOp Op)
  862. {
  863. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  864. string Ch = "xyzw".Substring(Meta.Elem, 1);
  865. if (Meta.Info == ShaderTexqInfo.Dimension)
  866. {
  867. string Sampler = GetTexSamplerName(Op);
  868. string Lod = GetOperExpr(Op, Op.OperandA); //???
  869. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  870. }
  871. else
  872. {
  873. throw new NotImplementedException(Meta.Info.ToString());
  874. }
  875. }
  876. private string GetTexsExpr(ShaderIrOp Op)
  877. {
  878. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  879. string Sampler = GetTexSamplerName(Op);
  880. string Coords = GetTexSamplerCoords(Op);
  881. string Ch = "rgba".Substring(Meta.Elem, 1);
  882. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  883. }
  884. private string GetTxlfExpr(ShaderIrOp Op)
  885. {
  886. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  887. string Sampler = GetTexSamplerName(Op);
  888. string Coords = GetITexSamplerCoords(Op);
  889. string Ch = "rgba".Substring(Meta.Elem, 1);
  890. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  891. }
  892. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  893. private string GetUtofExpr(ShaderIrOp Op)
  894. {
  895. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  896. }
  897. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  898. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  899. {
  900. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  901. }
  902. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  903. {
  904. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  905. GetOperExpr(Op, Op.OperandB) + ")";
  906. }
  907. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  908. {
  909. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  910. GetOperExpr(Op, Op.OperandB) + ", " +
  911. GetOperExpr(Op, Op.OperandC) + ")";
  912. }
  913. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  914. {
  915. return Opr + GetOperExpr(Op, Op.OperandA);
  916. }
  917. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  918. {
  919. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  920. GetOperExpr(Op, Op.OperandB);
  921. }
  922. private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr)
  923. {
  924. string A = GetOperExpr(Op, Op.OperandA);
  925. string B = GetOperExpr(Op, Op.OperandB);
  926. string NaNCheck =
  927. " || isnan(" + A + ")" +
  928. " || isnan(" + B + ")";
  929. return A + " " + Opr + " " + B + NaNCheck;
  930. }
  931. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  932. {
  933. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  934. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  935. GetOperExpr(Op, Op.OperandC);
  936. }
  937. private string GetTexSamplerName(ShaderIrOp Op)
  938. {
  939. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  940. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  941. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  942. {
  943. throw new InvalidOperationException();
  944. }
  945. return DeclInfo.Name;
  946. }
  947. private string GetTexSamplerCoords(ShaderIrOp Op)
  948. {
  949. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  950. GetOperExpr(Op, Op.OperandB) + ")";
  951. }
  952. private string GetITexSamplerCoords(ShaderIrOp Op)
  953. {
  954. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  955. GetOperExpr(Op, Op.OperandB) + ")";
  956. }
  957. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  958. {
  959. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  960. }
  961. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  962. {
  963. //Note: The "DstType" (of the cast) is the type that the operation
  964. //uses on the source operands, while the "SrcType" is the destination
  965. //type of the operand result (if it is a operation) or just the type
  966. //of the variable for registers/uniforms/attributes.
  967. OperType DstType = GetSrcNodeType(Dst);
  968. OperType SrcType = GetDstNodeType(Src);
  969. if (DstType != SrcType)
  970. {
  971. //Check for invalid casts
  972. //(like bool to int/float and others).
  973. if (SrcType != OperType.F32 &&
  974. SrcType != OperType.I32)
  975. {
  976. throw new InvalidOperationException();
  977. }
  978. switch (Src)
  979. {
  980. case ShaderIrOperGpr Gpr:
  981. {
  982. //When the Gpr is ZR, just return the 0 value directly,
  983. //since the float encoding for 0 is 0.
  984. if (Gpr.IsConst)
  985. {
  986. return "0";
  987. }
  988. break;
  989. }
  990. case ShaderIrOperImm Imm:
  991. {
  992. //For integer immediates being used as float,
  993. //it's better (for readability) to just return the float value.
  994. if (DstType == OperType.F32)
  995. {
  996. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  997. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  998. {
  999. return GetFloatConst(Value);
  1000. }
  1001. }
  1002. break;
  1003. }
  1004. }
  1005. switch (DstType)
  1006. {
  1007. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  1008. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  1009. }
  1010. }
  1011. return Expr;
  1012. }
  1013. private static string GetIntConst(int Value)
  1014. {
  1015. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  1016. return Value < 0 ? "(" + Expr + ")" : Expr;
  1017. }
  1018. private static string GetFloatConst(float Value)
  1019. {
  1020. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  1021. return Value < 0 ? "(" + Expr + ")" : Expr;
  1022. }
  1023. private static OperType GetDstNodeType(ShaderIrNode Node)
  1024. {
  1025. //Special case instructions with the result type different
  1026. //from the input types (like integer <-> float conversion) here.
  1027. if (Node is ShaderIrOp Op)
  1028. {
  1029. switch (Op.Inst)
  1030. {
  1031. case ShaderIrInst.Stof:
  1032. case ShaderIrInst.Txlf:
  1033. case ShaderIrInst.Utof:
  1034. return OperType.F32;
  1035. case ShaderIrInst.Ftos:
  1036. case ShaderIrInst.Ftou:
  1037. return OperType.I32;
  1038. }
  1039. }
  1040. return GetSrcNodeType(Node);
  1041. }
  1042. private static OperType GetSrcNodeType(ShaderIrNode Node)
  1043. {
  1044. switch (Node)
  1045. {
  1046. case ShaderIrOperAbuf Abuf:
  1047. return Abuf.Offs == GlslDecl.LayerAttr ||
  1048. Abuf.Offs == GlslDecl.InstanceIdAttr ||
  1049. Abuf.Offs == GlslDecl.VertexIdAttr ||
  1050. Abuf.Offs == GlslDecl.FaceAttr
  1051. ? OperType.I32
  1052. : OperType.F32;
  1053. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  1054. case ShaderIrOperGpr Gpr: return OperType.F32;
  1055. case ShaderIrOperImm Imm: return OperType.I32;
  1056. case ShaderIrOperImmf Immf: return OperType.F32;
  1057. case ShaderIrOperPred Pred: return OperType.Bool;
  1058. case ShaderIrOp Op:
  1059. if (Op.Inst > ShaderIrInst.B_Start &&
  1060. Op.Inst < ShaderIrInst.B_End)
  1061. {
  1062. return OperType.Bool;
  1063. }
  1064. else if (Op.Inst > ShaderIrInst.F_Start &&
  1065. Op.Inst < ShaderIrInst.F_End)
  1066. {
  1067. return OperType.F32;
  1068. }
  1069. else if (Op.Inst > ShaderIrInst.I_Start &&
  1070. Op.Inst < ShaderIrInst.I_End)
  1071. {
  1072. return OperType.I32;
  1073. }
  1074. break;
  1075. }
  1076. throw new ArgumentException(nameof(Node));
  1077. }
  1078. }
  1079. }