NvGpuEngine3d.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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. //TODO: Support independent blend properly.
  299. State.BlendEnabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable);
  300. if (State.BlendEnabled)
  301. {
  302. State.BlendSeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha);
  303. State.BlendEquationRgb = (GalBlendEquation)ReadRegister(NvGpuEngine3dReg.IBlendNEquationRgb);
  304. State.BlendFuncSrcRgb = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb);
  305. State.BlendFuncDstRgb = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb);
  306. State.BlendEquationAlpha = (GalBlendEquation)ReadRegister(NvGpuEngine3dReg.IBlendNEquationAlpha);
  307. State.BlendFuncSrcAlpha = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha);
  308. State.BlendFuncDstAlpha = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha);
  309. }
  310. }
  311. private void SetColorMask(GalPipelineState State)
  312. {
  313. bool ColorMaskCommon = ReadRegisterBool(NvGpuEngine3dReg.ColorMaskCommon);
  314. State.ColorMaskCommon = ColorMaskCommon;
  315. for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++)
  316. {
  317. int ColorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + (ColorMaskCommon ? 0 : Index));
  318. State.ColorMasks[Index].Red = ((ColorMask >> 0) & 0xf) != 0;
  319. State.ColorMasks[Index].Green = ((ColorMask >> 4) & 0xf) != 0;
  320. State.ColorMasks[Index].Blue = ((ColorMask >> 8) & 0xf) != 0;
  321. State.ColorMasks[Index].Alpha = ((ColorMask >> 12) & 0xf) != 0;
  322. }
  323. }
  324. private void SetPrimitiveRestart(GalPipelineState State)
  325. {
  326. State.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable);
  327. if (State.PrimitiveRestartEnabled)
  328. {
  329. State.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex);
  330. }
  331. }
  332. private void SetRenderTargets()
  333. {
  334. //Commercial games do not seem to
  335. //bool SeparateFragData = ReadRegisterBool(NvGpuEngine3dReg.RTSeparateFragData);
  336. uint Control = (uint)(ReadRegister(NvGpuEngine3dReg.RTControl));
  337. uint Count = Control & 0xf;
  338. if (Count > 0)
  339. {
  340. int[] Map = new int[Count];
  341. for (int Index = 0; Index < Count; Index++)
  342. {
  343. int Shift = 4 + Index * 3;
  344. Map[Index] = (int)((Control >> Shift) & 7);
  345. }
  346. Gpu.Renderer.RenderTarget.SetMap(Map);
  347. }
  348. else
  349. {
  350. Gpu.Renderer.RenderTarget.SetMap(null);
  351. }
  352. }
  353. private void UploadTextures(NvGpuVmm Vmm, GalPipelineState State, long[] Keys)
  354. {
  355. long BaseShPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  356. int TextureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex);
  357. int TexIndex = 0;
  358. for (int Index = 0; Index < Keys.Length; Index++)
  359. {
  360. foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetTextureUsage(Keys[Index]))
  361. {
  362. long Position;
  363. if (DeclInfo.IsCb)
  364. {
  365. Position = ConstBuffers[Index][DeclInfo.Cbuf].Position;
  366. }
  367. else
  368. {
  369. Position = ConstBuffers[Index][TextureCbIndex].Position;
  370. }
  371. int TextureHandle = Vmm.ReadInt32(Position + DeclInfo.Index * 4);
  372. UploadTexture(Vmm, TexIndex, TextureHandle);
  373. TexIndex++;
  374. }
  375. }
  376. }
  377. private void UploadTexture(NvGpuVmm Vmm, int TexIndex, int TextureHandle)
  378. {
  379. if (TextureHandle == 0)
  380. {
  381. //TODO: Is this correct?
  382. //Some games like puyo puyo will have 0 handles.
  383. //It may be just normal behaviour or a bug caused by sync issues.
  384. //The game does initialize the value properly after through.
  385. return;
  386. }
  387. int TicIndex = (TextureHandle >> 0) & 0xfffff;
  388. int TscIndex = (TextureHandle >> 20) & 0xfff;
  389. long TicPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexHeaderPoolOffset);
  390. long TscPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexSamplerPoolOffset);
  391. TicPosition += TicIndex * 0x20;
  392. TscPosition += TscIndex * 0x20;
  393. GalImage Image = TextureFactory.MakeTexture(Vmm, TicPosition);
  394. GalTextureSampler Sampler = TextureFactory.MakeSampler(Gpu, Vmm, TscPosition);
  395. long Key = Vmm.ReadInt64(TicPosition + 4) & 0xffffffffffff;
  396. if (Image.Layout == GalMemoryLayout.BlockLinear)
  397. {
  398. Key &= ~0x1ffL;
  399. }
  400. else if (Image.Layout == GalMemoryLayout.Pitch)
  401. {
  402. Key &= ~0x1fL;
  403. }
  404. Key = Vmm.GetPhysicalAddress(Key);
  405. if (Key == -1)
  406. {
  407. //FIXME: Shouldn't ignore invalid addresses.
  408. return;
  409. }
  410. Gpu.ResourceManager.SendTexture(Vmm, Key, Image, TexIndex);
  411. Gpu.Renderer.Texture.SetSampler(Sampler);
  412. }
  413. private void UploadConstBuffers(NvGpuVmm Vmm, GalPipelineState State, long[] Keys)
  414. {
  415. for (int Stage = 0; Stage < Keys.Length; Stage++)
  416. {
  417. foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetConstBufferUsage(Keys[Stage]))
  418. {
  419. ConstBuffer Cb = ConstBuffers[Stage][DeclInfo.Cbuf];
  420. if (!Cb.Enabled)
  421. {
  422. continue;
  423. }
  424. long Key = Vmm.GetPhysicalAddress(Cb.Position);
  425. if (QueryKeyUpload(Vmm, Key, Cb.Size, NvGpuBufferType.ConstBuffer))
  426. {
  427. IntPtr Source = Vmm.GetHostAddress(Cb.Position, Cb.Size);
  428. Gpu.Renderer.Buffer.SetData(Key, Cb.Size, Source);
  429. }
  430. State.ConstBufferKeys[Stage][DeclInfo.Cbuf] = Key;
  431. }
  432. }
  433. }
  434. private void UploadVertexArrays(NvGpuVmm Vmm, GalPipelineState State)
  435. {
  436. long IbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  437. long IboKey = Vmm.GetPhysicalAddress(IbPosition);
  438. int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  439. int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  440. int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  441. GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff);
  442. GalIndexFormat IndexFormat = (GalIndexFormat)IndexEntryFmt;
  443. int IndexEntrySize = 1 << IndexEntryFmt;
  444. if (IndexEntrySize > 4)
  445. {
  446. throw new InvalidOperationException();
  447. }
  448. if (IndexCount != 0)
  449. {
  450. int IbSize = IndexCount * IndexEntrySize;
  451. bool IboCached = Gpu.Renderer.Rasterizer.IsIboCached(IboKey, (uint)IbSize);
  452. bool UsesLegacyQuads =
  453. PrimType == GalPrimitiveType.Quads ||
  454. PrimType == GalPrimitiveType.QuadStrip;
  455. if (!IboCached || QueryKeyUpload(Vmm, IboKey, (uint)IbSize, NvGpuBufferType.Index))
  456. {
  457. if (!UsesLegacyQuads)
  458. {
  459. IntPtr DataAddress = Vmm.GetHostAddress(IbPosition, IbSize);
  460. Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, DataAddress);
  461. }
  462. else
  463. {
  464. byte[] Buffer = Vmm.ReadBytes(IbPosition, IbSize);
  465. if (PrimType == GalPrimitiveType.Quads)
  466. {
  467. Buffer = QuadHelper.ConvertIbQuadsToTris(Buffer, IndexEntrySize, IndexCount);
  468. }
  469. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  470. {
  471. Buffer = QuadHelper.ConvertIbQuadStripToTris(Buffer, IndexEntrySize, IndexCount);
  472. }
  473. Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, Buffer);
  474. }
  475. }
  476. if (!UsesLegacyQuads)
  477. {
  478. Gpu.Renderer.Rasterizer.SetIndexArray(IbSize, IndexFormat);
  479. }
  480. else
  481. {
  482. if (PrimType == GalPrimitiveType.Quads)
  483. {
  484. Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertIbSizeQuadsToTris(IbSize), IndexFormat);
  485. }
  486. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  487. {
  488. Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertIbSizeQuadStripToTris(IbSize), IndexFormat);
  489. }
  490. }
  491. }
  492. List<GalVertexAttrib>[] Attribs = new List<GalVertexAttrib>[32];
  493. for (int Attr = 0; Attr < 16; Attr++)
  494. {
  495. int Packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + Attr);
  496. int ArrayIndex = Packed & 0x1f;
  497. if (Attribs[ArrayIndex] == null)
  498. {
  499. Attribs[ArrayIndex] = new List<GalVertexAttrib>();
  500. }
  501. long VertexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + ArrayIndex * 4);
  502. int Offset = (Packed >> 7) & 0x3fff;
  503. //Note: 16 is the maximum size of an attribute,
  504. //having a component size of 32-bits with 4 elements (a vec4).
  505. IntPtr Pointer = Vmm.GetHostAddress(VertexPosition + Offset, 16);
  506. Attribs[ArrayIndex].Add(new GalVertexAttrib(
  507. Attr,
  508. ((Packed >> 6) & 0x1) != 0,
  509. Offset,
  510. Pointer,
  511. (GalVertexAttribSize)((Packed >> 21) & 0x3f),
  512. (GalVertexAttribType)((Packed >> 27) & 0x7),
  513. ((Packed >> 31) & 0x1) != 0));
  514. }
  515. State.VertexBindings = new GalVertexBinding[32];
  516. for (int Index = 0; Index < 32; Index++)
  517. {
  518. if (Attribs[Index] == null)
  519. {
  520. continue;
  521. }
  522. int Control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + Index * 4);
  523. bool Enable = (Control & 0x1000) != 0;
  524. if (!Enable)
  525. {
  526. continue;
  527. }
  528. long VertexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + Index * 4);
  529. long VertexEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + Index * 2);
  530. int VertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + Index * 4);
  531. bool Instanced = ReadRegisterBool(NvGpuEngine3dReg.VertexArrayNInstance + Index);
  532. int Stride = Control & 0xfff;
  533. if (Instanced && VertexDivisor != 0)
  534. {
  535. VertexPosition += Stride * (CurrentInstance / VertexDivisor);
  536. }
  537. if (VertexPosition > VertexEndPos)
  538. {
  539. //Instance is invalid, ignore the draw call
  540. continue;
  541. }
  542. long VboKey = Vmm.GetPhysicalAddress(VertexPosition);
  543. long VbSize = (VertexEndPos - VertexPosition) + 1;
  544. bool VboCached = Gpu.Renderer.Rasterizer.IsVboCached(VboKey, VbSize);
  545. if (!VboCached || QueryKeyUpload(Vmm, VboKey, VbSize, NvGpuBufferType.Vertex))
  546. {
  547. IntPtr DataAddress = Vmm.GetHostAddress(VertexPosition, VbSize);
  548. Gpu.Renderer.Rasterizer.CreateVbo(VboKey, (int)VbSize, DataAddress);
  549. }
  550. State.VertexBindings[Index].Enabled = true;
  551. State.VertexBindings[Index].Stride = Stride;
  552. State.VertexBindings[Index].VboKey = VboKey;
  553. State.VertexBindings[Index].Instanced = Instanced;
  554. State.VertexBindings[Index].Divisor = VertexDivisor;
  555. State.VertexBindings[Index].Attribs = Attribs[Index].ToArray();
  556. }
  557. }
  558. private void DispatchRender(NvGpuVmm Vmm, GalPipelineState State)
  559. {
  560. int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  561. int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  562. GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff);
  563. bool InstanceNext = ((PrimCtrl >> 26) & 1) != 0;
  564. bool InstanceCont = ((PrimCtrl >> 27) & 1) != 0;
  565. if (InstanceNext && InstanceCont)
  566. {
  567. throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time");
  568. }
  569. if (InstanceNext)
  570. {
  571. CurrentInstance++;
  572. }
  573. else if (!InstanceCont)
  574. {
  575. CurrentInstance = 0;
  576. }
  577. State.Instance = CurrentInstance;
  578. Gpu.Renderer.Pipeline.Bind(State);
  579. Gpu.Renderer.RenderTarget.Bind();
  580. if (IndexCount != 0)
  581. {
  582. int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  583. int IndexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst);
  584. int VertexBase = ReadRegister(NvGpuEngine3dReg.VertexArrayElemBase);
  585. long IndexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  586. long IboKey = Vmm.GetPhysicalAddress(IndexPosition);
  587. //Quad primitive types were deprecated on OpenGL 3.x,
  588. //they are converted to a triangles index buffer on IB creation,
  589. //so we should use the triangles type here too.
  590. if (PrimType == GalPrimitiveType.Quads ||
  591. PrimType == GalPrimitiveType.QuadStrip)
  592. {
  593. PrimType = GalPrimitiveType.Triangles;
  594. //Note: We assume that index first points to the first
  595. //vertex of a quad, if it points to the middle of a
  596. //quad (First % 4 != 0 for Quads) then it will not work properly.
  597. if (PrimType == GalPrimitiveType.Quads)
  598. {
  599. IndexFirst = QuadHelper.ConvertIbSizeQuadsToTris(IndexFirst);
  600. }
  601. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  602. {
  603. IndexFirst = QuadHelper.ConvertIbSizeQuadStripToTris(IndexFirst);
  604. }
  605. }
  606. Gpu.Renderer.Rasterizer.DrawElements(IboKey, IndexFirst, VertexBase, PrimType);
  607. }
  608. else
  609. {
  610. int VertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst);
  611. int VertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount);
  612. Gpu.Renderer.Rasterizer.DrawArrays(VertexFirst, VertexCount, PrimType);
  613. }
  614. //Is the GPU really clearing those registers after draw?
  615. WriteRegister(NvGpuEngine3dReg.IndexBatchFirst, 0);
  616. WriteRegister(NvGpuEngine3dReg.IndexBatchCount, 0);
  617. }
  618. private enum QueryMode
  619. {
  620. WriteSeq,
  621. Sync,
  622. WriteCounterAndTimestamp
  623. }
  624. private void QueryControl(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  625. {
  626. WriteRegister(PBEntry);
  627. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.QueryAddress);
  628. int Seq = Registers[(int)NvGpuEngine3dReg.QuerySequence];
  629. int Ctrl = Registers[(int)NvGpuEngine3dReg.QueryControl];
  630. QueryMode Mode = (QueryMode)(Ctrl & 3);
  631. switch (Mode)
  632. {
  633. case QueryMode.WriteSeq: Vmm.WriteInt32(Position, Seq); break;
  634. case QueryMode.WriteCounterAndTimestamp:
  635. {
  636. //TODO: Implement counters.
  637. long Counter = 1;
  638. long Timestamp = PerformanceCounter.ElapsedMilliseconds;
  639. Timestamp = (long)(Timestamp * 615384.615385);
  640. Vmm.WriteInt64(Position + 0, Counter);
  641. Vmm.WriteInt64(Position + 8, Timestamp);
  642. break;
  643. }
  644. }
  645. }
  646. private void CbData(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  647. {
  648. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  649. int Offset = ReadRegister(NvGpuEngine3dReg.ConstBufferOffset);
  650. foreach (int Arg in PBEntry.Arguments)
  651. {
  652. Vmm.WriteInt32(Position + Offset, Arg);
  653. Offset += 4;
  654. }
  655. WriteRegister(NvGpuEngine3dReg.ConstBufferOffset, Offset);
  656. UploadedKeys[(int)NvGpuBufferType.ConstBuffer].Clear();
  657. }
  658. private void CbBind(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  659. {
  660. int Stage = (PBEntry.Method - 0x904) >> 3;
  661. int Index = PBEntry.Arguments[0];
  662. bool Enabled = (Index & 1) != 0;
  663. Index = (Index >> 4) & 0x1f;
  664. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  665. long CbKey = Vmm.GetPhysicalAddress(Position);
  666. int Size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize);
  667. if (!Gpu.Renderer.Buffer.IsCached(CbKey, Size))
  668. {
  669. Gpu.Renderer.Buffer.Create(CbKey, Size);
  670. }
  671. ConstBuffer Cb = ConstBuffers[Stage][Index];
  672. if (Cb.Position != Position || Cb.Enabled != Enabled || Cb.Size != Size)
  673. {
  674. ConstBuffers[Stage][Index].Position = Position;
  675. ConstBuffers[Stage][Index].Enabled = Enabled;
  676. ConstBuffers[Stage][Index].Size = Size;
  677. }
  678. }
  679. private float GetFlipSign(NvGpuEngine3dReg Reg)
  680. {
  681. return MathF.Sign(ReadRegisterFloat(Reg));
  682. }
  683. private long MakeInt64From2xInt32(NvGpuEngine3dReg Reg)
  684. {
  685. return
  686. (long)Registers[(int)Reg + 0] << 32 |
  687. (uint)Registers[(int)Reg + 1];
  688. }
  689. private void WriteRegister(NvGpuPBEntry PBEntry)
  690. {
  691. int ArgsCount = PBEntry.Arguments.Count;
  692. if (ArgsCount > 0)
  693. {
  694. Registers[PBEntry.Method] = PBEntry.Arguments[ArgsCount - 1];
  695. }
  696. }
  697. private int ReadRegister(NvGpuEngine3dReg Reg)
  698. {
  699. return Registers[(int)Reg];
  700. }
  701. private float ReadRegisterFloat(NvGpuEngine3dReg Reg)
  702. {
  703. return BitConverter.Int32BitsToSingle(ReadRegister(Reg));
  704. }
  705. private bool ReadRegisterBool(NvGpuEngine3dReg Reg)
  706. {
  707. return (ReadRegister(Reg) & 1) != 0;
  708. }
  709. private void WriteRegister(NvGpuEngine3dReg Reg, int Value)
  710. {
  711. Registers[(int)Reg] = Value;
  712. }
  713. private bool QueryKeyUpload(NvGpuVmm Vmm, long Key, long Size, NvGpuBufferType Type)
  714. {
  715. List<long> Uploaded = UploadedKeys[(int)Type];
  716. if (Uploaded.Contains(Key))
  717. {
  718. return false;
  719. }
  720. Uploaded.Add(Key);
  721. return Vmm.IsRegionModified(Key, Size, Type);
  722. }
  723. }
  724. }