NvGpuEngine3d.cs 36 KB

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