NvGpuEngine3d.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Gal;
  3. using Ryujinx.Graphics.Memory;
  4. using Ryujinx.Graphics.Shader;
  5. using Ryujinx.Graphics.Texture;
  6. using System;
  7. using System.Collections.Generic;
  8. using Ryujinx.Profiler;
  9. namespace Ryujinx.Graphics.Graphics3d
  10. {
  11. class NvGpuEngine3d : INvGpuEngine
  12. {
  13. public int[] Registers { get; private set; }
  14. private NvGpu _gpu;
  15. private Dictionary<int, NvGpuMethod> _methods;
  16. private struct ConstBuffer
  17. {
  18. public bool Enabled;
  19. public long Position;
  20. public int Size;
  21. }
  22. private ConstBuffer[][] _constBuffers;
  23. // Viewport dimensions kept for scissor test limits
  24. private int _viewportX0 = 0;
  25. private int _viewportY0 = 0;
  26. private int _viewportX1 = 0;
  27. private int _viewportY1 = 0;
  28. private int _viewportWidth = 0;
  29. private int _viewportHeight = 0;
  30. private int _currentInstance = 0;
  31. public NvGpuEngine3d(NvGpu gpu)
  32. {
  33. _gpu = gpu;
  34. Registers = new int[0xe00];
  35. _methods = new Dictionary<int, NvGpuMethod>();
  36. void AddMethod(int meth, int count, int stride, NvGpuMethod method)
  37. {
  38. while (count-- > 0)
  39. {
  40. _methods.Add(meth, method);
  41. meth += stride;
  42. }
  43. }
  44. AddMethod(0x585, 1, 1, VertexEndGl);
  45. AddMethod(0x674, 1, 1, ClearBuffers);
  46. AddMethod(0x6c3, 1, 1, QueryControl);
  47. AddMethod(0x8e4, 16, 1, CbData);
  48. AddMethod(0x904, 5, 8, CbBind);
  49. _constBuffers = new ConstBuffer[6][];
  50. for (int index = 0; index < _constBuffers.Length; index++)
  51. {
  52. _constBuffers[index] = new ConstBuffer[18];
  53. }
  54. // Ensure that all components are enabled by default.
  55. // FIXME: Is this correct?
  56. WriteRegister(NvGpuEngine3dReg.ColorMaskN, 0x1111);
  57. WriteRegister(NvGpuEngine3dReg.FrameBufferSrgb, 1);
  58. WriteRegister(NvGpuEngine3dReg.FrontFace, (int)GalFrontFace.Cw);
  59. for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++)
  60. {
  61. WriteRegister(NvGpuEngine3dReg.IBlendNEquationRgb + index * 8, (int)GalBlendEquation.FuncAdd);
  62. WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb + index * 8, (int)GalBlendFactor.One);
  63. WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb + index * 8, (int)GalBlendFactor.Zero);
  64. WriteRegister(NvGpuEngine3dReg.IBlendNEquationAlpha + index * 8, (int)GalBlendEquation.FuncAdd);
  65. WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha + index * 8, (int)GalBlendFactor.One);
  66. WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha + index * 8, (int)GalBlendFactor.Zero);
  67. }
  68. }
  69. public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall)
  70. {
  71. if (_methods.TryGetValue(methCall.Method, out NvGpuMethod method))
  72. {
  73. ProfileConfig profile = Profiles.GPU.Engine3d.CallMethod;
  74. profile.SessionItem = method.Method.Name;
  75. Profile.Begin(profile);
  76. method(vmm, methCall);
  77. Profile.End(profile);
  78. }
  79. else
  80. {
  81. WriteRegister(methCall);
  82. }
  83. }
  84. private void VertexEndGl(NvGpuVmm vmm, GpuMethodCall methCall)
  85. {
  86. Profile.Begin(Profiles.GPU.Engine3d.VertexEnd);
  87. LockCaches();
  88. Profile.Begin(Profiles.GPU.Engine3d.ConfigureState);
  89. GalPipelineState state = new GalPipelineState();
  90. // Framebuffer must be run configured because viewport dimensions may be used in other methods
  91. SetFrameBuffer(state);
  92. Profile.End(Profiles.GPU.Engine3d.ConfigureState);
  93. for (int fbIndex = 0; fbIndex < 8; fbIndex++)
  94. {
  95. SetFrameBuffer(vmm, fbIndex);
  96. }
  97. SetFrontFace(state);
  98. SetCullFace(state);
  99. SetDepth(state);
  100. SetStencil(state);
  101. SetScissor(state);
  102. SetBlending(state);
  103. SetColorMask(state);
  104. SetPrimitiveRestart(state);
  105. SetZeta(vmm);
  106. SetRenderTargets();
  107. long[] keys = UploadShaders(vmm);
  108. _gpu.Renderer.Shader.BindProgram();
  109. UploadTextures(vmm, state, keys);
  110. UploadConstBuffers(vmm, state, keys);
  111. UploadVertexArrays(vmm, state);
  112. DispatchRender(vmm, state);
  113. UnlockCaches();
  114. Profile.End(Profiles.GPU.Engine3d.VertexEnd);
  115. }
  116. private void LockCaches()
  117. {
  118. _gpu.Renderer.Buffer.LockCache();
  119. _gpu.Renderer.Rasterizer.LockCaches();
  120. _gpu.Renderer.Texture.LockCache();
  121. }
  122. private void UnlockCaches()
  123. {
  124. _gpu.Renderer.Buffer.UnlockCache();
  125. _gpu.Renderer.Rasterizer.UnlockCaches();
  126. _gpu.Renderer.Texture.UnlockCache();
  127. }
  128. private void ClearBuffers(NvGpuVmm vmm, GpuMethodCall methCall)
  129. {
  130. Profile.Begin(Profiles.GPU.Engine3d.ClearBuffers);
  131. int attachment = (methCall.Argument >> 6) & 0xf;
  132. GalClearBufferFlags flags = (GalClearBufferFlags)(methCall.Argument & 0x3f);
  133. float red = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 0);
  134. float green = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 1);
  135. float blue = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 2);
  136. float alpha = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 3);
  137. float depth = ReadRegisterFloat(NvGpuEngine3dReg.ClearDepth);
  138. int stencil = ReadRegister(NvGpuEngine3dReg.ClearStencil);
  139. SetFrameBuffer(vmm, attachment);
  140. SetZeta(vmm);
  141. SetRenderTargets();
  142. _gpu.Renderer.RenderTarget.Bind();
  143. _gpu.Renderer.Rasterizer.ClearBuffers(flags, attachment, red, green, blue, alpha, depth, stencil);
  144. _gpu.Renderer.Pipeline.ResetDepthMask();
  145. _gpu.Renderer.Pipeline.ResetColorMask(attachment);
  146. Profile.End(Profiles.GPU.Engine3d.ClearBuffers);
  147. }
  148. private void SetFrameBuffer(NvGpuVmm vmm, int fbIndex)
  149. {
  150. ProfileConfig profile = Profiles.GPU.Engine3d.SetFrameBuffer;
  151. profile.SessionItem = fbIndex.ToString();
  152. Profile.Begin(profile);
  153. long va = MakeInt64From2xInt32(NvGpuEngine3dReg.FrameBufferNAddress + fbIndex * 0x10);
  154. int surfFormat = ReadRegister(NvGpuEngine3dReg.FrameBufferNFormat + fbIndex * 0x10);
  155. if (va == 0 || surfFormat == 0)
  156. {
  157. _gpu.Renderer.RenderTarget.UnbindColor(fbIndex);
  158. Profile.End(profile);
  159. return;
  160. }
  161. long key = vmm.GetPhysicalAddress(va);
  162. int width = ReadRegister(NvGpuEngine3dReg.FrameBufferNWidth + fbIndex * 0x10);
  163. int height = ReadRegister(NvGpuEngine3dReg.FrameBufferNHeight + fbIndex * 0x10);
  164. int arrayMode = ReadRegister(NvGpuEngine3dReg.FrameBufferNArrayMode + fbIndex * 0x10);
  165. int layerCount = arrayMode & 0xFFFF;
  166. int layerStride = ReadRegister(NvGpuEngine3dReg.FrameBufferNLayerStride + fbIndex * 0x10);
  167. int baseLayer = ReadRegister(NvGpuEngine3dReg.FrameBufferNBaseLayer + fbIndex * 0x10);
  168. int blockDim = ReadRegister(NvGpuEngine3dReg.FrameBufferNBlockDim + fbIndex * 0x10);
  169. int gobBlockHeight = 1 << ((blockDim >> 4) & 7);
  170. GalMemoryLayout layout = (GalMemoryLayout)((blockDim >> 12) & 1);
  171. float tx = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateX + fbIndex * 8);
  172. float ty = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateY + fbIndex * 8);
  173. float sx = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleX + fbIndex * 8);
  174. float sy = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleY + fbIndex * 8);
  175. _viewportX0 = (int)MathF.Max(0, tx - MathF.Abs(sx));
  176. _viewportY0 = (int)MathF.Max(0, ty - MathF.Abs(sy));
  177. _viewportX1 = (int)(tx + MathF.Abs(sx));
  178. _viewportY1 = (int)(ty + MathF.Abs(sy));
  179. GalImageFormat format = ImageUtils.ConvertSurface((GalSurfaceFormat)surfFormat);
  180. GalImage image = new GalImage(width, height, 1, 1, 1, gobBlockHeight, 1, layout, format, GalTextureTarget.TwoD);
  181. _gpu.ResourceManager.SendColorBuffer(vmm, key, fbIndex, image);
  182. _gpu.Renderer.RenderTarget.SetViewport(fbIndex, _viewportX0, _viewportY0, _viewportX1 - _viewportX0, _viewportY1 - _viewportY0);
  183. Profile.End(profile);
  184. }
  185. private void SetFrameBuffer(GalPipelineState state)
  186. {
  187. state.FramebufferSrgb = ReadRegisterBool(NvGpuEngine3dReg.FrameBufferSrgb);
  188. state.FlipX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  189. state.FlipY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  190. int screenYControl = ReadRegister(NvGpuEngine3dReg.ScreenYControl);
  191. bool negateY = (screenYControl & 1) != 0;
  192. if (negateY)
  193. {
  194. state.FlipY = -state.FlipY;
  195. }
  196. }
  197. private void SetZeta(NvGpuVmm vmm)
  198. {
  199. Profile.Begin(Profiles.GPU.Engine3d.SetZeta);
  200. long va = MakeInt64From2xInt32(NvGpuEngine3dReg.ZetaAddress);
  201. int zetaFormat = ReadRegister(NvGpuEngine3dReg.ZetaFormat);
  202. int blockDim = ReadRegister(NvGpuEngine3dReg.ZetaBlockDimensions);
  203. int gobBlockHeight = 1 << ((blockDim >> 4) & 7);
  204. GalMemoryLayout layout = (GalMemoryLayout)((blockDim >> 12) & 1); //?
  205. bool zetaEnable = ReadRegisterBool(NvGpuEngine3dReg.ZetaEnable);
  206. if (va == 0 || zetaFormat == 0 || !zetaEnable)
  207. {
  208. _gpu.Renderer.RenderTarget.UnbindZeta();
  209. Profile.End(Profiles.GPU.Engine3d.SetZeta);
  210. return;
  211. }
  212. long key = vmm.GetPhysicalAddress(va);
  213. int width = ReadRegister(NvGpuEngine3dReg.ZetaHoriz);
  214. int height = ReadRegister(NvGpuEngine3dReg.ZetaVert);
  215. GalImageFormat format = ImageUtils.ConvertZeta((GalZetaFormat)zetaFormat);
  216. // TODO: Support non 2D?
  217. GalImage image = new GalImage(width, height, 1, 1, 1, gobBlockHeight, 1, layout, format, GalTextureTarget.TwoD);
  218. _gpu.ResourceManager.SendZetaBuffer(vmm, key, image);
  219. Profile.End(Profiles.GPU.Engine3d.SetZeta);
  220. }
  221. private long[] UploadShaders(NvGpuVmm vmm)
  222. {
  223. Profile.Begin(Profiles.GPU.Engine3d.UploadShaders);
  224. long[] keys = new long[5];
  225. long basePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  226. int index = 1;
  227. int vpAControl = ReadRegister(NvGpuEngine3dReg.ShaderNControl);
  228. bool vpAEnable = (vpAControl & 1) != 0;
  229. if (vpAEnable)
  230. {
  231. // Note: The maxwell supports 2 vertex programs, usually
  232. // only VP B is used, but in some cases VP A is also used.
  233. // In this case, it seems to function as an extra vertex
  234. // shader stage.
  235. // The graphics abstraction layer has a special overload for this
  236. // case, which should merge the two shaders into one vertex shader.
  237. int vpAOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset);
  238. int vpBOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + 0x10);
  239. long vpAPos = basePosition + (uint)vpAOffset;
  240. long vpBPos = basePosition + (uint)vpBOffset;
  241. keys[(int)GalShaderType.Vertex] = vpBPos;
  242. _gpu.Renderer.Shader.Create(vmm, vpAPos, vpBPos, GalShaderType.Vertex);
  243. _gpu.Renderer.Shader.Bind(vpBPos);
  244. index = 2;
  245. }
  246. for (; index < 6; index++)
  247. {
  248. GalShaderType type = GetTypeFromProgram(index);
  249. int control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + index * 0x10);
  250. int offset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + index * 0x10);
  251. // Note: Vertex Program (B) is always enabled.
  252. bool enable = (control & 1) != 0 || index == 1;
  253. if (!enable)
  254. {
  255. _gpu.Renderer.Shader.Unbind(type);
  256. continue;
  257. }
  258. long key = basePosition + (uint)offset;
  259. keys[(int)type] = key;
  260. _gpu.Renderer.Shader.Create(vmm, key, type);
  261. _gpu.Renderer.Shader.Bind(key);
  262. }
  263. Profile.End(Profiles.GPU.Engine3d.UploadShaders);
  264. return keys;
  265. }
  266. private static GalShaderType GetTypeFromProgram(int program)
  267. {
  268. switch (program)
  269. {
  270. case 0:
  271. case 1: return GalShaderType.Vertex;
  272. case 2: return GalShaderType.TessControl;
  273. case 3: return GalShaderType.TessEvaluation;
  274. case 4: return GalShaderType.Geometry;
  275. case 5: return GalShaderType.Fragment;
  276. }
  277. throw new ArgumentOutOfRangeException(nameof(program));
  278. }
  279. private void SetFrontFace(GalPipelineState state)
  280. {
  281. float signX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  282. float signY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  283. GalFrontFace frontFace = (GalFrontFace)ReadRegister(NvGpuEngine3dReg.FrontFace);
  284. // Flipping breaks facing. Flipping front facing too fixes it
  285. if (signX != signY)
  286. {
  287. switch (frontFace)
  288. {
  289. case GalFrontFace.Cw: frontFace = GalFrontFace.Ccw; break;
  290. case GalFrontFace.Ccw: frontFace = GalFrontFace.Cw; break;
  291. }
  292. }
  293. state.FrontFace = frontFace;
  294. }
  295. private void SetCullFace(GalPipelineState state)
  296. {
  297. state.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable);
  298. if (state.CullFaceEnabled)
  299. {
  300. state.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace);
  301. }
  302. }
  303. private void SetDepth(GalPipelineState state)
  304. {
  305. state.DepthTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthTestEnable);
  306. state.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable);
  307. if (state.DepthTestEnabled)
  308. {
  309. state.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction);
  310. }
  311. state.DepthRangeNear = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNNear);
  312. state.DepthRangeFar = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNFar);
  313. }
  314. private void SetStencil(GalPipelineState state)
  315. {
  316. state.StencilTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.StencilEnable);
  317. if (state.StencilTestEnabled)
  318. {
  319. state.StencilBackFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilBackFuncFunc);
  320. state.StencilBackFuncRef = ReadRegister(NvGpuEngine3dReg.StencilBackFuncRef);
  321. state.StencilBackFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackFuncMask);
  322. state.StencilBackOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpFail);
  323. state.StencilBackOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZFail);
  324. state.StencilBackOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZPass);
  325. state.StencilBackMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackMask);
  326. state.StencilFrontFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncFunc);
  327. state.StencilFrontFuncRef = ReadRegister(NvGpuEngine3dReg.StencilFrontFuncRef);
  328. state.StencilFrontFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncMask);
  329. state.StencilFrontOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpFail);
  330. state.StencilFrontOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZFail);
  331. state.StencilFrontOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZPass);
  332. state.StencilFrontMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontMask);
  333. }
  334. }
  335. private void SetScissor(GalPipelineState state)
  336. {
  337. int count = 0;
  338. for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++)
  339. {
  340. state.ScissorTestEnabled[index] = ReadRegisterBool(NvGpuEngine3dReg.ScissorEnable + index * 4);
  341. if (state.ScissorTestEnabled[index])
  342. {
  343. uint scissorHorizontal = (uint)ReadRegister(NvGpuEngine3dReg.ScissorHorizontal + index * 4);
  344. uint scissorVertical = (uint)ReadRegister(NvGpuEngine3dReg.ScissorVertical + index * 4);
  345. int left = (int)(scissorHorizontal & 0xFFFF); // Left, lower 16 bits
  346. int right = (int)(scissorHorizontal >> 16); // Right, upper 16 bits
  347. int bottom = (int)(scissorVertical & 0xFFFF); // Bottom, lower 16 bits
  348. int top = (int)(scissorVertical >> 16); // Top, upper 16 bits
  349. int width = Math.Abs(right - left);
  350. int height = Math.Abs(top - bottom);
  351. // If the scissor test covers the whole possible viewport, i.e. uninitialized, disable scissor test
  352. if ((width > NvGpu.MaxViewportSize && height > NvGpu.MaxViewportSize) || width <= 0 || height <= 0)
  353. {
  354. state.ScissorTestEnabled[index] = false;
  355. continue;
  356. }
  357. // Keep track of how many scissor tests are active.
  358. // If only 1, and it's the first user should apply to all viewports
  359. count++;
  360. // Flip X
  361. if (state.FlipX == -1)
  362. {
  363. left = _viewportX1 - (left - _viewportX0);
  364. right = _viewportX1 - (right - _viewportX0);
  365. }
  366. // Ensure X is in the right order
  367. if (left > right)
  368. {
  369. int temp = left;
  370. left = right;
  371. right = temp;
  372. }
  373. // Flip Y
  374. if (state.FlipY == -1)
  375. {
  376. bottom = _viewportY1 - (bottom - _viewportY0);
  377. top = _viewportY1 - (top - _viewportY0);
  378. }
  379. // Ensure Y is in the right order
  380. if (bottom > top)
  381. {
  382. int temp = top;
  383. top = bottom;
  384. bottom = temp;
  385. }
  386. // Handle out of active viewport dimensions
  387. left = Math.Clamp(left, _viewportX0, _viewportX1);
  388. right = Math.Clamp(right, _viewportX0, _viewportX1);
  389. top = Math.Clamp(top, _viewportY0, _viewportY1);
  390. bottom = Math.Clamp(bottom, _viewportY0, _viewportY1);
  391. // Save values to state
  392. state.ScissorTestX[index] = left;
  393. state.ScissorTestY[index] = bottom;
  394. state.ScissorTestWidth[index] = right - left;
  395. state.ScissorTestHeight[index] = top - bottom;
  396. }
  397. }
  398. state.ScissorTestCount = count;
  399. }
  400. private void SetBlending(GalPipelineState state)
  401. {
  402. bool blendIndependent = ReadRegisterBool(NvGpuEngine3dReg.BlendIndependent);
  403. state.BlendIndependent = blendIndependent;
  404. for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++)
  405. {
  406. if (blendIndependent)
  407. {
  408. state.Blends[index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable + index);
  409. if (state.Blends[index].Enabled)
  410. {
  411. state.Blends[index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha + index * 8);
  412. state.Blends[index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationRgb + index * 8);
  413. state.Blends[index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcRgb + index * 8);
  414. state.Blends[index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstRgb + index * 8);
  415. state.Blends[index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationAlpha + index * 8);
  416. state.Blends[index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcAlpha + index * 8);
  417. state.Blends[index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstAlpha + index * 8);
  418. }
  419. }
  420. else
  421. {
  422. // It seems that even when independent blend is disabled, the first IBlend enable
  423. // register is still set to indicate whenever blend is enabled or not (?).
  424. state.Blends[index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable);
  425. if (state.Blends[index].Enabled)
  426. {
  427. state.Blends[index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.BlendSeparateAlpha);
  428. state.Blends[index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationRgb);
  429. state.Blends[index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcRgb);
  430. state.Blends[index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstRgb);
  431. state.Blends[index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationAlpha);
  432. state.Blends[index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcAlpha);
  433. state.Blends[index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstAlpha);
  434. }
  435. }
  436. }
  437. }
  438. private GalBlendEquation ReadBlendEquation(NvGpuEngine3dReg register)
  439. {
  440. return (GalBlendEquation)ReadRegister(register);
  441. }
  442. private GalBlendFactor ReadBlendFactor(NvGpuEngine3dReg register)
  443. {
  444. return (GalBlendFactor)ReadRegister(register);
  445. }
  446. private void SetColorMask(GalPipelineState state)
  447. {
  448. bool colorMaskCommon = ReadRegisterBool(NvGpuEngine3dReg.ColorMaskCommon);
  449. state.ColorMaskCommon = colorMaskCommon;
  450. for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++)
  451. {
  452. int colorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + (colorMaskCommon ? 0 : index));
  453. state.ColorMasks[index].Red = ((colorMask >> 0) & 0xf) != 0;
  454. state.ColorMasks[index].Green = ((colorMask >> 4) & 0xf) != 0;
  455. state.ColorMasks[index].Blue = ((colorMask >> 8) & 0xf) != 0;
  456. state.ColorMasks[index].Alpha = ((colorMask >> 12) & 0xf) != 0;
  457. }
  458. }
  459. private void SetPrimitiveRestart(GalPipelineState state)
  460. {
  461. state.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable);
  462. if (state.PrimitiveRestartEnabled)
  463. {
  464. state.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex);
  465. }
  466. }
  467. private void SetRenderTargets()
  468. {
  469. // Commercial games do not seem to
  470. // bool SeparateFragData = ReadRegisterBool(NvGpuEngine3dReg.RTSeparateFragData);
  471. uint control = (uint)(ReadRegister(NvGpuEngine3dReg.RtControl));
  472. uint count = control & 0xf;
  473. if (count > 0)
  474. {
  475. int[] map = new int[count];
  476. for (int index = 0; index < count; index++)
  477. {
  478. int shift = 4 + index * 3;
  479. map[index] = (int)((control >> shift) & 7);
  480. }
  481. _gpu.Renderer.RenderTarget.SetMap(map);
  482. }
  483. else
  484. {
  485. _gpu.Renderer.RenderTarget.SetMap(null);
  486. }
  487. }
  488. private void UploadTextures(NvGpuVmm vmm, GalPipelineState state, long[] keys)
  489. {
  490. Profile.Begin(Profiles.GPU.Engine3d.UploadTextures);
  491. long baseShPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  492. int textureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex);
  493. List<(long, GalImage, GalTextureSampler)> unboundTextures = new List<(long, GalImage, GalTextureSampler)>();
  494. for (int index = 0; index < keys.Length; index++)
  495. {
  496. foreach (TextureDescriptor desc in _gpu.Renderer.Shader.GetTextureUsage(keys[index]))
  497. {
  498. int textureHandle;
  499. if (desc.IsBindless)
  500. {
  501. long position = _constBuffers[index][desc.CbufSlot].Position;
  502. textureHandle = vmm.ReadInt32(position + desc.CbufOffset * 4);
  503. }
  504. else
  505. {
  506. long position = _constBuffers[index][textureCbIndex].Position;
  507. textureHandle = vmm.ReadInt32(position + desc.HandleIndex * 4);
  508. }
  509. unboundTextures.Add(UploadTexture(vmm, textureHandle));
  510. }
  511. }
  512. for (int index = 0; index < unboundTextures.Count; index++)
  513. {
  514. (long key, GalImage image, GalTextureSampler sampler) = unboundTextures[index];
  515. if (key == 0)
  516. {
  517. continue;
  518. }
  519. _gpu.Renderer.Texture.Bind(key, index, image);
  520. _gpu.Renderer.Texture.SetSampler(image, sampler);
  521. }
  522. Profile.End(Profiles.GPU.Engine3d.UploadTextures);
  523. }
  524. private (long, GalImage, GalTextureSampler) UploadTexture(NvGpuVmm vmm, int textureHandle)
  525. {
  526. if (textureHandle == 0)
  527. {
  528. // FIXME: Some games like puyo puyo will use handles with the value 0.
  529. // This is a bug, most likely caused by sync issues.
  530. return (0, default(GalImage), default(GalTextureSampler));
  531. }
  532. Profile.Begin(Profiles.GPU.Engine3d.UploadTexture);
  533. bool linkedTsc = ReadRegisterBool(NvGpuEngine3dReg.LinkedTsc);
  534. int ticIndex = (textureHandle >> 0) & 0xfffff;
  535. int tscIndex = linkedTsc ? ticIndex : (textureHandle >> 20) & 0xfff;
  536. long ticPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexHeaderPoolOffset);
  537. long tscPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexSamplerPoolOffset);
  538. ticPosition += ticIndex * 0x20;
  539. tscPosition += tscIndex * 0x20;
  540. GalImage image = TextureFactory.MakeTexture(vmm, ticPosition);
  541. GalTextureSampler sampler = TextureFactory.MakeSampler(_gpu, vmm, tscPosition);
  542. long key = vmm.ReadInt64(ticPosition + 4) & 0xffffffffffff;
  543. if (image.Layout == GalMemoryLayout.BlockLinear)
  544. {
  545. key &= ~0x1ffL;
  546. }
  547. else if (image.Layout == GalMemoryLayout.Pitch)
  548. {
  549. key &= ~0x1fL;
  550. }
  551. key = vmm.GetPhysicalAddress(key);
  552. if (key == -1)
  553. {
  554. Profile.End(Profiles.GPU.Engine3d.UploadTexture);
  555. // FIXME: Shouldn't ignore invalid addresses.
  556. return (0, default(GalImage), default(GalTextureSampler));
  557. }
  558. _gpu.ResourceManager.SendTexture(vmm, key, image);
  559. Profile.End(Profiles.GPU.Engine3d.UploadTexture);
  560. return (key, image, sampler);
  561. }
  562. private void UploadConstBuffers(NvGpuVmm vmm, GalPipelineState state, long[] keys)
  563. {
  564. Profile.Begin(Profiles.GPU.Engine3d.UploadConstBuffers);
  565. for (int stage = 0; stage < keys.Length; stage++)
  566. {
  567. foreach (CBufferDescriptor desc in _gpu.Renderer.Shader.GetConstBufferUsage(keys[stage]))
  568. {
  569. ConstBuffer cb = _constBuffers[stage][desc.Slot];
  570. if (!cb.Enabled)
  571. {
  572. continue;
  573. }
  574. long key = vmm.GetPhysicalAddress(cb.Position);
  575. if (_gpu.ResourceManager.MemoryRegionModified(vmm, key, cb.Size, NvGpuBufferType.ConstBuffer))
  576. {
  577. if (vmm.TryGetHostAddress(cb.Position, cb.Size, out IntPtr cbPtr))
  578. {
  579. _gpu.Renderer.Buffer.SetData(key, cb.Size, cbPtr);
  580. }
  581. else
  582. {
  583. _gpu.Renderer.Buffer.SetData(key, vmm.ReadBytes(cb.Position, cb.Size));
  584. }
  585. }
  586. state.ConstBufferKeys[stage][desc.Slot] = key;
  587. }
  588. }
  589. Profile.End(Profiles.GPU.Engine3d.UploadConstBuffers);
  590. }
  591. private void UploadVertexArrays(NvGpuVmm vmm, GalPipelineState state)
  592. {
  593. Profile.Begin(Profiles.GPU.Engine3d.UploadVertexArrays);
  594. long ibPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  595. long iboKey = vmm.GetPhysicalAddress(ibPosition);
  596. int indexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  597. int indexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  598. int primCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  599. GalPrimitiveType primType = (GalPrimitiveType)(primCtrl & 0xffff);
  600. GalIndexFormat indexFormat = (GalIndexFormat)indexEntryFmt;
  601. int indexEntrySize = 1 << indexEntryFmt;
  602. if (indexEntrySize > 4)
  603. {
  604. throw new InvalidOperationException("Invalid index entry size \"" + indexEntrySize + "\"!");
  605. }
  606. if (indexCount != 0)
  607. {
  608. int ibSize = indexCount * indexEntrySize;
  609. bool iboCached = _gpu.Renderer.Rasterizer.IsIboCached(iboKey, (uint)ibSize);
  610. bool usesLegacyQuads =
  611. primType == GalPrimitiveType.Quads ||
  612. primType == GalPrimitiveType.QuadStrip;
  613. if (!iboCached || _gpu.ResourceManager.MemoryRegionModified(vmm, iboKey, (uint)ibSize, NvGpuBufferType.Index))
  614. {
  615. if (!usesLegacyQuads)
  616. {
  617. if (vmm.TryGetHostAddress(ibPosition, ibSize, out IntPtr ibPtr))
  618. {
  619. _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, ibPtr);
  620. }
  621. else
  622. {
  623. _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, vmm.ReadBytes(ibPosition, ibSize));
  624. }
  625. }
  626. else
  627. {
  628. byte[] buffer = vmm.ReadBytes(ibPosition, ibSize);
  629. if (primType == GalPrimitiveType.Quads)
  630. {
  631. buffer = QuadHelper.ConvertQuadsToTris(buffer, indexEntrySize, indexCount);
  632. }
  633. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  634. {
  635. buffer = QuadHelper.ConvertQuadStripToTris(buffer, indexEntrySize, indexCount);
  636. }
  637. _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, buffer);
  638. }
  639. }
  640. if (!usesLegacyQuads)
  641. {
  642. _gpu.Renderer.Rasterizer.SetIndexArray(ibSize, indexFormat);
  643. }
  644. else
  645. {
  646. if (primType == GalPrimitiveType.Quads)
  647. {
  648. _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadsToTris(ibSize), indexFormat);
  649. }
  650. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  651. {
  652. _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadStripToTris(ibSize), indexFormat);
  653. }
  654. }
  655. }
  656. List<GalVertexAttrib>[] attribs = new List<GalVertexAttrib>[32];
  657. for (int attr = 0; attr < 16; attr++)
  658. {
  659. int packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + attr);
  660. int arrayIndex = packed & 0x1f;
  661. if (attribs[arrayIndex] == null)
  662. {
  663. attribs[arrayIndex] = new List<GalVertexAttrib>();
  664. }
  665. long vbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + arrayIndex * 4);
  666. if (vbPosition == 0)
  667. {
  668. continue;
  669. }
  670. bool isConst = ((packed >> 6) & 1) != 0;
  671. int offset = (packed >> 7) & 0x3fff;
  672. GalVertexAttribSize size = (GalVertexAttribSize)((packed >> 21) & 0x3f);
  673. GalVertexAttribType type = (GalVertexAttribType)((packed >> 27) & 0x7);
  674. bool isRgba = ((packed >> 31) & 1) != 0;
  675. // Check vertex array is enabled to avoid out of bounds exception when reading bytes
  676. bool enable = (ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + arrayIndex * 4) & 0x1000) != 0;
  677. // Note: 16 is the maximum size of an attribute,
  678. // having a component size of 32-bits with 4 elements (a vec4).
  679. if (enable)
  680. {
  681. byte[] data = vmm.ReadBytes(vbPosition + offset, 16);
  682. attribs[arrayIndex].Add(new GalVertexAttrib(attr, isConst, offset, data, size, type, isRgba));
  683. }
  684. }
  685. state.VertexBindings = new GalVertexBinding[32];
  686. for (int index = 0; index < 32; index++)
  687. {
  688. if (attribs[index] == null)
  689. {
  690. continue;
  691. }
  692. int control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + index * 4);
  693. bool enable = (control & 0x1000) != 0;
  694. if (!enable)
  695. {
  696. continue;
  697. }
  698. long vbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + index * 4);
  699. long vbEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + index * 2);
  700. int vertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + index * 4);
  701. bool instanced = ReadRegisterBool(NvGpuEngine3dReg.VertexArrayNInstance + index);
  702. int stride = control & 0xfff;
  703. if (instanced && vertexDivisor != 0)
  704. {
  705. vbPosition += stride * (_currentInstance / vertexDivisor);
  706. }
  707. if (vbPosition > vbEndPos)
  708. {
  709. // Instance is invalid, ignore the draw call
  710. continue;
  711. }
  712. long vboKey = vmm.GetPhysicalAddress(vbPosition);
  713. long vbSize = (vbEndPos - vbPosition) + 1;
  714. int modifiedVbSize = (int)vbSize;
  715. // If quads convert size to triangle length
  716. if (stride == 0)
  717. {
  718. if (primType == GalPrimitiveType.Quads)
  719. {
  720. modifiedVbSize = QuadHelper.ConvertSizeQuadsToTris(modifiedVbSize);
  721. }
  722. else if (primType == GalPrimitiveType.QuadStrip)
  723. {
  724. modifiedVbSize = QuadHelper.ConvertSizeQuadStripToTris(modifiedVbSize);
  725. }
  726. }
  727. bool vboCached = _gpu.Renderer.Rasterizer.IsVboCached(vboKey, modifiedVbSize);
  728. if (!vboCached || _gpu.ResourceManager.MemoryRegionModified(vmm, vboKey, vbSize, NvGpuBufferType.Vertex))
  729. {
  730. if ((primType == GalPrimitiveType.Quads | primType == GalPrimitiveType.QuadStrip) && stride != 0)
  731. {
  732. // Convert quad buffer to triangles
  733. byte[] data = vmm.ReadBytes(vbPosition, vbSize);
  734. if (primType == GalPrimitiveType.Quads)
  735. {
  736. data = QuadHelper.ConvertQuadsToTris(data, stride, (int)(vbSize / stride));
  737. }
  738. else
  739. {
  740. data = QuadHelper.ConvertQuadStripToTris(data, stride, (int)(vbSize / stride));
  741. }
  742. _gpu.Renderer.Rasterizer.CreateVbo(vboKey, data);
  743. }
  744. else if (vmm.TryGetHostAddress(vbPosition, vbSize, out IntPtr vbPtr))
  745. {
  746. _gpu.Renderer.Rasterizer.CreateVbo(vboKey, (int)vbSize, vbPtr);
  747. }
  748. else
  749. {
  750. _gpu.Renderer.Rasterizer.CreateVbo(vboKey, vmm.ReadBytes(vbPosition, vbSize));
  751. }
  752. }
  753. state.VertexBindings[index].Enabled = true;
  754. state.VertexBindings[index].Stride = stride;
  755. state.VertexBindings[index].VboKey = vboKey;
  756. state.VertexBindings[index].Instanced = instanced;
  757. state.VertexBindings[index].Divisor = vertexDivisor;
  758. state.VertexBindings[index].Attribs = attribs[index].ToArray();
  759. }
  760. Profile.End(Profiles.GPU.Engine3d.UploadVertexArrays);
  761. }
  762. private void DispatchRender(NvGpuVmm vmm, GalPipelineState state)
  763. {
  764. int indexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  765. int primCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  766. GalPrimitiveType primType = (GalPrimitiveType)(primCtrl & 0xffff);
  767. bool instanceNext = ((primCtrl >> 26) & 1) != 0;
  768. bool instanceCont = ((primCtrl >> 27) & 1) != 0;
  769. if (instanceNext && instanceCont)
  770. {
  771. throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time");
  772. }
  773. if (instanceNext)
  774. {
  775. _currentInstance++;
  776. }
  777. else if (!instanceCont)
  778. {
  779. _currentInstance = 0;
  780. }
  781. state.Instance = _currentInstance;
  782. _gpu.Renderer.Pipeline.Bind(state);
  783. _gpu.Renderer.RenderTarget.Bind();
  784. if (indexCount != 0)
  785. {
  786. int indexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  787. int indexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst);
  788. int vertexBase = ReadRegister(NvGpuEngine3dReg.VertexArrayElemBase);
  789. long indexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  790. long iboKey = vmm.GetPhysicalAddress(indexPosition);
  791. // Quad primitive types were deprecated on OpenGL 3.x,
  792. // they are converted to a triangles index buffer on IB creation,
  793. // so we should use the triangles type here too.
  794. if (primType == GalPrimitiveType.Quads || primType == GalPrimitiveType.QuadStrip)
  795. {
  796. // Note: We assume that index first points to the first
  797. // vertex of a quad, if it points to the middle of a
  798. // quad (First % 4 != 0 for Quads) then it will not work properly.
  799. if (primType == GalPrimitiveType.Quads)
  800. {
  801. indexFirst = QuadHelper.ConvertSizeQuadsToTris(indexFirst);
  802. }
  803. else // QuadStrip
  804. {
  805. indexFirst = QuadHelper.ConvertSizeQuadStripToTris(indexFirst);
  806. }
  807. primType = GalPrimitiveType.Triangles;
  808. }
  809. _gpu.Renderer.Rasterizer.DrawElements(iboKey, indexFirst, vertexBase, primType);
  810. }
  811. else
  812. {
  813. int vertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst);
  814. int vertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount);
  815. // Quad primitive types were deprecated on OpenGL 3.x,
  816. // they are converted to a triangles index buffer on IB creation,
  817. // so we should use the triangles type here too.
  818. if (primType == GalPrimitiveType.Quads || primType == GalPrimitiveType.QuadStrip)
  819. {
  820. // Note: We assume that index first points to the first
  821. // vertex of a quad, if it points to the middle of a
  822. // quad (First % 4 != 0 for Quads) then it will not work properly.
  823. if (primType == GalPrimitiveType.Quads)
  824. {
  825. vertexFirst = QuadHelper.ConvertSizeQuadsToTris(vertexFirst);
  826. }
  827. else // QuadStrip
  828. {
  829. vertexFirst = QuadHelper.ConvertSizeQuadStripToTris(vertexFirst);
  830. }
  831. primType = GalPrimitiveType.Triangles;
  832. vertexCount = QuadHelper.ConvertSizeQuadsToTris(vertexCount);
  833. }
  834. _gpu.Renderer.Rasterizer.DrawArrays(vertexFirst, vertexCount, primType);
  835. }
  836. // Reset pipeline for host OpenGL calls
  837. _gpu.Renderer.Pipeline.Unbind(state);
  838. // Is the GPU really clearing those registers after draw?
  839. WriteRegister(NvGpuEngine3dReg.IndexBatchFirst, 0);
  840. WriteRegister(NvGpuEngine3dReg.IndexBatchCount, 0);
  841. }
  842. private enum QueryMode
  843. {
  844. WriteSeq,
  845. Sync,
  846. WriteCounterAndTimestamp
  847. }
  848. private void QueryControl(NvGpuVmm vmm, GpuMethodCall methCall)
  849. {
  850. WriteRegister(methCall);
  851. long position = MakeInt64From2xInt32(NvGpuEngine3dReg.QueryAddress);
  852. int seq = Registers[(int)NvGpuEngine3dReg.QuerySequence];
  853. int ctrl = Registers[(int)NvGpuEngine3dReg.QueryControl];
  854. QueryMode mode = (QueryMode)(ctrl & 3);
  855. switch (mode)
  856. {
  857. case QueryMode.WriteSeq: vmm.WriteInt32(position, seq); break;
  858. case QueryMode.WriteCounterAndTimestamp:
  859. {
  860. // TODO: Implement counters.
  861. long counter = 1;
  862. long timestamp = PerformanceCounter.ElapsedMilliseconds;
  863. vmm.WriteInt64(position + 0, counter);
  864. vmm.WriteInt64(position + 8, timestamp);
  865. break;
  866. }
  867. }
  868. }
  869. private void CbData(NvGpuVmm vmm, GpuMethodCall methCall)
  870. {
  871. long position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  872. int offset = ReadRegister(NvGpuEngine3dReg.ConstBufferOffset);
  873. vmm.WriteInt32(position + offset, methCall.Argument);
  874. WriteRegister(NvGpuEngine3dReg.ConstBufferOffset, offset + 4);
  875. _gpu.ResourceManager.ClearPbCache(NvGpuBufferType.ConstBuffer);
  876. }
  877. private void CbBind(NvGpuVmm vmm, GpuMethodCall methCall)
  878. {
  879. int stage = (methCall.Method - 0x904) >> 3;
  880. int index = methCall.Argument;
  881. bool enabled = (index & 1) != 0;
  882. index = (index >> 4) & 0x1f;
  883. long position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  884. long cbKey = vmm.GetPhysicalAddress(position);
  885. int size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize);
  886. if (!_gpu.Renderer.Buffer.IsCached(cbKey, size))
  887. {
  888. _gpu.Renderer.Buffer.Create(cbKey, size);
  889. }
  890. ConstBuffer cb = _constBuffers[stage][index];
  891. if (cb.Position != position || cb.Enabled != enabled || cb.Size != size)
  892. {
  893. _constBuffers[stage][index].Position = position;
  894. _constBuffers[stage][index].Enabled = enabled;
  895. _constBuffers[stage][index].Size = size;
  896. }
  897. }
  898. private float GetFlipSign(NvGpuEngine3dReg reg)
  899. {
  900. return MathF.Sign(ReadRegisterFloat(reg));
  901. }
  902. private long MakeInt64From2xInt32(NvGpuEngine3dReg reg)
  903. {
  904. return
  905. (long)Registers[(int)reg + 0] << 32 |
  906. (uint)Registers[(int)reg + 1];
  907. }
  908. private void WriteRegister(GpuMethodCall methCall)
  909. {
  910. Registers[methCall.Method] = methCall.Argument;
  911. }
  912. private int ReadRegister(NvGpuEngine3dReg reg)
  913. {
  914. return Registers[(int)reg];
  915. }
  916. private float ReadRegisterFloat(NvGpuEngine3dReg reg)
  917. {
  918. return BitConverter.Int32BitsToSingle(ReadRegister(reg));
  919. }
  920. private bool ReadRegisterBool(NvGpuEngine3dReg reg)
  921. {
  922. return (ReadRegister(reg) & 1) != 0;
  923. }
  924. private void WriteRegister(NvGpuEngine3dReg reg, int value)
  925. {
  926. Registers[(int)reg] = value;
  927. }
  928. }
  929. }