NvGpuEngine3d.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Gal;
  3. using Ryujinx.Graphics.Memory;
  4. using Ryujinx.Graphics.Texture;
  5. using System;
  6. using System.Collections.Generic;
  7. namespace Ryujinx.Graphics.Graphics3d
  8. {
  9. class NvGpuEngine3d : INvGpuEngine
  10. {
  11. public int[] Registers { get; private set; }
  12. private NvGpu Gpu;
  13. private Dictionary<int, NvGpuMethod> Methods;
  14. private struct ConstBuffer
  15. {
  16. public bool Enabled;
  17. public long Position;
  18. public int Size;
  19. }
  20. private ConstBuffer[][] ConstBuffers;
  21. private int CurrentInstance = 0;
  22. public NvGpuEngine3d(NvGpu Gpu)
  23. {
  24. this.Gpu = Gpu;
  25. Registers = new int[0xe00];
  26. Methods = new Dictionary<int, NvGpuMethod>();
  27. void AddMethod(int Meth, int Count, int Stride, NvGpuMethod Method)
  28. {
  29. while (Count-- > 0)
  30. {
  31. Methods.Add(Meth, Method);
  32. Meth += Stride;
  33. }
  34. }
  35. AddMethod(0x585, 1, 1, VertexEndGl);
  36. AddMethod(0x674, 1, 1, ClearBuffers);
  37. AddMethod(0x6c3, 1, 1, QueryControl);
  38. AddMethod(0x8e4, 16, 1, CbData);
  39. AddMethod(0x904, 5, 8, CbBind);
  40. ConstBuffers = new ConstBuffer[6][];
  41. for (int Index = 0; Index < ConstBuffers.Length; Index++)
  42. {
  43. ConstBuffers[Index] = new ConstBuffer[18];
  44. }
  45. //Ensure that all components are enabled by default.
  46. //FIXME: Is this correct?
  47. WriteRegister(NvGpuEngine3dReg.ColorMaskN, 0x1111);
  48. WriteRegister(NvGpuEngine3dReg.FrameBufferSrgb, 1);
  49. for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++)
  50. {
  51. WriteRegister(NvGpuEngine3dReg.IBlendNEquationRgb + Index * 8, (int)GalBlendEquation.FuncAdd);
  52. WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb + Index * 8, (int)GalBlendFactor.One);
  53. WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb + Index * 8, (int)GalBlendFactor.Zero);
  54. WriteRegister(NvGpuEngine3dReg.IBlendNEquationAlpha + Index * 8, (int)GalBlendEquation.FuncAdd);
  55. WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha + Index * 8, (int)GalBlendFactor.One);
  56. WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha + Index * 8, (int)GalBlendFactor.Zero);
  57. }
  58. }
  59. public void CallMethod(NvGpuVmm Vmm, GpuMethodCall MethCall)
  60. {
  61. if (Methods.TryGetValue(MethCall.Method, out NvGpuMethod Method))
  62. {
  63. Method(Vmm, MethCall);
  64. }
  65. else
  66. {
  67. WriteRegister(MethCall);
  68. }
  69. }
  70. private void VertexEndGl(NvGpuVmm Vmm, GpuMethodCall MethCall)
  71. {
  72. LockCaches();
  73. GalPipelineState State = new GalPipelineState();
  74. SetFrameBuffer(State);
  75. SetFrontFace(State);
  76. SetCullFace(State);
  77. SetDepth(State);
  78. SetStencil(State);
  79. SetBlending(State);
  80. SetColorMask(State);
  81. SetPrimitiveRestart(State);
  82. for (int FbIndex = 0; FbIndex < 8; FbIndex++)
  83. {
  84. SetFrameBuffer(Vmm, FbIndex);
  85. }
  86. SetZeta(Vmm);
  87. SetRenderTargets();
  88. long[] Keys = UploadShaders(Vmm);
  89. Gpu.Renderer.Shader.BindProgram();
  90. UploadTextures(Vmm, State, Keys);
  91. UploadConstBuffers(Vmm, State, Keys);
  92. UploadVertexArrays(Vmm, State);
  93. DispatchRender(Vmm, State);
  94. UnlockCaches();
  95. }
  96. private void LockCaches()
  97. {
  98. Gpu.Renderer.Buffer.LockCache();
  99. Gpu.Renderer.Rasterizer.LockCaches();
  100. Gpu.Renderer.Texture.LockCache();
  101. }
  102. private void UnlockCaches()
  103. {
  104. Gpu.Renderer.Buffer.UnlockCache();
  105. Gpu.Renderer.Rasterizer.UnlockCaches();
  106. Gpu.Renderer.Texture.UnlockCache();
  107. }
  108. private void ClearBuffers(NvGpuVmm Vmm, GpuMethodCall MethCall)
  109. {
  110. int Attachment = (MethCall.Argument >> 6) & 0xf;
  111. GalClearBufferFlags Flags = (GalClearBufferFlags)(MethCall.Argument & 0x3f);
  112. float Red = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 0);
  113. float Green = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 1);
  114. float Blue = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 2);
  115. float Alpha = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 3);
  116. float Depth = ReadRegisterFloat(NvGpuEngine3dReg.ClearDepth);
  117. int Stencil = ReadRegister(NvGpuEngine3dReg.ClearStencil);
  118. SetFrameBuffer(Vmm, Attachment);
  119. SetZeta(Vmm);
  120. SetRenderTargets();
  121. Gpu.Renderer.RenderTarget.Bind();
  122. Gpu.Renderer.Rasterizer.ClearBuffers(Flags, Attachment, Red, Green, Blue, Alpha, Depth, Stencil);
  123. Gpu.Renderer.Pipeline.ResetDepthMask();
  124. Gpu.Renderer.Pipeline.ResetColorMask(Attachment);
  125. }
  126. private void SetFrameBuffer(NvGpuVmm Vmm, int FbIndex)
  127. {
  128. long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.FrameBufferNAddress + FbIndex * 0x10);
  129. int SurfFormat = ReadRegister(NvGpuEngine3dReg.FrameBufferNFormat + FbIndex * 0x10);
  130. if (VA == 0 || SurfFormat == 0)
  131. {
  132. Gpu.Renderer.RenderTarget.UnbindColor(FbIndex);
  133. return;
  134. }
  135. long Key = Vmm.GetPhysicalAddress(VA);
  136. int Width = ReadRegister(NvGpuEngine3dReg.FrameBufferNWidth + FbIndex * 0x10);
  137. int Height = ReadRegister(NvGpuEngine3dReg.FrameBufferNHeight + FbIndex * 0x10);
  138. int BlockDim = ReadRegister(NvGpuEngine3dReg.FrameBufferNBlockDim + FbIndex * 0x10);
  139. int GobBlockHeight = 1 << ((BlockDim >> 4) & 7);
  140. GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1);
  141. float TX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateX + FbIndex * 8);
  142. float TY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateY + FbIndex * 8);
  143. float SX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleX + FbIndex * 8);
  144. float SY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleY + FbIndex * 8);
  145. int VpX = (int)MathF.Max(0, TX - MathF.Abs(SX));
  146. int VpY = (int)MathF.Max(0, TY - MathF.Abs(SY));
  147. int VpW = (int)(TX + MathF.Abs(SX)) - VpX;
  148. int VpH = (int)(TY + MathF.Abs(SY)) - VpY;
  149. GalImageFormat Format = ImageUtils.ConvertSurface((GalSurfaceFormat)SurfFormat);
  150. GalImage Image = new GalImage(Width, Height, 1, GobBlockHeight, Layout, Format);
  151. Gpu.ResourceManager.SendColorBuffer(Vmm, Key, FbIndex, Image);
  152. Gpu.Renderer.RenderTarget.SetViewport(FbIndex, VpX, VpY, VpW, VpH);
  153. }
  154. private void SetFrameBuffer(GalPipelineState State)
  155. {
  156. State.FramebufferSrgb = ReadRegisterBool(NvGpuEngine3dReg.FrameBufferSrgb);
  157. State.FlipX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  158. State.FlipY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  159. int ScreenYControl = ReadRegister(NvGpuEngine3dReg.ScreenYControl);
  160. bool NegateY = (ScreenYControl & 1) != 0;
  161. if (NegateY)
  162. {
  163. State.FlipY = -State.FlipY;
  164. }
  165. }
  166. private void SetZeta(NvGpuVmm Vmm)
  167. {
  168. long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.ZetaAddress);
  169. int ZetaFormat = ReadRegister(NvGpuEngine3dReg.ZetaFormat);
  170. int BlockDim = ReadRegister(NvGpuEngine3dReg.ZetaBlockDimensions);
  171. int GobBlockHeight = 1 << ((BlockDim >> 4) & 7);
  172. GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1); //?
  173. bool ZetaEnable = ReadRegisterBool(NvGpuEngine3dReg.ZetaEnable);
  174. if (VA == 0 || ZetaFormat == 0 || !ZetaEnable)
  175. {
  176. Gpu.Renderer.RenderTarget.UnbindZeta();
  177. return;
  178. }
  179. long Key = Vmm.GetPhysicalAddress(VA);
  180. int Width = ReadRegister(NvGpuEngine3dReg.ZetaHoriz);
  181. int Height = ReadRegister(NvGpuEngine3dReg.ZetaVert);
  182. GalImageFormat Format = ImageUtils.ConvertZeta((GalZetaFormat)ZetaFormat);
  183. GalImage Image = new GalImage(Width, Height, 1, GobBlockHeight, Layout, Format);
  184. Gpu.ResourceManager.SendZetaBuffer(Vmm, Key, Image);
  185. }
  186. private long[] UploadShaders(NvGpuVmm Vmm)
  187. {
  188. long[] Keys = new long[5];
  189. long BasePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  190. int Index = 1;
  191. int VpAControl = ReadRegister(NvGpuEngine3dReg.ShaderNControl);
  192. bool VpAEnable = (VpAControl & 1) != 0;
  193. if (VpAEnable)
  194. {
  195. //Note: The maxwell supports 2 vertex programs, usually
  196. //only VP B is used, but in some cases VP A is also used.
  197. //In this case, it seems to function as an extra vertex
  198. //shader stage.
  199. //The graphics abstraction layer has a special overload for this
  200. //case, which should merge the two shaders into one vertex shader.
  201. int VpAOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset);
  202. int VpBOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + 0x10);
  203. long VpAPos = BasePosition + (uint)VpAOffset;
  204. long VpBPos = BasePosition + (uint)VpBOffset;
  205. Keys[(int)GalShaderType.Vertex] = VpBPos;
  206. Gpu.Renderer.Shader.Create(Vmm, VpAPos, VpBPos, GalShaderType.Vertex);
  207. Gpu.Renderer.Shader.Bind(VpBPos);
  208. Index = 2;
  209. }
  210. for (; Index < 6; Index++)
  211. {
  212. GalShaderType Type = GetTypeFromProgram(Index);
  213. int Control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + Index * 0x10);
  214. int Offset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + Index * 0x10);
  215. //Note: Vertex Program (B) is always enabled.
  216. bool Enable = (Control & 1) != 0 || Index == 1;
  217. if (!Enable)
  218. {
  219. Gpu.Renderer.Shader.Unbind(Type);
  220. continue;
  221. }
  222. long Key = BasePosition + (uint)Offset;
  223. Keys[(int)Type] = Key;
  224. Gpu.Renderer.Shader.Create(Vmm, Key, Type);
  225. Gpu.Renderer.Shader.Bind(Key);
  226. }
  227. return Keys;
  228. }
  229. private static GalShaderType GetTypeFromProgram(int Program)
  230. {
  231. switch (Program)
  232. {
  233. case 0:
  234. case 1: return GalShaderType.Vertex;
  235. case 2: return GalShaderType.TessControl;
  236. case 3: return GalShaderType.TessEvaluation;
  237. case 4: return GalShaderType.Geometry;
  238. case 5: return GalShaderType.Fragment;
  239. }
  240. throw new ArgumentOutOfRangeException(nameof(Program));
  241. }
  242. private void SetFrontFace(GalPipelineState State)
  243. {
  244. float SignX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  245. float SignY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  246. GalFrontFace FrontFace = (GalFrontFace)ReadRegister(NvGpuEngine3dReg.FrontFace);
  247. //Flipping breaks facing. Flipping front facing too fixes it
  248. if (SignX != SignY)
  249. {
  250. switch (FrontFace)
  251. {
  252. case GalFrontFace.CW: FrontFace = GalFrontFace.CCW; break;
  253. case GalFrontFace.CCW: FrontFace = GalFrontFace.CW; break;
  254. }
  255. }
  256. State.FrontFace = FrontFace;
  257. }
  258. private void SetCullFace(GalPipelineState State)
  259. {
  260. State.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable);
  261. if (State.CullFaceEnabled)
  262. {
  263. State.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace);
  264. }
  265. }
  266. private void SetDepth(GalPipelineState State)
  267. {
  268. State.DepthTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthTestEnable);
  269. State.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable);
  270. if (State.DepthTestEnabled)
  271. {
  272. State.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction);
  273. }
  274. State.DepthRangeNear = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNNear);
  275. State.DepthRangeFar = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNFar);
  276. }
  277. private void SetStencil(GalPipelineState State)
  278. {
  279. State.StencilTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.StencilEnable);
  280. if (State.StencilTestEnabled)
  281. {
  282. State.StencilBackFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilBackFuncFunc);
  283. State.StencilBackFuncRef = ReadRegister(NvGpuEngine3dReg.StencilBackFuncRef);
  284. State.StencilBackFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackFuncMask);
  285. State.StencilBackOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpFail);
  286. State.StencilBackOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZFail);
  287. State.StencilBackOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZPass);
  288. State.StencilBackMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackMask);
  289. State.StencilFrontFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncFunc);
  290. State.StencilFrontFuncRef = ReadRegister(NvGpuEngine3dReg.StencilFrontFuncRef);
  291. State.StencilFrontFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncMask);
  292. State.StencilFrontOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpFail);
  293. State.StencilFrontOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZFail);
  294. State.StencilFrontOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZPass);
  295. State.StencilFrontMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontMask);
  296. }
  297. }
  298. private void SetBlending(GalPipelineState State)
  299. {
  300. bool BlendIndependent = ReadRegisterBool(NvGpuEngine3dReg.BlendIndependent);
  301. State.BlendIndependent = BlendIndependent;
  302. for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++)
  303. {
  304. if (BlendIndependent)
  305. {
  306. State.Blends[Index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable + Index);
  307. if (State.Blends[Index].Enabled)
  308. {
  309. State.Blends[Index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha + Index * 8);
  310. State.Blends[Index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationRgb + Index * 8);
  311. State.Blends[Index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcRgb + Index * 8);
  312. State.Blends[Index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstRgb + Index * 8);
  313. State.Blends[Index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationAlpha + Index * 8);
  314. State.Blends[Index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcAlpha + Index * 8);
  315. State.Blends[Index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstAlpha + Index * 8);
  316. }
  317. }
  318. else
  319. {
  320. //It seems that even when independent blend is disabled, the first IBlend enable
  321. //register is still set to indicate whenever blend is enabled or not (?).
  322. State.Blends[Index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable);
  323. if (State.Blends[Index].Enabled)
  324. {
  325. State.Blends[Index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.BlendSeparateAlpha);
  326. State.Blends[Index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationRgb);
  327. State.Blends[Index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcRgb);
  328. State.Blends[Index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstRgb);
  329. State.Blends[Index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationAlpha);
  330. State.Blends[Index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcAlpha);
  331. State.Blends[Index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstAlpha);
  332. }
  333. }
  334. }
  335. }
  336. private GalBlendEquation ReadBlendEquation(NvGpuEngine3dReg Register)
  337. {
  338. return (GalBlendEquation)ReadRegister(Register);
  339. }
  340. private GalBlendFactor ReadBlendFactor(NvGpuEngine3dReg Register)
  341. {
  342. return (GalBlendFactor)ReadRegister(Register);
  343. }
  344. private void SetColorMask(GalPipelineState State)
  345. {
  346. bool ColorMaskCommon = ReadRegisterBool(NvGpuEngine3dReg.ColorMaskCommon);
  347. State.ColorMaskCommon = ColorMaskCommon;
  348. for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++)
  349. {
  350. int ColorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + (ColorMaskCommon ? 0 : Index));
  351. State.ColorMasks[Index].Red = ((ColorMask >> 0) & 0xf) != 0;
  352. State.ColorMasks[Index].Green = ((ColorMask >> 4) & 0xf) != 0;
  353. State.ColorMasks[Index].Blue = ((ColorMask >> 8) & 0xf) != 0;
  354. State.ColorMasks[Index].Alpha = ((ColorMask >> 12) & 0xf) != 0;
  355. }
  356. }
  357. private void SetPrimitiveRestart(GalPipelineState State)
  358. {
  359. State.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable);
  360. if (State.PrimitiveRestartEnabled)
  361. {
  362. State.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex);
  363. }
  364. }
  365. private void SetRenderTargets()
  366. {
  367. //Commercial games do not seem to
  368. //bool SeparateFragData = ReadRegisterBool(NvGpuEngine3dReg.RTSeparateFragData);
  369. uint Control = (uint)(ReadRegister(NvGpuEngine3dReg.RTControl));
  370. uint Count = Control & 0xf;
  371. if (Count > 0)
  372. {
  373. int[] Map = new int[Count];
  374. for (int Index = 0; Index < Count; Index++)
  375. {
  376. int Shift = 4 + Index * 3;
  377. Map[Index] = (int)((Control >> Shift) & 7);
  378. }
  379. Gpu.Renderer.RenderTarget.SetMap(Map);
  380. }
  381. else
  382. {
  383. Gpu.Renderer.RenderTarget.SetMap(null);
  384. }
  385. }
  386. private void UploadTextures(NvGpuVmm Vmm, GalPipelineState State, long[] Keys)
  387. {
  388. long BaseShPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  389. int TextureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex);
  390. List<(long, GalImage, GalTextureSampler)> UnboundTextures = new List<(long, GalImage, GalTextureSampler)>();
  391. for (int Index = 0; Index < Keys.Length; Index++)
  392. {
  393. foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetTextureUsage(Keys[Index]))
  394. {
  395. long Position;
  396. if (DeclInfo.IsCb)
  397. {
  398. Position = ConstBuffers[Index][DeclInfo.Cbuf].Position;
  399. }
  400. else
  401. {
  402. Position = ConstBuffers[Index][TextureCbIndex].Position;
  403. }
  404. int TextureHandle = Vmm.ReadInt32(Position + DeclInfo.Index * 4);
  405. UnboundTextures.Add(UploadTexture(Vmm, TextureHandle));
  406. }
  407. }
  408. for (int Index = 0; Index < UnboundTextures.Count; Index++)
  409. {
  410. (long Key, GalImage Image, GalTextureSampler Sampler) = UnboundTextures[Index];
  411. if (Key == 0)
  412. {
  413. continue;
  414. }
  415. Gpu.Renderer.Texture.Bind(Key, Index, Image);
  416. Gpu.Renderer.Texture.SetSampler(Sampler);
  417. }
  418. }
  419. private (long, GalImage, GalTextureSampler) UploadTexture(NvGpuVmm Vmm, int TextureHandle)
  420. {
  421. if (TextureHandle == 0)
  422. {
  423. //FIXME: Some games like puyo puyo will use handles with the value 0.
  424. //This is a bug, most likely caused by sync issues.
  425. return (0, default(GalImage), default(GalTextureSampler));
  426. }
  427. bool LinkedTsc = ReadRegisterBool(NvGpuEngine3dReg.LinkedTsc);
  428. int TicIndex = (TextureHandle >> 0) & 0xfffff;
  429. int TscIndex = LinkedTsc ? TicIndex : (TextureHandle >> 20) & 0xfff;
  430. long TicPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexHeaderPoolOffset);
  431. long TscPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexSamplerPoolOffset);
  432. TicPosition += TicIndex * 0x20;
  433. TscPosition += TscIndex * 0x20;
  434. GalImage Image = TextureFactory.MakeTexture(Vmm, TicPosition);
  435. GalTextureSampler Sampler = TextureFactory.MakeSampler(Gpu, Vmm, TscPosition);
  436. long Key = Vmm.ReadInt64(TicPosition + 4) & 0xffffffffffff;
  437. if (Image.Layout == GalMemoryLayout.BlockLinear)
  438. {
  439. Key &= ~0x1ffL;
  440. }
  441. else if (Image.Layout == GalMemoryLayout.Pitch)
  442. {
  443. Key &= ~0x1fL;
  444. }
  445. Key = Vmm.GetPhysicalAddress(Key);
  446. if (Key == -1)
  447. {
  448. //FIXME: Shouldn't ignore invalid addresses.
  449. return (0, default(GalImage), default(GalTextureSampler));
  450. }
  451. Gpu.ResourceManager.SendTexture(Vmm, Key, Image);
  452. return (Key, Image, Sampler);
  453. }
  454. private void UploadConstBuffers(NvGpuVmm Vmm, GalPipelineState State, long[] Keys)
  455. {
  456. for (int Stage = 0; Stage < Keys.Length; Stage++)
  457. {
  458. foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetConstBufferUsage(Keys[Stage]))
  459. {
  460. ConstBuffer Cb = ConstBuffers[Stage][DeclInfo.Cbuf];
  461. if (!Cb.Enabled)
  462. {
  463. continue;
  464. }
  465. long Key = Vmm.GetPhysicalAddress(Cb.Position);
  466. if (Gpu.ResourceManager.MemoryRegionModified(Vmm, Key, Cb.Size, NvGpuBufferType.ConstBuffer))
  467. {
  468. if (Vmm.TryGetHostAddress(Cb.Position, Cb.Size, out IntPtr CbPtr))
  469. {
  470. Gpu.Renderer.Buffer.SetData(Key, Cb.Size, CbPtr);
  471. }
  472. else
  473. {
  474. Gpu.Renderer.Buffer.SetData(Key, Vmm.ReadBytes(Cb.Position, Cb.Size));
  475. }
  476. }
  477. State.ConstBufferKeys[Stage][DeclInfo.Cbuf] = Key;
  478. }
  479. }
  480. }
  481. private void UploadVertexArrays(NvGpuVmm Vmm, GalPipelineState State)
  482. {
  483. long IbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  484. long IboKey = Vmm.GetPhysicalAddress(IbPosition);
  485. int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  486. int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  487. int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  488. GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff);
  489. GalIndexFormat IndexFormat = (GalIndexFormat)IndexEntryFmt;
  490. int IndexEntrySize = 1 << IndexEntryFmt;
  491. if (IndexEntrySize > 4)
  492. {
  493. throw new InvalidOperationException("Invalid index entry size \"" + IndexEntrySize + "\"!");
  494. }
  495. if (IndexCount != 0)
  496. {
  497. int IbSize = IndexCount * IndexEntrySize;
  498. bool IboCached = Gpu.Renderer.Rasterizer.IsIboCached(IboKey, (uint)IbSize);
  499. bool UsesLegacyQuads =
  500. PrimType == GalPrimitiveType.Quads ||
  501. PrimType == GalPrimitiveType.QuadStrip;
  502. if (!IboCached || Gpu.ResourceManager.MemoryRegionModified(Vmm, IboKey, (uint)IbSize, NvGpuBufferType.Index))
  503. {
  504. if (!UsesLegacyQuads)
  505. {
  506. if (Vmm.TryGetHostAddress(IbPosition, IbSize, out IntPtr IbPtr))
  507. {
  508. Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, IbPtr);
  509. }
  510. else
  511. {
  512. Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, Vmm.ReadBytes(IbPosition, IbSize));
  513. }
  514. }
  515. else
  516. {
  517. byte[] Buffer = Vmm.ReadBytes(IbPosition, IbSize);
  518. if (PrimType == GalPrimitiveType.Quads)
  519. {
  520. Buffer = QuadHelper.ConvertQuadsToTris(Buffer, IndexEntrySize, IndexCount);
  521. }
  522. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  523. {
  524. Buffer = QuadHelper.ConvertQuadStripToTris(Buffer, IndexEntrySize, IndexCount);
  525. }
  526. Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, Buffer);
  527. }
  528. }
  529. if (!UsesLegacyQuads)
  530. {
  531. Gpu.Renderer.Rasterizer.SetIndexArray(IbSize, IndexFormat);
  532. }
  533. else
  534. {
  535. if (PrimType == GalPrimitiveType.Quads)
  536. {
  537. Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadsToTris(IbSize), IndexFormat);
  538. }
  539. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  540. {
  541. Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadStripToTris(IbSize), IndexFormat);
  542. }
  543. }
  544. }
  545. List<GalVertexAttrib>[] Attribs = new List<GalVertexAttrib>[32];
  546. for (int Attr = 0; Attr < 16; Attr++)
  547. {
  548. int Packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + Attr);
  549. int ArrayIndex = Packed & 0x1f;
  550. if (Attribs[ArrayIndex] == null)
  551. {
  552. Attribs[ArrayIndex] = new List<GalVertexAttrib>();
  553. }
  554. long VbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + ArrayIndex * 4);
  555. if (VbPosition == 0)
  556. {
  557. continue;
  558. }
  559. bool IsConst = ((Packed >> 6) & 1) != 0;
  560. int Offset = (Packed >> 7) & 0x3fff;
  561. GalVertexAttribSize Size = (GalVertexAttribSize)((Packed >> 21) & 0x3f);
  562. GalVertexAttribType Type = (GalVertexAttribType)((Packed >> 27) & 0x7);
  563. bool IsRgba = ((Packed >> 31) & 1) != 0;
  564. //Note: 16 is the maximum size of an attribute,
  565. //having a component size of 32-bits with 4 elements (a vec4).
  566. byte[] Data = Vmm.ReadBytes(VbPosition + Offset, 16);
  567. Attribs[ArrayIndex].Add(new GalVertexAttrib(Attr, IsConst, Offset, Data, Size, Type, IsRgba));
  568. }
  569. State.VertexBindings = new GalVertexBinding[32];
  570. for (int Index = 0; Index < 32; Index++)
  571. {
  572. if (Attribs[Index] == null)
  573. {
  574. continue;
  575. }
  576. int Control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + Index * 4);
  577. bool Enable = (Control & 0x1000) != 0;
  578. if (!Enable)
  579. {
  580. continue;
  581. }
  582. long VbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + Index * 4);
  583. long VbEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + Index * 2);
  584. int VertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + Index * 4);
  585. bool Instanced = ReadRegisterBool(NvGpuEngine3dReg.VertexArrayNInstance + Index);
  586. int Stride = Control & 0xfff;
  587. if (Instanced && VertexDivisor != 0)
  588. {
  589. VbPosition += Stride * (CurrentInstance / VertexDivisor);
  590. }
  591. if (VbPosition > VbEndPos)
  592. {
  593. //Instance is invalid, ignore the draw call
  594. continue;
  595. }
  596. long VboKey = Vmm.GetPhysicalAddress(VbPosition);
  597. long VbSize = (VbEndPos - VbPosition) + 1;
  598. int ModifiedVbSize = (int)VbSize;
  599. // If quads convert size to triangle length
  600. if (Stride == 0)
  601. {
  602. if (PrimType == GalPrimitiveType.Quads)
  603. {
  604. ModifiedVbSize = QuadHelper.ConvertSizeQuadsToTris(ModifiedVbSize);
  605. }
  606. else if (PrimType == GalPrimitiveType.QuadStrip)
  607. {
  608. ModifiedVbSize = QuadHelper.ConvertSizeQuadStripToTris(ModifiedVbSize);
  609. }
  610. }
  611. bool VboCached = Gpu.Renderer.Rasterizer.IsVboCached(VboKey, ModifiedVbSize);
  612. if (!VboCached || Gpu.ResourceManager.MemoryRegionModified(Vmm, VboKey, VbSize, NvGpuBufferType.Vertex))
  613. {
  614. if ((PrimType == GalPrimitiveType.Quads | PrimType == GalPrimitiveType.QuadStrip) && Stride != 0)
  615. {
  616. // Convert quad buffer to triangles
  617. byte[] data = Vmm.ReadBytes(VbPosition, VbSize);
  618. if (PrimType == GalPrimitiveType.Quads)
  619. {
  620. data = QuadHelper.ConvertQuadsToTris(data, Stride, (int)(VbSize / Stride));
  621. }
  622. else
  623. {
  624. data = QuadHelper.ConvertQuadStripToTris(data, Stride, (int)(VbSize / Stride));
  625. }
  626. Gpu.Renderer.Rasterizer.CreateVbo(VboKey, data);
  627. }
  628. else if (Vmm.TryGetHostAddress(VbPosition, VbSize, out IntPtr VbPtr))
  629. {
  630. Gpu.Renderer.Rasterizer.CreateVbo(VboKey, (int)VbSize, VbPtr);
  631. }
  632. else
  633. {
  634. Gpu.Renderer.Rasterizer.CreateVbo(VboKey, Vmm.ReadBytes(VbPosition, VbSize));
  635. }
  636. }
  637. State.VertexBindings[Index].Enabled = true;
  638. State.VertexBindings[Index].Stride = Stride;
  639. State.VertexBindings[Index].VboKey = VboKey;
  640. State.VertexBindings[Index].Instanced = Instanced;
  641. State.VertexBindings[Index].Divisor = VertexDivisor;
  642. State.VertexBindings[Index].Attribs = Attribs[Index].ToArray();
  643. }
  644. }
  645. private void DispatchRender(NvGpuVmm Vmm, GalPipelineState State)
  646. {
  647. int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  648. int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  649. GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff);
  650. bool InstanceNext = ((PrimCtrl >> 26) & 1) != 0;
  651. bool InstanceCont = ((PrimCtrl >> 27) & 1) != 0;
  652. if (InstanceNext && InstanceCont)
  653. {
  654. throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time");
  655. }
  656. if (InstanceNext)
  657. {
  658. CurrentInstance++;
  659. }
  660. else if (!InstanceCont)
  661. {
  662. CurrentInstance = 0;
  663. }
  664. State.Instance = CurrentInstance;
  665. Gpu.Renderer.Pipeline.Bind(State);
  666. Gpu.Renderer.RenderTarget.Bind();
  667. if (IndexCount != 0)
  668. {
  669. int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  670. int IndexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst);
  671. int VertexBase = ReadRegister(NvGpuEngine3dReg.VertexArrayElemBase);
  672. long IndexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  673. long IboKey = Vmm.GetPhysicalAddress(IndexPosition);
  674. //Quad primitive types were deprecated on OpenGL 3.x,
  675. //they are converted to a triangles index buffer on IB creation,
  676. //so we should use the triangles type here too.
  677. if (PrimType == GalPrimitiveType.Quads || PrimType == GalPrimitiveType.QuadStrip)
  678. {
  679. //Note: We assume that index first points to the first
  680. //vertex of a quad, if it points to the middle of a
  681. //quad (First % 4 != 0 for Quads) then it will not work properly.
  682. if (PrimType == GalPrimitiveType.Quads)
  683. {
  684. IndexFirst = QuadHelper.ConvertSizeQuadsToTris(IndexFirst);
  685. }
  686. else // QuadStrip
  687. {
  688. IndexFirst = QuadHelper.ConvertSizeQuadStripToTris(IndexFirst);
  689. }
  690. PrimType = GalPrimitiveType.Triangles;
  691. }
  692. Gpu.Renderer.Rasterizer.DrawElements(IboKey, IndexFirst, VertexBase, PrimType);
  693. }
  694. else
  695. {
  696. int VertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst);
  697. int VertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount);
  698. //Quad primitive types were deprecated on OpenGL 3.x,
  699. //they are converted to a triangles index buffer on IB creation,
  700. //so we should use the triangles type here too.
  701. if (PrimType == GalPrimitiveType.Quads || PrimType == GalPrimitiveType.QuadStrip)
  702. {
  703. //Note: We assume that index first points to the first
  704. //vertex of a quad, if it points to the middle of a
  705. //quad (First % 4 != 0 for Quads) then it will not work properly.
  706. if (PrimType == GalPrimitiveType.Quads)
  707. {
  708. VertexFirst = QuadHelper.ConvertSizeQuadsToTris(VertexFirst);
  709. }
  710. else // QuadStrip
  711. {
  712. VertexFirst = QuadHelper.ConvertSizeQuadStripToTris(VertexFirst);
  713. }
  714. PrimType = GalPrimitiveType.Triangles;
  715. VertexCount = QuadHelper.ConvertSizeQuadsToTris(VertexCount);
  716. }
  717. Gpu.Renderer.Rasterizer.DrawArrays(VertexFirst, VertexCount, PrimType);
  718. }
  719. //Is the GPU really clearing those registers after draw?
  720. WriteRegister(NvGpuEngine3dReg.IndexBatchFirst, 0);
  721. WriteRegister(NvGpuEngine3dReg.IndexBatchCount, 0);
  722. }
  723. private enum QueryMode
  724. {
  725. WriteSeq,
  726. Sync,
  727. WriteCounterAndTimestamp
  728. }
  729. private void QueryControl(NvGpuVmm Vmm, GpuMethodCall MethCall)
  730. {
  731. WriteRegister(MethCall);
  732. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.QueryAddress);
  733. int Seq = Registers[(int)NvGpuEngine3dReg.QuerySequence];
  734. int Ctrl = Registers[(int)NvGpuEngine3dReg.QueryControl];
  735. QueryMode Mode = (QueryMode)(Ctrl & 3);
  736. switch (Mode)
  737. {
  738. case QueryMode.WriteSeq: Vmm.WriteInt32(Position, Seq); break;
  739. case QueryMode.WriteCounterAndTimestamp:
  740. {
  741. //TODO: Implement counters.
  742. long Counter = 1;
  743. long Timestamp = PerformanceCounter.ElapsedMilliseconds;
  744. Timestamp = (long)(Timestamp * 615384.615385);
  745. Vmm.WriteInt64(Position + 0, Counter);
  746. Vmm.WriteInt64(Position + 8, Timestamp);
  747. break;
  748. }
  749. }
  750. }
  751. private void CbData(NvGpuVmm Vmm, GpuMethodCall MethCall)
  752. {
  753. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  754. int Offset = ReadRegister(NvGpuEngine3dReg.ConstBufferOffset);
  755. Vmm.WriteInt32(Position + Offset, MethCall.Argument);
  756. WriteRegister(NvGpuEngine3dReg.ConstBufferOffset, Offset + 4);
  757. Gpu.ResourceManager.ClearPbCache(NvGpuBufferType.ConstBuffer);
  758. }
  759. private void CbBind(NvGpuVmm Vmm, GpuMethodCall MethCall)
  760. {
  761. int Stage = (MethCall.Method - 0x904) >> 3;
  762. int Index = MethCall.Argument;
  763. bool Enabled = (Index & 1) != 0;
  764. Index = (Index >> 4) & 0x1f;
  765. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  766. long CbKey = Vmm.GetPhysicalAddress(Position);
  767. int Size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize);
  768. if (!Gpu.Renderer.Buffer.IsCached(CbKey, Size))
  769. {
  770. Gpu.Renderer.Buffer.Create(CbKey, Size);
  771. }
  772. ConstBuffer Cb = ConstBuffers[Stage][Index];
  773. if (Cb.Position != Position || Cb.Enabled != Enabled || Cb.Size != Size)
  774. {
  775. ConstBuffers[Stage][Index].Position = Position;
  776. ConstBuffers[Stage][Index].Enabled = Enabled;
  777. ConstBuffers[Stage][Index].Size = Size;
  778. }
  779. }
  780. private float GetFlipSign(NvGpuEngine3dReg Reg)
  781. {
  782. return MathF.Sign(ReadRegisterFloat(Reg));
  783. }
  784. private long MakeInt64From2xInt32(NvGpuEngine3dReg Reg)
  785. {
  786. return
  787. (long)Registers[(int)Reg + 0] << 32 |
  788. (uint)Registers[(int)Reg + 1];
  789. }
  790. private void WriteRegister(GpuMethodCall MethCall)
  791. {
  792. Registers[MethCall.Method] = MethCall.Argument;
  793. }
  794. private int ReadRegister(NvGpuEngine3dReg Reg)
  795. {
  796. return Registers[(int)Reg];
  797. }
  798. private float ReadRegisterFloat(NvGpuEngine3dReg Reg)
  799. {
  800. return BitConverter.Int32BitsToSingle(ReadRegister(Reg));
  801. }
  802. private bool ReadRegisterBool(NvGpuEngine3dReg Reg)
  803. {
  804. return (ReadRegister(Reg) & 1) != 0;
  805. }
  806. private void WriteRegister(NvGpuEngine3dReg Reg, int Value)
  807. {
  808. Registers[(int)Reg] = Value;
  809. }
  810. }
  811. }