NvGpuEngine3d.cs 36 KB

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