Declarations.cs 21 KB

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