NvGpuEngine3d.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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. //Ensure that all components are enabled by default.
  51. //FIXME: Is this correct?
  52. WriteRegister(NvGpuEngine3dReg.ColorMaskN, 0x1111);
  53. }
  54. public void CallMethod(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  55. {
  56. if (Methods.TryGetValue(PBEntry.Method, out NvGpuMethod Method))
  57. {
  58. Method(Vmm, PBEntry);
  59. }
  60. else
  61. {
  62. WriteRegister(PBEntry);
  63. }
  64. }
  65. public void ResetCache()
  66. {
  67. foreach (List<long> Uploaded in UploadedKeys)
  68. {
  69. Uploaded.Clear();
  70. }
  71. }
  72. private void VertexEndGl(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  73. {
  74. LockCaches();
  75. GalPipelineState State = new GalPipelineState();
  76. SetFrameBuffer(State);
  77. SetFrontFace(State);
  78. SetCullFace(State);
  79. SetDepth(State);
  80. SetStencil(State);
  81. SetBlending(State);
  82. SetColorMask(State);
  83. SetPrimitiveRestart(State);
  84. for (int FbIndex = 0; FbIndex < 8; FbIndex++)
  85. {
  86. SetFrameBuffer(Vmm, FbIndex);
  87. }
  88. SetZeta(Vmm);
  89. SetRenderTargets();
  90. long[] Keys = UploadShaders(Vmm);
  91. Gpu.Renderer.Shader.BindProgram();
  92. UploadTextures(Vmm, State, Keys);
  93. UploadConstBuffers(Vmm, State, Keys);
  94. UploadVertexArrays(Vmm, State);
  95. DispatchRender(Vmm, State);
  96. UnlockCaches();
  97. }
  98. private void LockCaches()
  99. {
  100. Gpu.Renderer.Buffer.LockCache();
  101. Gpu.Renderer.Rasterizer.LockCaches();
  102. Gpu.Renderer.Texture.LockCache();
  103. }
  104. private void UnlockCaches()
  105. {
  106. Gpu.Renderer.Buffer.UnlockCache();
  107. Gpu.Renderer.Rasterizer.UnlockCaches();
  108. Gpu.Renderer.Texture.UnlockCache();
  109. }
  110. private void ClearBuffers(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  111. {
  112. int Arg0 = PBEntry.Arguments[0];
  113. int Attachment = (Arg0 >> 6) & 0xf;
  114. GalClearBufferFlags Flags = (GalClearBufferFlags)(Arg0 & 0x3f);
  115. float Red = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 0);
  116. float Green = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 1);
  117. float Blue = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 2);
  118. float Alpha = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 3);
  119. float Depth = ReadRegisterFloat(NvGpuEngine3dReg.ClearDepth);
  120. int Stencil = ReadRegister(NvGpuEngine3dReg.ClearStencil);
  121. SetFrameBuffer(Vmm, Attachment);
  122. SetZeta(Vmm);
  123. SetRenderTargets();
  124. Gpu.Renderer.RenderTarget.Bind();
  125. Gpu.Renderer.Rasterizer.ClearBuffers(Flags, Attachment, Red, Green, Blue, Alpha, Depth, Stencil);
  126. Gpu.Renderer.Pipeline.ResetDepthMask();
  127. Gpu.Renderer.Pipeline.ResetColorMask(Attachment);
  128. }
  129. private void SetFrameBuffer(NvGpuVmm Vmm, int FbIndex)
  130. {
  131. long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.FrameBufferNAddress + FbIndex * 0x10);
  132. int SurfFormat = ReadRegister(NvGpuEngine3dReg.FrameBufferNFormat + FbIndex * 0x10);
  133. if (VA == 0 || SurfFormat == 0)
  134. {
  135. Gpu.Renderer.RenderTarget.UnbindColor(FbIndex);
  136. return;
  137. }
  138. long Key = Vmm.GetPhysicalAddress(VA);
  139. int Width = ReadRegister(NvGpuEngine3dReg.FrameBufferNWidth + FbIndex * 0x10);
  140. int Height = ReadRegister(NvGpuEngine3dReg.FrameBufferNHeight + FbIndex * 0x10);
  141. int BlockDim = ReadRegister(NvGpuEngine3dReg.FrameBufferNBlockDim + FbIndex * 0x10);
  142. int GobBlockHeight = 1 << ((BlockDim >> 4) & 7);
  143. GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1);
  144. float TX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateX + FbIndex * 8);
  145. float TY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateY + FbIndex * 8);
  146. float SX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleX + FbIndex * 8);
  147. float SY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleY + FbIndex * 8);
  148. int VpX = (int)MathF.Max(0, TX - MathF.Abs(SX));
  149. int VpY = (int)MathF.Max(0, TY - MathF.Abs(SY));
  150. int VpW = (int)(TX + MathF.Abs(SX)) - VpX;
  151. int VpH = (int)(TY + MathF.Abs(SY)) - VpY;
  152. GalImageFormat Format = ImageUtils.ConvertSurface((GalSurfaceFormat)SurfFormat);
  153. GalImage Image = new GalImage(Width, Height, 1, GobBlockHeight, Layout, Format);
  154. Gpu.ResourceManager.SendColorBuffer(Vmm, Key, FbIndex, Image);
  155. Gpu.Renderer.RenderTarget.SetViewport(FbIndex, VpX, VpY, VpW, VpH);
  156. }
  157. private void SetFrameBuffer(GalPipelineState State)
  158. {
  159. State.FramebufferSrgb = ReadRegisterBool(NvGpuEngine3dReg.FrameBufferSrgb);
  160. State.FlipX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  161. State.FlipY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  162. }
  163. private void SetZeta(NvGpuVmm Vmm)
  164. {
  165. long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.ZetaAddress);
  166. int ZetaFormat = ReadRegister(NvGpuEngine3dReg.ZetaFormat);
  167. int BlockDim = ReadRegister(NvGpuEngine3dReg.ZetaBlockDimensions);
  168. int GobBlockHeight = 1 << ((BlockDim >> 4) & 7);
  169. GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1); //?
  170. bool ZetaEnable = ReadRegisterBool(NvGpuEngine3dReg.ZetaEnable);
  171. if (VA == 0 || ZetaFormat == 0 || !ZetaEnable)
  172. {
  173. Gpu.Renderer.RenderTarget.UnbindZeta();
  174. return;
  175. }
  176. long Key = Vmm.GetPhysicalAddress(VA);
  177. int Width = ReadRegister(NvGpuEngine3dReg.ZetaHoriz);
  178. int Height = ReadRegister(NvGpuEngine3dReg.ZetaVert);
  179. GalImageFormat Format = ImageUtils.ConvertZeta((GalZetaFormat)ZetaFormat);
  180. GalImage Image = new GalImage(Width, Height, 1, GobBlockHeight, Layout, Format);
  181. Gpu.ResourceManager.SendZetaBuffer(Vmm, Key, Image);
  182. }
  183. private long[] UploadShaders(NvGpuVmm Vmm)
  184. {
  185. long[] Keys = new long[5];
  186. long BasePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  187. int Index = 1;
  188. int VpAControl = ReadRegister(NvGpuEngine3dReg.ShaderNControl);
  189. bool VpAEnable = (VpAControl & 1) != 0;
  190. if (VpAEnable)
  191. {
  192. //Note: The maxwell supports 2 vertex programs, usually
  193. //only VP B is used, but in some cases VP A is also used.
  194. //In this case, it seems to function as an extra vertex
  195. //shader stage.
  196. //The graphics abstraction layer has a special overload for this
  197. //case, which should merge the two shaders into one vertex shader.
  198. int VpAOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset);
  199. int VpBOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + 0x10);
  200. long VpAPos = BasePosition + (uint)VpAOffset;
  201. long VpBPos = BasePosition + (uint)VpBOffset;
  202. Keys[(int)GalShaderType.Vertex] = VpBPos;
  203. Gpu.Renderer.Shader.Create(Vmm, VpAPos, VpBPos, GalShaderType.Vertex);
  204. Gpu.Renderer.Shader.Bind(VpBPos);
  205. Index = 2;
  206. }
  207. for (; Index < 6; Index++)
  208. {
  209. GalShaderType Type = GetTypeFromProgram(Index);
  210. int Control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + Index * 0x10);
  211. int Offset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + Index * 0x10);
  212. //Note: Vertex Program (B) is always enabled.
  213. bool Enable = (Control & 1) != 0 || Index == 1;
  214. if (!Enable)
  215. {
  216. Gpu.Renderer.Shader.Unbind(Type);
  217. continue;
  218. }
  219. long Key = BasePosition + (uint)Offset;
  220. Keys[(int)Type] = Key;
  221. Gpu.Renderer.Shader.Create(Vmm, Key, Type);
  222. Gpu.Renderer.Shader.Bind(Key);
  223. }
  224. return Keys;
  225. }
  226. private static GalShaderType GetTypeFromProgram(int Program)
  227. {
  228. switch (Program)
  229. {
  230. case 0:
  231. case 1: return GalShaderType.Vertex;
  232. case 2: return GalShaderType.TessControl;
  233. case 3: return GalShaderType.TessEvaluation;
  234. case 4: return GalShaderType.Geometry;
  235. case 5: return GalShaderType.Fragment;
  236. }
  237. throw new ArgumentOutOfRangeException(nameof(Program));
  238. }
  239. private void SetFrontFace(GalPipelineState State)
  240. {
  241. float SignX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  242. float SignY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  243. GalFrontFace FrontFace = (GalFrontFace)ReadRegister(NvGpuEngine3dReg.FrontFace);
  244. //Flipping breaks facing. Flipping front facing too fixes it
  245. if (SignX != SignY)
  246. {
  247. switch (FrontFace)
  248. {
  249. case GalFrontFace.CW: FrontFace = GalFrontFace.CCW; break;
  250. case GalFrontFace.CCW: FrontFace = GalFrontFace.CW; break;
  251. }
  252. }
  253. State.FrontFace = FrontFace;
  254. }
  255. private void SetCullFace(GalPipelineState State)
  256. {
  257. State.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable);
  258. if (State.CullFaceEnabled)
  259. {
  260. State.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace);
  261. }
  262. }
  263. private void SetDepth(GalPipelineState State)
  264. {
  265. State.DepthTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthTestEnable);
  266. State.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable);
  267. if (State.DepthTestEnabled)
  268. {
  269. State.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction);
  270. }
  271. State.DepthRangeNear = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNNear);
  272. State.DepthRangeFar = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNFar);
  273. }
  274. private void SetStencil(GalPipelineState State)
  275. {
  276. State.StencilTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.StencilEnable);
  277. if (State.StencilTestEnabled)
  278. {
  279. State.StencilBackFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilBackFuncFunc);
  280. State.StencilBackFuncRef = ReadRegister(NvGpuEngine3dReg.StencilBackFuncRef);
  281. State.StencilBackFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackFuncMask);
  282. State.StencilBackOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpFail);
  283. State.StencilBackOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZFail);
  284. State.StencilBackOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZPass);
  285. State.StencilBackMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackMask);
  286. State.StencilFrontFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncFunc);
  287. State.StencilFrontFuncRef = ReadRegister(NvGpuEngine3dReg.StencilFrontFuncRef);
  288. State.StencilFrontFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncMask);
  289. State.StencilFrontOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpFail);
  290. State.StencilFrontOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZFail);
  291. State.StencilFrontOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZPass);
  292. State.StencilFrontMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontMask);
  293. }
  294. }
  295. private void SetBlending(GalPipelineState State)
  296. {
  297. //TODO: Support independent blend properly.
  298. State.BlendEnabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable);
  299. if (State.BlendEnabled)
  300. {
  301. State.BlendSeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha);
  302. State.BlendEquationRgb = (GalBlendEquation)ReadRegister(NvGpuEngine3dReg.IBlendNEquationRgb);
  303. State.BlendFuncSrcRgb = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb);
  304. State.BlendFuncDstRgb = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb);
  305. State.BlendEquationAlpha = (GalBlendEquation)ReadRegister(NvGpuEngine3dReg.IBlendNEquationAlpha);
  306. State.BlendFuncSrcAlpha = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha);
  307. State.BlendFuncDstAlpha = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha);
  308. }
  309. }
  310. private void SetColorMask(GalPipelineState State)
  311. {
  312. bool ColorMaskCommon = ReadRegisterBool(NvGpuEngine3dReg.ColorMaskCommon);
  313. State.ColorMaskCommon = ColorMaskCommon;
  314. for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++)
  315. {
  316. int ColorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + (ColorMaskCommon ? 0 : 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. }