Declarations.cs 22 KB

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