Declarations.cs 27 KB

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