OpenGLRenderer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using OpenTK.Graphics.OpenGL;
  2. using Ryujinx.Common.Configuration;
  3. using Ryujinx.Common.Logging;
  4. using Ryujinx.Graphics.GAL;
  5. using Ryujinx.Graphics.OpenGL.Image;
  6. using Ryujinx.Graphics.OpenGL.Queries;
  7. using Ryujinx.Graphics.Shader.Translation;
  8. using System;
  9. using BufferAccess = Ryujinx.Graphics.GAL.BufferAccess;
  10. namespace Ryujinx.Graphics.OpenGL
  11. {
  12. public sealed class OpenGLRenderer : IRenderer
  13. {
  14. private readonly Pipeline _pipeline;
  15. public IPipeline Pipeline => _pipeline;
  16. private readonly Counters _counters;
  17. private readonly Window _window;
  18. public IWindow Window => _window;
  19. private readonly TextureCopy _textureCopy;
  20. private readonly TextureCopy _backgroundTextureCopy;
  21. internal TextureCopy TextureCopy => BackgroundContextWorker.InBackground ? _backgroundTextureCopy : _textureCopy;
  22. internal TextureCopyIncompatible TextureCopyIncompatible { get; }
  23. internal TextureCopyMS TextureCopyMS { get; }
  24. private readonly Sync _sync;
  25. public uint ProgramCount { get; set; } = 0;
  26. public event EventHandler<ScreenCaptureImageInfo> ScreenCaptured;
  27. internal PersistentBuffers PersistentBuffers { get; }
  28. internal ResourcePool ResourcePool { get; }
  29. internal int BufferCount { get; private set; }
  30. public string GpuVendor { get; private set; }
  31. public string GpuRenderer { get; private set; }
  32. public string GpuVersion { get; private set; }
  33. public bool PreferThreading => true;
  34. public OpenGLRenderer()
  35. {
  36. _pipeline = new Pipeline();
  37. _counters = new Counters();
  38. _window = new Window(this);
  39. _textureCopy = new TextureCopy(this);
  40. _backgroundTextureCopy = new TextureCopy(this);
  41. TextureCopyIncompatible = new TextureCopyIncompatible(this);
  42. TextureCopyMS = new TextureCopyMS(this);
  43. _sync = new Sync();
  44. PersistentBuffers = new PersistentBuffers();
  45. ResourcePool = new ResourcePool();
  46. }
  47. public BufferHandle CreateBuffer(int size, GAL.BufferAccess access)
  48. {
  49. BufferCount++;
  50. BufferAccess memType = access & GAL.BufferAccess.MemoryTypeMask;
  51. if (memType == GAL.BufferAccess.HostMemory)
  52. {
  53. BufferHandle handle = Buffer.CreatePersistent(size);
  54. PersistentBuffers.Map(handle, size);
  55. return handle;
  56. }
  57. else
  58. {
  59. return Buffer.Create(size);
  60. }
  61. }
  62. public BufferHandle CreateBuffer(nint pointer, int size)
  63. {
  64. throw new NotSupportedException();
  65. }
  66. public BufferHandle CreateBufferSparse(ReadOnlySpan<BufferRange> storageBuffers)
  67. {
  68. throw new NotSupportedException();
  69. }
  70. public IImageArray CreateImageArray(int size, bool isBuffer)
  71. {
  72. return new ImageArray(size);
  73. }
  74. public IProgram CreateProgram(ShaderSource[] shaders, ShaderInfo info)
  75. {
  76. ProgramCount++;
  77. return new Program(shaders, info.FragmentOutputMap);
  78. }
  79. public ISampler CreateSampler(SamplerCreateInfo info)
  80. {
  81. return new Sampler(info);
  82. }
  83. public ITexture CreateTexture(TextureCreateInfo info)
  84. {
  85. if (info.Target == Target.TextureBuffer)
  86. {
  87. return new TextureBuffer(this, info);
  88. }
  89. else
  90. {
  91. return ResourcePool.GetTextureOrNull(info) ?? new TextureStorage(this, info).CreateDefaultView();
  92. }
  93. }
  94. public ITextureArray CreateTextureArray(int size, bool isBuffer)
  95. {
  96. return new TextureArray(size);
  97. }
  98. public void DeleteBuffer(BufferHandle buffer)
  99. {
  100. PersistentBuffers.Unmap(buffer);
  101. Buffer.Delete(buffer);
  102. }
  103. public HardwareInfo GetHardwareInfo()
  104. {
  105. return new HardwareInfo(GpuVendor, GpuRenderer, GpuVendor); // OpenGL does not provide a driver name, vendor name is closest analogue.
  106. }
  107. public PinnedSpan<byte> GetBufferData(BufferHandle buffer, int offset, int size)
  108. {
  109. return Buffer.GetData(this, buffer, offset, size);
  110. }
  111. public Capabilities GetCapabilities()
  112. {
  113. bool intelWindows = HwCapabilities.Vendor == HwCapabilities.GpuVendor.IntelWindows;
  114. bool intelUnix = HwCapabilities.Vendor == HwCapabilities.GpuVendor.IntelUnix;
  115. bool amdWindows = HwCapabilities.Vendor == HwCapabilities.GpuVendor.AmdWindows;
  116. return new Capabilities(
  117. api: TargetApi.OpenGL,
  118. vendorName: GpuVendor,
  119. memoryType: SystemMemoryType.BackendManaged,
  120. hasFrontFacingBug: intelWindows,
  121. hasVectorIndexingBug: amdWindows,
  122. needsFragmentOutputSpecialization: false,
  123. reduceShaderPrecision: false,
  124. supportsAstcCompression: HwCapabilities.SupportsAstcCompression,
  125. supportsBc123Compression: HwCapabilities.SupportsTextureCompressionS3tc,
  126. supportsBc45Compression: HwCapabilities.SupportsTextureCompressionRgtc,
  127. supportsBc67Compression: true, // Should check BPTC extension, but for some reason NVIDIA is not exposing the extension.
  128. supportsEtc2Compression: true,
  129. supports3DTextureCompression: false,
  130. supportsBgraFormat: false,
  131. supportsR4G4Format: false,
  132. supportsR4G4B4A4Format: true,
  133. supportsScaledVertexFormats: true,
  134. supportsSnormBufferTextureFormat: false,
  135. supports5BitComponentFormat: true,
  136. supportsSparseBuffer: false,
  137. supportsBlendEquationAdvanced: HwCapabilities.SupportsBlendEquationAdvanced,
  138. supportsFragmentShaderInterlock: HwCapabilities.SupportsFragmentShaderInterlock,
  139. supportsFragmentShaderOrderingIntel: HwCapabilities.SupportsFragmentShaderOrdering,
  140. supportsGeometryShader: true,
  141. supportsGeometryShaderPassthrough: HwCapabilities.SupportsGeometryShaderPassthrough,
  142. supportsTransformFeedback: true,
  143. supportsImageLoadFormatted: HwCapabilities.SupportsImageLoadFormatted,
  144. supportsLayerVertexTessellation: HwCapabilities.SupportsShaderViewportLayerArray,
  145. supportsMismatchingViewFormat: HwCapabilities.SupportsMismatchingViewFormat,
  146. supportsCubemapView: true,
  147. supportsNonConstantTextureOffset: HwCapabilities.SupportsNonConstantTextureOffset,
  148. supportsQuads: HwCapabilities.SupportsQuads,
  149. supportsSeparateSampler: false,
  150. supportsShaderBallot: HwCapabilities.SupportsShaderBallot,
  151. supportsShaderBarrierDivergence: !(intelWindows || intelUnix),
  152. supportsShaderFloat64: true,
  153. supportsTextureGatherOffsets: true,
  154. supportsTextureShadowLod: HwCapabilities.SupportsTextureShadowLod,
  155. supportsVertexStoreAndAtomics: true,
  156. supportsViewportIndexVertexTessellation: HwCapabilities.SupportsShaderViewportLayerArray,
  157. supportsViewportMask: HwCapabilities.SupportsViewportArray2,
  158. supportsViewportSwizzle: HwCapabilities.SupportsViewportSwizzle,
  159. supportsIndirectParameters: HwCapabilities.SupportsIndirectParameters,
  160. supportsDepthClipControl: true,
  161. uniformBufferSetIndex: 0,
  162. storageBufferSetIndex: 1,
  163. textureSetIndex: 2,
  164. imageSetIndex: 3,
  165. extraSetBaseIndex: 0,
  166. maximumExtraSets: 0,
  167. maximumUniformBuffersPerStage: 13, // TODO: Avoid hardcoding those limits here and get from driver?
  168. maximumStorageBuffersPerStage: 16,
  169. maximumTexturesPerStage: 32,
  170. maximumImagesPerStage: 8,
  171. maximumComputeSharedMemorySize: HwCapabilities.MaximumComputeSharedMemorySize,
  172. maximumSupportedAnisotropy: HwCapabilities.MaximumSupportedAnisotropy,
  173. shaderSubgroupSize: Constants.MaxSubgroupSize,
  174. storageBufferOffsetAlignment: HwCapabilities.StorageBufferOffsetAlignment,
  175. textureBufferOffsetAlignment: HwCapabilities.TextureBufferOffsetAlignment,
  176. gatherBiasPrecision: intelWindows || amdWindows ? 8 : 0, // Precision is 8 for these vendors on Vulkan.
  177. maximumGpuMemory: 0);
  178. }
  179. public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data)
  180. {
  181. Buffer.SetData(buffer, offset, data);
  182. }
  183. public void UpdateCounters()
  184. {
  185. _counters.Update();
  186. }
  187. public void PreFrame()
  188. {
  189. _sync.Cleanup();
  190. ResourcePool.Tick();
  191. }
  192. public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler, float divisor, bool hostReserved)
  193. {
  194. return _counters.QueueReport(type, resultHandler, divisor, _pipeline.DrawCount, hostReserved);
  195. }
  196. public void Initialize(GraphicsDebugLevel glLogLevel)
  197. {
  198. Debugger.Initialize(glLogLevel);
  199. PrintGpuInformation();
  200. if (HwCapabilities.SupportsParallelShaderCompile)
  201. {
  202. GL.Arb.MaxShaderCompilerThreads(Math.Min(Environment.ProcessorCount, 8));
  203. }
  204. _counters.Initialize();
  205. // This is required to disable [0, 1] clamping for SNorm outputs on compatibility profiles.
  206. // This call is expected to fail if we're running with a core profile,
  207. // as this clamp target was deprecated, but that's fine as a core profile
  208. // should already have the desired behaviour where outputs are not clamped.
  209. GL.ClampColor(ClampColorTarget.ClampFragmentColor, ClampColorMode.False);
  210. }
  211. private void PrintGpuInformation()
  212. {
  213. GpuVendor = GL.GetString(StringName.Vendor);
  214. GpuRenderer = GL.GetString(StringName.Renderer);
  215. GpuVersion = GL.GetString(StringName.Version);
  216. Logger.Notice.Print(LogClass.Gpu, $"{GpuVendor} {GpuRenderer} ({GpuVersion})");
  217. }
  218. public void ResetCounter(CounterType type)
  219. {
  220. _counters.QueueReset(type);
  221. }
  222. public void BackgroundContextAction(Action action, bool alwaysBackground = false)
  223. {
  224. // alwaysBackground is ignored, since we cannot switch from the current context.
  225. if (_window.BackgroundContext.HasContext())
  226. {
  227. action(); // We have a context already - use that (assuming it is the main one).
  228. }
  229. else
  230. {
  231. _window.BackgroundContext.Invoke(action);
  232. }
  233. }
  234. public void InitializeBackgroundContext(IOpenGLContext baseContext)
  235. {
  236. _window.InitializeBackgroundContext(baseContext);
  237. }
  238. public void Dispose()
  239. {
  240. _textureCopy.Dispose();
  241. _backgroundTextureCopy.Dispose();
  242. TextureCopyMS.Dispose();
  243. PersistentBuffers.Dispose();
  244. ResourcePool.Dispose();
  245. _pipeline.Dispose();
  246. _window.Dispose();
  247. _counters.Dispose();
  248. _sync.Dispose();
  249. }
  250. public IProgram LoadProgramBinary(byte[] programBinary, bool hasFragmentShader, ShaderInfo info)
  251. {
  252. return new Program(programBinary, hasFragmentShader, info.FragmentOutputMap);
  253. }
  254. public void CreateSync(ulong id, bool strict)
  255. {
  256. _sync.Create(id);
  257. }
  258. public void WaitSync(ulong id)
  259. {
  260. _sync.Wait(id);
  261. }
  262. public ulong GetCurrentSync()
  263. {
  264. return _sync.GetCurrent();
  265. }
  266. public void SetInterruptAction(Action<Action> interruptAction)
  267. {
  268. // Currently no need for an interrupt action.
  269. }
  270. public void Screenshot()
  271. {
  272. _window.ScreenCaptureRequested = true;
  273. }
  274. public void OnScreenCaptured(ScreenCaptureImageInfo bitmap)
  275. {
  276. ScreenCaptured?.Invoke(this, bitmap);
  277. }
  278. public bool PrepareHostMapping(nint address, ulong size)
  279. {
  280. return false;
  281. }
  282. }
  283. }