Declarations.cs 20 KB

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