Declarations.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  3. using Ryujinx.Graphics.Shader.StructuredIr;
  4. using Ryujinx.Graphics.Shader.Translation;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
  9. {
  10. static class Declarations
  11. {
  12. // At least 16 attributes are guaranteed by the spec.
  13. public const int MaxAttributes = 16;
  14. public static void Declare(CodeGenContext context, StructuredProgramInfo info)
  15. {
  16. context.AppendLine("#version 440 core");
  17. context.AppendLine("#extension GL_ARB_gpu_shader_int64 : enable");
  18. context.AppendLine("#extension GL_ARB_shader_ballot : enable");
  19. context.AppendLine("#extension GL_ARB_shader_group_vote : enable");
  20. context.AppendLine("#extension GL_EXT_shader_image_load_formatted : enable");
  21. if (context.Config.Stage == ShaderStage.Compute)
  22. {
  23. context.AppendLine("#extension GL_ARB_compute_shader : enable");
  24. }
  25. context.AppendLine("#pragma optionNV(fastmath off)");
  26. context.AppendLine();
  27. context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
  28. context.AppendLine();
  29. if (context.Config.Stage == ShaderStage.Geometry)
  30. {
  31. string inPrimitive = context.Config.GpuAccessor.QueryPrimitiveTopology().ToGlslString();
  32. context.AppendLine($"layout ({inPrimitive}) in;");
  33. string outPrimitive = context.Config.OutputTopology.ToGlslString();
  34. int maxOutputVertices = context.Config.MaxOutputVertices;
  35. context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
  36. context.AppendLine();
  37. }
  38. if (context.Config.Stage == ShaderStage.Compute)
  39. {
  40. int localMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeLocalMemorySize(), 4);
  41. if (localMemorySize != 0)
  42. {
  43. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  44. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  45. context.AppendLine();
  46. }
  47. int sharedMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeSharedMemorySize(), 4);
  48. if (sharedMemorySize != 0)
  49. {
  50. string sharedMemorySizeStr = NumberFormatter.FormatInt(sharedMemorySize);
  51. context.AppendLine($"shared uint {DefaultNames.SharedMemoryName}[{sharedMemorySizeStr}];");
  52. context.AppendLine();
  53. }
  54. }
  55. else if (context.Config.LocalMemorySize != 0)
  56. {
  57. int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
  58. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  59. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  60. context.AppendLine();
  61. }
  62. if (info.CBuffers.Count != 0)
  63. {
  64. DeclareUniforms(context, info);
  65. context.AppendLine();
  66. }
  67. if (info.SBuffers.Count != 0)
  68. {
  69. DeclareStorages(context, info);
  70. context.AppendLine();
  71. }
  72. if (info.Samplers.Count != 0)
  73. {
  74. DeclareSamplers(context, info);
  75. context.AppendLine();
  76. }
  77. if (info.Images.Count != 0)
  78. {
  79. DeclareImages(context, info);
  80. context.AppendLine();
  81. }
  82. if (context.Config.Stage != ShaderStage.Compute)
  83. {
  84. if (info.IAttributes.Count != 0)
  85. {
  86. DeclareInputAttributes(context, info);
  87. context.AppendLine();
  88. }
  89. if (info.OAttributes.Count != 0 || context.Config.Stage != ShaderStage.Fragment)
  90. {
  91. DeclareOutputAttributes(context, info);
  92. context.AppendLine();
  93. }
  94. }
  95. else
  96. {
  97. string localSizeX = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeX());
  98. string localSizeY = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeY());
  99. string localSizeZ = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeZ());
  100. context.AppendLine(
  101. "layout (" +
  102. $"local_size_x = {localSizeX}, " +
  103. $"local_size_y = {localSizeY}, " +
  104. $"local_size_z = {localSizeZ}) in;");
  105. context.AppendLine();
  106. }
  107. if (context.Config.Stage == ShaderStage.Fragment || context.Config.Stage == ShaderStage.Compute)
  108. {
  109. if (DeclareRenderScale(context))
  110. {
  111. context.AppendLine();
  112. }
  113. }
  114. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighS32) != 0)
  115. {
  116. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighS32.glsl");
  117. }
  118. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighU32) != 0)
  119. {
  120. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighU32.glsl");
  121. }
  122. if ((info.HelperFunctionsMask & HelperFunctionsMask.Shuffle) != 0)
  123. {
  124. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/Shuffle.glsl");
  125. }
  126. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleDown) != 0)
  127. {
  128. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleDown.glsl");
  129. }
  130. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleUp) != 0)
  131. {
  132. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleUp.glsl");
  133. }
  134. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleXor) != 0)
  135. {
  136. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleXor.glsl");
  137. }
  138. if ((info.HelperFunctionsMask & HelperFunctionsMask.SwizzleAdd) != 0)
  139. {
  140. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/SwizzleAdd.glsl");
  141. }
  142. }
  143. public static void DeclareLocals(CodeGenContext context, StructuredProgramInfo info)
  144. {
  145. foreach (AstOperand decl in info.Locals)
  146. {
  147. string name = context.OperandManager.DeclareLocal(decl);
  148. context.AppendLine(GetVarTypeName(decl.VarType) + " " + name + ";");
  149. }
  150. }
  151. private static string GetVarTypeName(VariableType type)
  152. {
  153. switch (type)
  154. {
  155. case VariableType.Bool: return "bool";
  156. case VariableType.F32: return "precise float";
  157. case VariableType.F64: return "double";
  158. case VariableType.S32: return "int";
  159. case VariableType.U32: return "uint";
  160. }
  161. throw new ArgumentException($"Invalid variable type \"{type}\".");
  162. }
  163. private static void DeclareUniforms(CodeGenContext context, StructuredProgramInfo info)
  164. {
  165. foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
  166. {
  167. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  168. ubName += "_" + DefaultNames.UniformNamePrefix + cbufSlot;
  169. context.CBufferDescriptors.Add(new BufferDescriptor(ubName, cbufSlot));
  170. context.AppendLine("layout (std140) uniform " + ubName);
  171. context.EnterScope();
  172. string ubSize = "[" + NumberFormatter.FormatInt(Constants.ConstantBufferSize / 16) + "]";
  173. context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, cbufSlot) + ubSize + ";");
  174. context.LeaveScope(";");
  175. }
  176. }
  177. private static bool DeclareRenderScale(CodeGenContext context)
  178. {
  179. if ((context.Config.UsedFeatures & (FeatureFlags.FragCoordXY | FeatureFlags.IntegerSampling)) != 0)
  180. {
  181. string stage = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  182. int scaleElements = context.TextureDescriptors.Count;
  183. if (context.Config.Stage == ShaderStage.Fragment)
  184. {
  185. scaleElements++; // Also includes render target scale, for gl_FragCoord.
  186. }
  187. context.AppendLine($"uniform float {stage}_renderScale[{scaleElements}];");
  188. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.IntegerSampling))
  189. {
  190. context.AppendLine();
  191. AppendHelperFunction(context, $"Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/TexelFetchScale_{stage}.glsl");
  192. }
  193. return true;
  194. }
  195. return false;
  196. }
  197. private static void DeclareStorages(CodeGenContext context, StructuredProgramInfo info)
  198. {
  199. string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  200. sbName += "_" + DefaultNames.StorageNamePrefix;
  201. string blockName = $"{sbName}_{DefaultNames.BlockSuffix}";
  202. int maxSlot = 0;
  203. foreach (int sbufSlot in info.SBuffers)
  204. {
  205. context.SBufferDescriptors.Add(new BufferDescriptor($"{blockName}[{sbufSlot}]", sbufSlot));
  206. if (maxSlot < sbufSlot)
  207. {
  208. maxSlot = sbufSlot;
  209. }
  210. }
  211. context.AppendLine("layout (std430) buffer " + blockName);
  212. context.EnterScope();
  213. context.AppendLine("uint " + DefaultNames.DataName + "[];");
  214. string arraySize = NumberFormatter.FormatInt(maxSlot + 1);
  215. context.LeaveScope($" {sbName}[{arraySize}];");
  216. }
  217. private static void DeclareSamplers(CodeGenContext context, StructuredProgramInfo info)
  218. {
  219. Dictionary<string, AstTextureOperation> samplers = new Dictionary<string, AstTextureOperation>();
  220. // Texture instructions other than TextureSample (like TextureSize)
  221. // may have incomplete sampler type information. In those cases,
  222. // we prefer instead the more accurate information from the
  223. // TextureSample instruction, if both are available.
  224. foreach (AstTextureOperation texOp in info.Samplers.OrderBy(x => x.Handle * 2 + (x.Inst == Instruction.TextureSample ? 0 : 1)))
  225. {
  226. string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
  227. string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
  228. if (!samplers.TryAdd(samplerName, texOp))
  229. {
  230. continue;
  231. }
  232. string samplerTypeName = GetSamplerTypeName(texOp.Type);
  233. context.AppendLine("uniform " + samplerTypeName + " " + samplerName + ";");
  234. }
  235. foreach (KeyValuePair<string, AstTextureOperation> kv in samplers)
  236. {
  237. string samplerName = kv.Key;
  238. AstTextureOperation texOp = kv.Value;
  239. TextureDescriptor desc;
  240. if ((texOp.Flags & TextureFlags.Bindless) != 0)
  241. {
  242. AstOperand operand = texOp.GetSource(0) as AstOperand;
  243. desc = new TextureDescriptor(samplerName, texOp.Type, operand.CbufSlot, operand.CbufOffset);
  244. context.TextureDescriptors.Add(desc);
  245. }
  246. else if ((texOp.Type & SamplerType.Indexed) != 0)
  247. {
  248. for (int index = 0; index < texOp.ArraySize; index++)
  249. {
  250. string indexExpr = NumberFormatter.FormatInt(index);
  251. string indexedSamplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
  252. desc = new TextureDescriptor(indexedSamplerName, texOp.Type, texOp.Handle + index * 2);
  253. context.TextureDescriptors.Add(desc);
  254. }
  255. }
  256. else
  257. {
  258. desc = new TextureDescriptor(samplerName, texOp.Type, texOp.Handle);
  259. context.TextureDescriptors.Add(desc);
  260. }
  261. }
  262. }
  263. private static void DeclareImages(CodeGenContext context, StructuredProgramInfo info)
  264. {
  265. Dictionary<string, AstTextureOperation> images = new Dictionary<string, AstTextureOperation>();
  266. foreach (AstTextureOperation texOp in info.Images.OrderBy(x => x.Handle))
  267. {
  268. string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
  269. string imageName = OperandManager.GetImageName(context.Config.Stage, texOp, indexExpr);
  270. if (!images.TryAdd(imageName, texOp))
  271. {
  272. // Ensure that all texture operations share the same format.
  273. // This avoid errors like mismatched formats.
  274. texOp.Format = images[imageName].Format;
  275. continue;
  276. }
  277. string layout = texOp.Format.ToGlslFormat();
  278. if (!string.IsNullOrEmpty(layout))
  279. {
  280. layout = "layout(" + layout + ") ";
  281. }
  282. string imageTypeName = GetImageTypeName(texOp.Type, texOp.Format.GetComponentType());
  283. context.AppendLine("uniform " + layout + imageTypeName + " " + imageName + ";");
  284. }
  285. foreach (KeyValuePair<string, AstTextureOperation> kv in images)
  286. {
  287. string imageName = kv.Key;
  288. AstTextureOperation texOp = kv.Value;
  289. if ((texOp.Type & SamplerType.Indexed) != 0)
  290. {
  291. for (int index = 0; index < texOp.ArraySize; index++)
  292. {
  293. string indexExpr = NumberFormatter.FormatInt(index);
  294. string indexedSamplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
  295. var desc = new TextureDescriptor(indexedSamplerName, texOp.Type, texOp.Handle + index * 2);
  296. context.TextureDescriptors.Add(desc);
  297. }
  298. }
  299. else
  300. {
  301. var desc = new TextureDescriptor(imageName, texOp.Type, texOp.Handle);
  302. context.ImageDescriptors.Add(desc);
  303. }
  304. }
  305. }
  306. private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
  307. {
  308. string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
  309. foreach (int attr in info.IAttributes.OrderBy(x => x))
  310. {
  311. string iq = string.Empty;
  312. if (context.Config.Stage == ShaderStage.Fragment)
  313. {
  314. iq = context.Config.ImapTypes[attr].GetFirstUsedType() switch
  315. {
  316. PixelImap.Constant => "flat ",
  317. PixelImap.ScreenLinear => "noperspective ",
  318. _ => string.Empty
  319. };
  320. }
  321. for (int c = 0; c < 4; c++)
  322. {
  323. char swzMask = "xyzw"[c];
  324. context.AppendLine($"layout (location = {attr}, component = {c}) {iq}in float {DefaultNames.IAttributePrefix}{attr}_{swzMask}{suffix};");
  325. }
  326. }
  327. }
  328. private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  329. {
  330. if (context.Config.Stage == ShaderStage.Fragment)
  331. {
  332. DeclareUsedOutputAttributes(context, info);
  333. }
  334. else
  335. {
  336. DeclareAllOutputAttributes(context, info);
  337. }
  338. }
  339. private static void DeclareUsedOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  340. {
  341. foreach (int attr in info.OAttributes.OrderBy(x => x))
  342. {
  343. context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
  344. }
  345. }
  346. private static void DeclareAllOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  347. {
  348. for (int attr = 0; attr < MaxAttributes; attr++)
  349. {
  350. for (int c = 0; c < 4; c++)
  351. {
  352. char swzMask = "xyzw"[c];
  353. context.AppendLine($"layout (location = {attr}, component = {c}) out float {DefaultNames.OAttributePrefix}{attr}_{swzMask};");
  354. }
  355. }
  356. foreach (int attr in info.OAttributes.OrderBy(x => x).Where(x => x >= MaxAttributes))
  357. {
  358. for (int c = 0; c < 4; c++)
  359. {
  360. char swzMask = "xyzw"[c];
  361. context.AppendLine($"layout (location = {attr}, component = {c}) out float {DefaultNames.OAttributePrefix}{attr}_{swzMask};");
  362. }
  363. }
  364. }
  365. private static void AppendHelperFunction(CodeGenContext context, string filename)
  366. {
  367. string code = EmbeddedResources.ReadAllText(filename);
  368. context.AppendLine(code.Replace("\t", CodeGenContext.Tab));
  369. context.AppendLine();
  370. }
  371. private static string GetSamplerTypeName(SamplerType type)
  372. {
  373. string typeName;
  374. switch (type & SamplerType.Mask)
  375. {
  376. case SamplerType.Texture1D: typeName = "sampler1D"; break;
  377. case SamplerType.TextureBuffer: typeName = "samplerBuffer"; break;
  378. case SamplerType.Texture2D: typeName = "sampler2D"; break;
  379. case SamplerType.Texture3D: typeName = "sampler3D"; break;
  380. case SamplerType.TextureCube: typeName = "samplerCube"; break;
  381. default: throw new ArgumentException($"Invalid sampler type \"{type}\".");
  382. }
  383. if ((type & SamplerType.Multisample) != 0)
  384. {
  385. typeName += "MS";
  386. }
  387. if ((type & SamplerType.Array) != 0)
  388. {
  389. typeName += "Array";
  390. }
  391. if ((type & SamplerType.Shadow) != 0)
  392. {
  393. typeName += "Shadow";
  394. }
  395. return typeName;
  396. }
  397. private static string GetImageTypeName(SamplerType type, VariableType componentType)
  398. {
  399. string typeName;
  400. switch (type & SamplerType.Mask)
  401. {
  402. case SamplerType.Texture1D: typeName = "image1D"; break;
  403. case SamplerType.TextureBuffer: typeName = "imageBuffer"; break;
  404. case SamplerType.Texture2D: typeName = "image2D"; break;
  405. case SamplerType.Texture3D: typeName = "image3D"; break;
  406. case SamplerType.TextureCube: typeName = "imageCube"; break;
  407. default: throw new ArgumentException($"Invalid sampler type \"{type}\".");
  408. }
  409. if ((type & SamplerType.Multisample) != 0)
  410. {
  411. typeName += "MS";
  412. }
  413. if ((type & SamplerType.Array) != 0)
  414. {
  415. typeName += "Array";
  416. }
  417. switch (componentType)
  418. {
  419. case VariableType.U32: typeName = 'u' + typeName; break;
  420. case VariableType.S32: typeName = 'i' + typeName; break;
  421. }
  422. return typeName;
  423. }
  424. }
  425. }