NvGpuEngine3d.cs 37 KB

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