NvGpuEngine3d.cs 34 KB

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