Declarations.cs 22 KB

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