Declarations.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 450 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. if (context.Config.GpPassthrough)
  26. {
  27. context.AppendLine("#extension GL_NV_geometry_shader_passthrough : enable");
  28. }
  29. context.AppendLine("#pragma optionNV(fastmath off)");
  30. context.AppendLine();
  31. context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
  32. context.AppendLine();
  33. if (context.Config.Stage == ShaderStage.Compute)
  34. {
  35. int localMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeLocalMemorySize(), 4);
  36. if (localMemorySize != 0)
  37. {
  38. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  39. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  40. context.AppendLine();
  41. }
  42. int sharedMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeSharedMemorySize(), 4);
  43. if (sharedMemorySize != 0)
  44. {
  45. string sharedMemorySizeStr = NumberFormatter.FormatInt(sharedMemorySize);
  46. context.AppendLine($"shared uint {DefaultNames.SharedMemoryName}[{sharedMemorySizeStr}];");
  47. context.AppendLine();
  48. }
  49. }
  50. else if (context.Config.LocalMemorySize != 0)
  51. {
  52. int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
  53. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  54. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  55. context.AppendLine();
  56. }
  57. var cBufferDescriptors = context.Config.GetConstantBufferDescriptors();
  58. if (cBufferDescriptors.Length != 0)
  59. {
  60. DeclareUniforms(context, cBufferDescriptors);
  61. context.AppendLine();
  62. }
  63. var sBufferDescriptors = context.Config.GetStorageBufferDescriptors();
  64. if (sBufferDescriptors.Length != 0)
  65. {
  66. DeclareStorages(context, sBufferDescriptors);
  67. context.AppendLine();
  68. }
  69. var textureDescriptors = context.Config.GetTextureDescriptors();
  70. if (textureDescriptors.Length != 0)
  71. {
  72. DeclareSamplers(context, textureDescriptors);
  73. context.AppendLine();
  74. }
  75. var imageDescriptors = context.Config.GetImageDescriptors();
  76. if (imageDescriptors.Length != 0)
  77. {
  78. DeclareImages(context, imageDescriptors);
  79. context.AppendLine();
  80. }
  81. if (context.Config.Stage != ShaderStage.Compute)
  82. {
  83. if (context.Config.Stage == ShaderStage.Geometry)
  84. {
  85. string inPrimitive = context.Config.GpuAccessor.QueryPrimitiveTopology().ToGlslString();
  86. context.AppendLine($"layout ({inPrimitive}) in;");
  87. if (context.Config.GpPassthrough)
  88. {
  89. context.AppendLine($"layout (passthrough) in gl_PerVertex");
  90. context.EnterScope();
  91. context.AppendLine("vec4 gl_Position;");
  92. context.AppendLine("float gl_PointSize;");
  93. context.AppendLine("float gl_ClipDistance[];");
  94. context.LeaveScope(";");
  95. }
  96. else
  97. {
  98. string outPrimitive = context.Config.OutputTopology.ToGlslString();
  99. int maxOutputVertices = context.Config.MaxOutputVertices;
  100. context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
  101. }
  102. context.AppendLine();
  103. }
  104. if (info.IAttributes.Count != 0)
  105. {
  106. DeclareInputAttributes(context, info);
  107. context.AppendLine();
  108. }
  109. if (info.OAttributes.Count != 0 || context.Config.Stage != ShaderStage.Fragment)
  110. {
  111. DeclareOutputAttributes(context, info);
  112. context.AppendLine();
  113. }
  114. }
  115. else
  116. {
  117. string localSizeX = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeX());
  118. string localSizeY = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeY());
  119. string localSizeZ = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeZ());
  120. context.AppendLine(
  121. "layout (" +
  122. $"local_size_x = {localSizeX}, " +
  123. $"local_size_y = {localSizeY}, " +
  124. $"local_size_z = {localSizeZ}) in;");
  125. context.AppendLine();
  126. }
  127. if (context.Config.Stage == ShaderStage.Fragment || context.Config.Stage == ShaderStage.Compute)
  128. {
  129. if (context.Config.Stage == ShaderStage.Fragment)
  130. {
  131. if (context.Config.GpuAccessor.QueryEarlyZForce())
  132. {
  133. context.AppendLine("layout(early_fragment_tests) in;");
  134. context.AppendLine();
  135. }
  136. context.AppendLine($"uniform bool {DefaultNames.IsBgraName}[8];");
  137. context.AppendLine();
  138. }
  139. if (DeclareRenderScale(context))
  140. {
  141. context.AppendLine();
  142. }
  143. }
  144. if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Shared) != 0)
  145. {
  146. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Shared.glsl");
  147. }
  148. if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Storage) != 0)
  149. {
  150. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Storage.glsl");
  151. }
  152. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighS32) != 0)
  153. {
  154. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighS32.glsl");
  155. }
  156. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighU32) != 0)
  157. {
  158. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighU32.glsl");
  159. }
  160. if ((info.HelperFunctionsMask & HelperFunctionsMask.Shuffle) != 0)
  161. {
  162. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/Shuffle.glsl");
  163. }
  164. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleDown) != 0)
  165. {
  166. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleDown.glsl");
  167. }
  168. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleUp) != 0)
  169. {
  170. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleUp.glsl");
  171. }
  172. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleXor) != 0)
  173. {
  174. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleXor.glsl");
  175. }
  176. if ((info.HelperFunctionsMask & HelperFunctionsMask.SwizzleAdd) != 0)
  177. {
  178. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/SwizzleAdd.glsl");
  179. }
  180. }
  181. public static void DeclareLocals(CodeGenContext context, StructuredFunction function)
  182. {
  183. foreach (AstOperand decl in function.Locals)
  184. {
  185. string name = context.OperandManager.DeclareLocal(decl);
  186. context.AppendLine(GetVarTypeName(decl.VarType) + " " + name + ";");
  187. }
  188. }
  189. public static string GetVarTypeName(VariableType type)
  190. {
  191. switch (type)
  192. {
  193. case VariableType.Bool: return "bool";
  194. case VariableType.F32: return "precise float";
  195. case VariableType.F64: return "double";
  196. case VariableType.None: return "void";
  197. case VariableType.S32: return "int";
  198. case VariableType.U32: return "uint";
  199. }
  200. throw new ArgumentException($"Invalid variable type \"{type}\".");
  201. }
  202. private static void DeclareUniforms(CodeGenContext context, BufferDescriptor[] descriptors)
  203. {
  204. string ubSize = "[" + NumberFormatter.FormatInt(Constants.ConstantBufferSize / 16) + "]";
  205. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  206. {
  207. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  208. ubName += "_" + DefaultNames.UniformNamePrefix;
  209. string blockName = $"{ubName}_{DefaultNames.BlockSuffix}";
  210. context.AppendLine($"layout (binding = {context.Config.FirstConstantBufferBinding}, std140) uniform {blockName}");
  211. context.EnterScope();
  212. context.AppendLine("vec4 " + DefaultNames.DataName + ubSize + ";");
  213. context.LeaveScope($" {ubName}[{NumberFormatter.FormatInt(descriptors.Max(x => x.Slot) + 1)}];");
  214. }
  215. else
  216. {
  217. foreach (var descriptor in descriptors)
  218. {
  219. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  220. ubName += "_" + DefaultNames.UniformNamePrefix + descriptor.Slot;
  221. context.AppendLine($"layout (binding = {descriptor.Binding}, std140) uniform {ubName}");
  222. context.EnterScope();
  223. context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, descriptor.Slot, false) + ubSize + ";");
  224. context.LeaveScope(";");
  225. }
  226. }
  227. }
  228. private static void DeclareStorages(CodeGenContext context, BufferDescriptor[] descriptors)
  229. {
  230. string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  231. sbName += "_" + DefaultNames.StorageNamePrefix;
  232. string blockName = $"{sbName}_{DefaultNames.BlockSuffix}";
  233. context.AppendLine($"layout (binding = {context.Config.FirstStorageBufferBinding}, std430) buffer {blockName}");
  234. context.EnterScope();
  235. context.AppendLine("uint " + DefaultNames.DataName + "[];");
  236. context.LeaveScope($" {sbName}[{NumberFormatter.FormatInt(descriptors.Max(x => x.Slot) + 1)}];");
  237. }
  238. private static void DeclareSamplers(CodeGenContext context, TextureDescriptor[] descriptors)
  239. {
  240. int arraySize = 0;
  241. foreach (var descriptor in descriptors)
  242. {
  243. if (descriptor.Type.HasFlag(SamplerType.Indexed))
  244. {
  245. if (arraySize == 0)
  246. {
  247. arraySize = ShaderConfig.SamplerArraySize;
  248. }
  249. else if (--arraySize != 0)
  250. {
  251. continue;
  252. }
  253. }
  254. string indexExpr = NumberFormatter.FormatInt(arraySize);
  255. string samplerName = OperandManager.GetSamplerName(
  256. context.Config.Stage,
  257. descriptor.CbufSlot,
  258. descriptor.HandleIndex,
  259. descriptor.Type.HasFlag(SamplerType.Indexed),
  260. indexExpr);
  261. string samplerTypeName = descriptor.Type.ToGlslSamplerType();
  262. context.AppendLine($"layout (binding = {descriptor.Binding}) uniform {samplerTypeName} {samplerName};");
  263. }
  264. }
  265. private static void DeclareImages(CodeGenContext context, TextureDescriptor[] descriptors)
  266. {
  267. int arraySize = 0;
  268. foreach (var descriptor in descriptors)
  269. {
  270. if (descriptor.Type.HasFlag(SamplerType.Indexed))
  271. {
  272. if (arraySize == 0)
  273. {
  274. arraySize = ShaderConfig.SamplerArraySize;
  275. }
  276. else if (--arraySize != 0)
  277. {
  278. continue;
  279. }
  280. }
  281. string indexExpr = NumberFormatter.FormatInt(arraySize);
  282. string imageName = OperandManager.GetImageName(
  283. context.Config.Stage,
  284. descriptor.CbufSlot,
  285. descriptor.HandleIndex,
  286. descriptor.Format,
  287. descriptor.Type.HasFlag(SamplerType.Indexed),
  288. indexExpr);
  289. string layout = descriptor.Format.ToGlslFormat();
  290. if (!string.IsNullOrEmpty(layout))
  291. {
  292. layout = ", " + layout;
  293. }
  294. string imageTypeName = descriptor.Type.ToGlslImageType(descriptor.Format.GetComponentType());
  295. context.AppendLine($"layout (binding = {descriptor.Binding}{layout}) uniform {imageTypeName} {imageName};");
  296. }
  297. }
  298. private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
  299. {
  300. string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
  301. foreach (int attr in info.IAttributes.OrderBy(x => x))
  302. {
  303. string iq = string.Empty;
  304. if (context.Config.Stage == ShaderStage.Fragment)
  305. {
  306. iq = context.Config.ImapTypes[attr].GetFirstUsedType() switch
  307. {
  308. PixelImap.Constant => "flat ",
  309. PixelImap.ScreenLinear => "noperspective ",
  310. _ => string.Empty
  311. };
  312. }
  313. string pass = context.Config.GpPassthrough ? "passthrough, " : string.Empty;
  314. string name = $"{DefaultNames.IAttributePrefix}{attr}";
  315. if ((context.Config.Flags & TranslationFlags.Feedback) != 0)
  316. {
  317. for (int c = 0; c < 4; c++)
  318. {
  319. char swzMask = "xyzw"[c];
  320. context.AppendLine($"layout ({pass}location = {attr}, component = {c}) {iq}in float {name}_{swzMask}{suffix};");
  321. }
  322. }
  323. else
  324. {
  325. context.AppendLine($"layout ({pass}location = {attr}) {iq}in vec4 {name}{suffix};");
  326. }
  327. }
  328. }
  329. private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  330. {
  331. if (context.Config.Stage == ShaderStage.Fragment)
  332. {
  333. DeclareUsedOutputAttributes(context, info);
  334. }
  335. else
  336. {
  337. DeclareAllOutputAttributes(context, info);
  338. }
  339. }
  340. private static void DeclareUsedOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  341. {
  342. foreach (int attr in info.OAttributes.OrderBy(x => x))
  343. {
  344. context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
  345. }
  346. }
  347. private static void DeclareAllOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  348. {
  349. for (int attr = 0; attr < MaxAttributes; attr++)
  350. {
  351. DeclareOutputAttribute(context, attr);
  352. }
  353. foreach (int attr in info.OAttributes.OrderBy(x => x).Where(x => x >= MaxAttributes))
  354. {
  355. DeclareOutputAttribute(context, attr);
  356. }
  357. }
  358. private static void DeclareOutputAttribute(CodeGenContext context, int attr)
  359. {
  360. string name = $"{DefaultNames.OAttributePrefix}{attr}";
  361. if ((context.Config.Flags & TranslationFlags.Feedback) != 0)
  362. {
  363. for (int c = 0; c < 4; c++)
  364. {
  365. char swzMask = "xyzw"[c];
  366. context.AppendLine($"layout (location = {attr}, component = {c}) out float {name}_{swzMask};");
  367. }
  368. }
  369. else
  370. {
  371. context.AppendLine($"layout (location = {attr}) out vec4 {name};");
  372. }
  373. }
  374. private static bool DeclareRenderScale(CodeGenContext context)
  375. {
  376. if ((context.Config.UsedFeatures & (FeatureFlags.FragCoordXY | FeatureFlags.IntegerSampling)) != 0)
  377. {
  378. string stage = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  379. int scaleElements = context.Config.GetTextureDescriptors().Length + context.Config.GetImageDescriptors().Length;
  380. if (context.Config.Stage == ShaderStage.Fragment)
  381. {
  382. scaleElements++; // Also includes render target scale, for gl_FragCoord.
  383. }
  384. context.AppendLine($"uniform float {stage}_renderScale[{scaleElements}];");
  385. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.IntegerSampling))
  386. {
  387. context.AppendLine();
  388. AppendHelperFunction(context, $"Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/TexelFetchScale_{stage}.glsl");
  389. }
  390. return true;
  391. }
  392. return false;
  393. }
  394. private static void AppendHelperFunction(CodeGenContext context, string filename)
  395. {
  396. string code = EmbeddedResources.ReadAllText(filename);
  397. code = code.Replace("\t", CodeGenContext.Tab);
  398. code = code.Replace("$SHARED_MEM$", DefaultNames.SharedMemoryName);
  399. code = code.Replace("$STORAGE_MEM$", OperandManager.GetShaderStagePrefix(context.Config.Stage) + "_" + DefaultNames.StorageNamePrefix);
  400. context.AppendLine(code);
  401. context.AppendLine();
  402. }
  403. }
  404. }