diff options
Diffstat (limited to 'Ryujinx.Graphics/Graphics3d')
25 files changed, 0 insertions, 5671 deletions
diff --git a/Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs b/Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs deleted file mode 100644 index aa0db682..00000000 --- a/Ryujinx.Graphics/Graphics3d/INvGpuEngine.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Ryujinx.Graphics.Memory; - -namespace Ryujinx.Graphics.Graphics3d -{ - interface INvGpuEngine - { - int[] Registers { get; } - - void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall); - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs b/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs deleted file mode 100644 index 9a6206fa..00000000 --- a/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs +++ /dev/null @@ -1,416 +0,0 @@ -using Ryujinx.Common.Logging; -using Ryujinx.Graphics.Memory; -using System; -using System.Collections.Generic; - -namespace Ryujinx.Graphics.Graphics3d -{ - class MacroInterpreter - { - private enum AssignmentOperation - { - IgnoreAndFetch = 0, - Move = 1, - MoveAndSetMaddr = 2, - FetchAndSend = 3, - MoveAndSend = 4, - FetchAndSetMaddr = 5, - MoveAndSetMaddrThenFetchAndSend = 6, - MoveAndSetMaddrThenSendHigh = 7 - } - - private enum AluOperation - { - AluReg = 0, - AddImmediate = 1, - BitfieldReplace = 2, - BitfieldExtractLslImm = 3, - BitfieldExtractLslReg = 4, - ReadImmediate = 5 - } - - private enum AluRegOperation - { - Add = 0, - AddWithCarry = 1, - Subtract = 2, - SubtractWithBorrow = 3, - BitwiseExclusiveOr = 8, - BitwiseOr = 9, - BitwiseAnd = 10, - BitwiseAndNot = 11, - BitwiseNotAnd = 12 - } - - private NvGpuFifo _pFifo; - private INvGpuEngine _engine; - - public Queue<int> Fifo { get; private set; } - - private int[] _gprs; - - private int _methAddr; - private int _methIncr; - - private bool _carry; - - private int _opCode; - - private int _pipeOp; - - private int _pc; - - public MacroInterpreter(NvGpuFifo pFifo, INvGpuEngine engine) - { - _pFifo = pFifo; - _engine = engine; - - Fifo = new Queue<int>(); - - _gprs = new int[8]; - } - - public void Execute(NvGpuVmm vmm, int[] mme, int position, int param) - { - Reset(); - - _gprs[1] = param; - - _pc = position; - - FetchOpCode(mme); - - while (Step(vmm, mme)); - - // Due to the delay slot, we still need to execute - // one more instruction before we actually exit. - Step(vmm, mme); - } - - private void Reset() - { - for (int index = 0; index < _gprs.Length; index++) - { - _gprs[index] = 0; - } - - _methAddr = 0; - _methIncr = 0; - - _carry = false; - } - - private bool Step(NvGpuVmm vmm, int[] mme) - { - int baseAddr = _pc - 1; - - FetchOpCode(mme); - - if ((_opCode & 7) < 7) - { - // Operation produces a value. - AssignmentOperation asgOp = (AssignmentOperation)((_opCode >> 4) & 7); - - int result = GetAluResult(); - - switch (asgOp) - { - // Fetch parameter and ignore result. - case AssignmentOperation.IgnoreAndFetch: - { - SetDstGpr(FetchParam()); - - break; - } - - // Move result. - case AssignmentOperation.Move: - { - SetDstGpr(result); - - break; - } - - // Move result and use as Method Address. - case AssignmentOperation.MoveAndSetMaddr: - { - SetDstGpr(result); - - SetMethAddr(result); - - break; - } - - // Fetch parameter and send result. - case AssignmentOperation.FetchAndSend: - { - SetDstGpr(FetchParam()); - - Send(vmm, result); - - break; - } - - // Move and send result. - case AssignmentOperation.MoveAndSend: - { - SetDstGpr(result); - - Send(vmm, result); - - break; - } - - // Fetch parameter and use result as Method Address. - case AssignmentOperation.FetchAndSetMaddr: - { - SetDstGpr(FetchParam()); - - SetMethAddr(result); - - break; - } - - // Move result and use as Method Address, then fetch and send parameter. - case AssignmentOperation.MoveAndSetMaddrThenFetchAndSend: - { - SetDstGpr(result); - - SetMethAddr(result); - - Send(vmm, FetchParam()); - - break; - } - - // Move result and use as Method Address, then send bits 17:12 of result. - case AssignmentOperation.MoveAndSetMaddrThenSendHigh: - { - SetDstGpr(result); - - SetMethAddr(result); - - Send(vmm, (result >> 12) & 0x3f); - - break; - } - } - } - else - { - // Branch. - bool onNotZero = ((_opCode >> 4) & 1) != 0; - - bool taken = onNotZero - ? GetGprA() != 0 - : GetGprA() == 0; - - if (taken) - { - _pc = baseAddr + GetImm(); - - bool noDelays = (_opCode & 0x20) != 0; - - if (noDelays) - { - FetchOpCode(mme); - } - - return true; - } - } - - bool exit = (_opCode & 0x80) != 0; - - return !exit; - } - - private void FetchOpCode(int[] mme) - { - _opCode = _pipeOp; - - _pipeOp = mme[_pc++]; - } - - private int GetAluResult() - { - AluOperation op = (AluOperation)(_opCode & 7); - - switch (op) - { - case AluOperation.AluReg: - { - AluRegOperation aluOp = (AluRegOperation)((_opCode >> 17) & 0x1f); - - return GetAluResult(aluOp, GetGprA(), GetGprB()); - } - - case AluOperation.AddImmediate: - { - return GetGprA() + GetImm(); - } - - case AluOperation.BitfieldReplace: - case AluOperation.BitfieldExtractLslImm: - case AluOperation.BitfieldExtractLslReg: - { - int bfSrcBit = (_opCode >> 17) & 0x1f; - int bfSize = (_opCode >> 22) & 0x1f; - int bfDstBit = (_opCode >> 27) & 0x1f; - - int bfMask = (1 << bfSize) - 1; - - int dst = GetGprA(); - int src = GetGprB(); - - switch (op) - { - case AluOperation.BitfieldReplace: - { - src = (int)((uint)src >> bfSrcBit) & bfMask; - - dst &= ~(bfMask << bfDstBit); - - dst |= src << bfDstBit; - - return dst; - } - - case AluOperation.BitfieldExtractLslImm: - { - src = (int)((uint)src >> dst) & bfMask; - - return src << bfDstBit; - } - - case AluOperation.BitfieldExtractLslReg: - { - src = (int)((uint)src >> bfSrcBit) & bfMask; - - return src << dst; - } - } - - break; - } - - case AluOperation.ReadImmediate: - { - return Read(GetGprA() + GetImm()); - } - } - - throw new ArgumentException(nameof(_opCode)); - } - - private int GetAluResult(AluRegOperation aluOp, int a, int b) - { - switch (aluOp) - { - case AluRegOperation.Add: - { - ulong result = (ulong)a + (ulong)b; - - _carry = result > 0xffffffff; - - return (int)result; - } - - case AluRegOperation.AddWithCarry: - { - ulong result = (ulong)a + (ulong)b + (_carry ? 1UL : 0UL); - - _carry = result > 0xffffffff; - - return (int)result; - } - - case AluRegOperation.Subtract: - { - ulong result = (ulong)a - (ulong)b; - - _carry = result < 0x100000000; - - return (int)result; - } - - case AluRegOperation.SubtractWithBorrow: - { - ulong result = (ulong)a - (ulong)b - (_carry ? 0UL : 1UL); - - _carry = result < 0x100000000; - - return (int)result; - } - - case AluRegOperation.BitwiseExclusiveOr: return a ^ b; - case AluRegOperation.BitwiseOr: return a | b; - case AluRegOperation.BitwiseAnd: return a & b; - case AluRegOperation.BitwiseAndNot: return a & ~b; - case AluRegOperation.BitwiseNotAnd: return ~(a & b); - } - - throw new ArgumentOutOfRangeException(nameof(aluOp)); - } - - private int GetImm() - { - // Note: The immediate is signed, the sign-extension is intended here. - return _opCode >> 14; - } - - private void SetMethAddr(int value) - { - _methAddr = (value >> 0) & 0xfff; - _methIncr = (value >> 12) & 0x3f; - } - - private void SetDstGpr(int value) - { - _gprs[(_opCode >> 8) & 7] = value; - } - - private int GetGprA() - { - return GetGprValue((_opCode >> 11) & 7); - } - - private int GetGprB() - { - return GetGprValue((_opCode >> 14) & 7); - } - - private int GetGprValue(int index) - { - return index != 0 ? _gprs[index] : 0; - } - - private int FetchParam() - { - int value; - - if (!Fifo.TryDequeue(out value)) - { - Logger.PrintWarning(LogClass.Gpu, "Macro attempted to fetch an inexistent argument."); - - return 0; - } - - return value; - } - - private int Read(int reg) - { - return _engine.Registers[reg]; - } - - private void Send(NvGpuVmm vmm, int value) - { - GpuMethodCall methCall = new GpuMethodCall(_methAddr, value); - - _engine.CallMethod(vmm, methCall); - - _methAddr += _methIncr; - } - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine.cs deleted file mode 100644 index 20c36fda..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Ryujinx.Graphics.Graphics3d -{ - enum NvGpuEngine - { - _2d = 0x902d, - _3d = 0xb197, - Compute = 0xb1c0, - P2mf = 0xa140, - M2mf = 0xb0b5 - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs deleted file mode 100644 index b6dae2a3..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine2d.cs +++ /dev/null @@ -1,263 +0,0 @@ -using Ryujinx.Graphics.Gal; -using Ryujinx.Graphics.Memory; -using Ryujinx.Graphics.Texture; -using Ryujinx.Profiler; - -namespace Ryujinx.Graphics.Graphics3d -{ - class NvGpuEngine2d : INvGpuEngine - { - private enum CopyOperation - { - SrcCopyAnd, - RopAnd, - Blend, - SrcCopy, - Rop, - SrcCopyPremult, - BlendPremult - } - - public int[] Registers { get; private set; } - - private NvGpu _gpu; - - public NvGpuEngine2d(NvGpu gpu) - { - _gpu = gpu; - - Registers = new int[0x238]; - } - - public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - WriteRegister(methCall); - - if ((NvGpuEngine2dReg)methCall.Method == NvGpuEngine2dReg.BlitSrcYInt) - { - TextureCopy(vmm); - } - } - - private void TextureCopy(NvGpuVmm vmm) - { - Profile.Begin(Profiles.GPU.Engine2d.TextureCopy); - - CopyOperation operation = (CopyOperation)ReadRegister(NvGpuEngine2dReg.CopyOperation); - - int dstFormat = ReadRegister(NvGpuEngine2dReg.DstFormat); - bool dstLinear = ReadRegister(NvGpuEngine2dReg.DstLinear) != 0; - int dstWidth = ReadRegister(NvGpuEngine2dReg.DstWidth); - int dstHeight = ReadRegister(NvGpuEngine2dReg.DstHeight); - int dstDepth = ReadRegister(NvGpuEngine2dReg.DstDepth); - int dstLayer = ReadRegister(NvGpuEngine2dReg.DstLayer); - int dstPitch = ReadRegister(NvGpuEngine2dReg.DstPitch); - int dstBlkDim = ReadRegister(NvGpuEngine2dReg.DstBlockDimensions); - - int srcFormat = ReadRegister(NvGpuEngine2dReg.SrcFormat); - bool srcLinear = ReadRegister(NvGpuEngine2dReg.SrcLinear) != 0; - int srcWidth = ReadRegister(NvGpuEngine2dReg.SrcWidth); - int srcHeight = ReadRegister(NvGpuEngine2dReg.SrcHeight); - int srcDepth = ReadRegister(NvGpuEngine2dReg.SrcDepth); - int srcLayer = ReadRegister(NvGpuEngine2dReg.SrcLayer); - int srcPitch = ReadRegister(NvGpuEngine2dReg.SrcPitch); - int srcBlkDim = ReadRegister(NvGpuEngine2dReg.SrcBlockDimensions); - - int dstBlitX = ReadRegister(NvGpuEngine2dReg.BlitDstX); - int dstBlitY = ReadRegister(NvGpuEngine2dReg.BlitDstY); - int dstBlitW = ReadRegister(NvGpuEngine2dReg.BlitDstW); - int dstBlitH = ReadRegister(NvGpuEngine2dReg.BlitDstH); - - long blitDuDx = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDuDxFract); - long blitDvDy = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDvDyFract); - - long srcBlitX = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcXFract); - long srcBlitY = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcYFract); - - GalImageFormat srcImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)srcFormat); - GalImageFormat dstImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)dstFormat); - - GalMemoryLayout srcLayout = GetLayout(srcLinear); - GalMemoryLayout dstLayout = GetLayout(dstLinear); - - int srcBlockHeight = 1 << ((srcBlkDim >> 4) & 0xf); - int dstBlockHeight = 1 << ((dstBlkDim >> 4) & 0xf); - - long srcAddress = MakeInt64From2xInt32(NvGpuEngine2dReg.SrcAddress); - long dstAddress = MakeInt64From2xInt32(NvGpuEngine2dReg.DstAddress); - - long srcKey = vmm.GetPhysicalAddress(srcAddress); - long dstKey = vmm.GetPhysicalAddress(dstAddress); - - bool isSrcLayered = false; - bool isDstLayered = false; - - GalTextureTarget srcTarget = GalTextureTarget.TwoD; - - if (srcDepth != 0) - { - srcTarget = GalTextureTarget.TwoDArray; - srcDepth++; - isSrcLayered = true; - } - else - { - srcDepth = 1; - } - - GalTextureTarget dstTarget = GalTextureTarget.TwoD; - - if (dstDepth != 0) - { - dstTarget = GalTextureTarget.TwoDArray; - dstDepth++; - isDstLayered = true; - } - else - { - dstDepth = 1; - } - - GalImage srcTexture = new GalImage( - srcWidth, - srcHeight, - 1, srcDepth, 1, - srcBlockHeight, 1, - srcLayout, - srcImgFormat, - srcTarget); - - GalImage dstTexture = new GalImage( - dstWidth, - dstHeight, - 1, dstDepth, 1, - dstBlockHeight, 1, - dstLayout, - dstImgFormat, - dstTarget); - - srcTexture.Pitch = srcPitch; - dstTexture.Pitch = dstPitch; - - long GetLayerOffset(GalImage image, int layer) - { - int targetMipLevel = image.MaxMipmapLevel <= 1 ? 1 : image.MaxMipmapLevel - 1; - return ImageUtils.GetLayerOffset(image, targetMipLevel) * layer; - } - - int srcLayerIndex = -1; - - if (isSrcLayered && _gpu.ResourceManager.TryGetTextureLayer(srcKey, out srcLayerIndex) && srcLayerIndex != 0) - { - srcKey = srcKey - GetLayerOffset(srcTexture, srcLayerIndex); - } - - int dstLayerIndex = -1; - - if (isDstLayered && _gpu.ResourceManager.TryGetTextureLayer(dstKey, out dstLayerIndex) && dstLayerIndex != 0) - { - dstKey = dstKey - GetLayerOffset(dstTexture, dstLayerIndex); - } - - _gpu.ResourceManager.SendTexture(vmm, srcKey, srcTexture); - _gpu.ResourceManager.SendTexture(vmm, dstKey, dstTexture); - - if (isSrcLayered && srcLayerIndex == -1) - { - for (int layer = 0; layer < srcTexture.LayerCount; layer++) - { - _gpu.ResourceManager.SetTextureArrayLayer(srcKey + GetLayerOffset(srcTexture, layer), layer); - } - - srcLayerIndex = 0; - } - - if (isDstLayered && dstLayerIndex == -1) - { - for (int layer = 0; layer < dstTexture.LayerCount; layer++) - { - _gpu.ResourceManager.SetTextureArrayLayer(dstKey + GetLayerOffset(dstTexture, layer), layer); - } - - dstLayerIndex = 0; - } - - int srcBlitX1 = (int)(srcBlitX >> 32); - int srcBlitY1 = (int)(srcBlitY >> 32); - - int srcBlitX2 = (int)(srcBlitX + dstBlitW * blitDuDx >> 32); - int srcBlitY2 = (int)(srcBlitY + dstBlitH * blitDvDy >> 32); - - _gpu.Renderer.RenderTarget.Copy( - srcTexture, - dstTexture, - srcKey, - dstKey, - srcLayerIndex, - dstLayerIndex, - srcBlitX1, - srcBlitY1, - srcBlitX2, - srcBlitY2, - dstBlitX, - dstBlitY, - dstBlitX + dstBlitW, - dstBlitY + dstBlitH); - - // Do a guest side copy as well. This is necessary when - // the texture is modified by the guest, however it doesn't - // work when resources that the gpu can write to are copied, - // like framebuffers. - - // FIXME: SUPPORT MULTILAYER CORRECTLY HERE (this will cause weird stuffs on the first layer) - ImageUtils.CopyTexture( - vmm, - srcTexture, - dstTexture, - srcAddress, - dstAddress, - srcBlitX1, - srcBlitY1, - dstBlitX, - dstBlitY, - dstBlitW, - dstBlitH); - - vmm.IsRegionModified(dstKey, ImageUtils.GetSize(dstTexture), NvGpuBufferType.Texture); - - Profile.End(Profiles.GPU.Engine2d.TextureCopy); - } - - private static GalMemoryLayout GetLayout(bool linear) - { - return linear - ? GalMemoryLayout.Pitch - : GalMemoryLayout.BlockLinear; - } - - private long MakeInt64From2xInt32(NvGpuEngine2dReg reg) - { - return - (long)Registers[(int)reg + 0] << 32 | - (uint)Registers[(int)reg + 1]; - } - - private void WriteRegister(GpuMethodCall methCall) - { - Registers[methCall.Method] = methCall.Argument; - } - - private long ReadRegisterFixed1_31_32(NvGpuEngine2dReg reg) - { - long low = (uint)ReadRegister(reg + 0); - long high = (uint)ReadRegister(reg + 1); - - return low | (high << 32); - } - - private int ReadRegister(NvGpuEngine2dReg reg) - { - return Registers[(int)reg]; - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine2dReg.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine2dReg.cs deleted file mode 100644 index 7747b5a3..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine2dReg.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace Ryujinx.Graphics.Graphics3d -{ - enum NvGpuEngine2dReg - { - DstFormat = 0x80, - DstLinear = 0x81, - DstBlockDimensions = 0x82, - DstDepth = 0x83, - DstLayer = 0x84, - DstPitch = 0x85, - DstWidth = 0x86, - DstHeight = 0x87, - DstAddress = 0x88, - DstAddressLow = 0x89, - SrcFormat = 0x8c, - SrcLinear = 0x8d, - SrcBlockDimensions = 0x8e, - SrcDepth = 0x8f, - SrcLayer = 0x90, - SrcPitch = 0x91, - SrcWidth = 0x92, - SrcHeight = 0x93, - SrcAddress = 0x94, - SrcAddressLow = 0x95, - ClipEnable = 0xa4, - CopyOperation = 0xab, - BlitControl = 0x223, - BlitDstX = 0x22c, - BlitDstY = 0x22d, - BlitDstW = 0x22e, - BlitDstH = 0x22f, - BlitDuDxFract = 0x230, - BlitDuDxInt = 0x231, - BlitDvDyFract = 0x232, - BlitDvDyInt = 0x233, - BlitSrcXFract = 0x234, - BlitSrcXInt = 0x235, - BlitSrcYFract = 0x236, - BlitSrcYInt = 0x237 - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs deleted file mode 100644 index e475a964..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3d.cs +++ /dev/null @@ -1,1237 +0,0 @@ -using Ryujinx.Common; -using Ryujinx.Graphics.Gal; -using Ryujinx.Graphics.Memory; -using Ryujinx.Graphics.Shader; -using Ryujinx.Graphics.Texture; -using System; -using System.Collections.Generic; -using Ryujinx.Profiler; - -namespace Ryujinx.Graphics.Graphics3d -{ - class NvGpuEngine3d : INvGpuEngine - { - public int[] Registers { get; private set; } - - private NvGpu _gpu; - - private Dictionary<int, NvGpuMethod> _methods; - - private struct ConstBuffer - { - public bool Enabled; - public long Position; - public int Size; - } - - private ConstBuffer[][] _constBuffers; - - // Viewport dimensions kept for scissor test limits - private int _viewportX0 = 0; - private int _viewportY0 = 0; - private int _viewportX1 = 0; - private int _viewportY1 = 0; - private int _viewportWidth = 0; - private int _viewportHeight = 0; - - private int _currentInstance = 0; - - public NvGpuEngine3d(NvGpu gpu) - { - _gpu = gpu; - - Registers = new int[0xe00]; - - _methods = new Dictionary<int, NvGpuMethod>(); - - void AddMethod(int meth, int count, int stride, NvGpuMethod method) - { - while (count-- > 0) - { - _methods.Add(meth, method); - - meth += stride; - } - } - - AddMethod(0x585, 1, 1, VertexEndGl); - AddMethod(0x674, 1, 1, ClearBuffers); - AddMethod(0x6c3, 1, 1, QueryControl); - AddMethod(0x8e4, 16, 1, CbData); - AddMethod(0x904, 5, 8, CbBind); - - _constBuffers = new ConstBuffer[6][]; - - for (int index = 0; index < _constBuffers.Length; index++) - { - _constBuffers[index] = new ConstBuffer[18]; - } - - // Ensure that all components are enabled by default. - // FIXME: Is this correct? - WriteRegister(NvGpuEngine3dReg.ColorMaskN, 0x1111); - - WriteRegister(NvGpuEngine3dReg.FrameBufferSrgb, 1); - - WriteRegister(NvGpuEngine3dReg.FrontFace, (int)GalFrontFace.Cw); - - for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) - { - WriteRegister(NvGpuEngine3dReg.IBlendNEquationRgb + index * 8, (int)GalBlendEquation.FuncAdd); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb + index * 8, (int)GalBlendFactor.One); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb + index * 8, (int)GalBlendFactor.Zero); - WriteRegister(NvGpuEngine3dReg.IBlendNEquationAlpha + index * 8, (int)GalBlendEquation.FuncAdd); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha + index * 8, (int)GalBlendFactor.One); - WriteRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha + index * 8, (int)GalBlendFactor.Zero); - } - } - - public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - if (_methods.TryGetValue(methCall.Method, out NvGpuMethod method)) - { - ProfileConfig profile = Profiles.GPU.Engine3d.CallMethod; - - profile.SessionItem = method.Method.Name; - - Profile.Begin(profile); - - method(vmm, methCall); - - Profile.End(profile); - } - else - { - WriteRegister(methCall); - } - } - - private void VertexEndGl(NvGpuVmm vmm, GpuMethodCall methCall) - { - Profile.Begin(Profiles.GPU.Engine3d.VertexEnd); - - LockCaches(); - - Profile.Begin(Profiles.GPU.Engine3d.ConfigureState); - - GalPipelineState state = new GalPipelineState(); - - // Framebuffer must be run configured because viewport dimensions may be used in other methods - SetFrameBuffer(state); - - Profile.End(Profiles.GPU.Engine3d.ConfigureState); - - for (int fbIndex = 0; fbIndex < 8; fbIndex++) - { - SetFrameBuffer(vmm, fbIndex); - } - - SetFrontFace(state); - SetCullFace(state); - SetDepth(state); - SetStencil(state); - SetScissor(state); - SetBlending(state); - SetColorMask(state); - SetPrimitiveRestart(state); - - SetZeta(vmm); - - SetRenderTargets(); - - long[] keys = UploadShaders(vmm); - - _gpu.Renderer.Shader.BindProgram(); - - UploadTextures(vmm, state, keys); - UploadConstBuffers(vmm, state, keys); - UploadVertexArrays(vmm, state); - - DispatchRender(vmm, state); - - UnlockCaches(); - - Profile.End(Profiles.GPU.Engine3d.VertexEnd); - } - - private void LockCaches() - { - _gpu.Renderer.Buffer.LockCache(); - _gpu.Renderer.Rasterizer.LockCaches(); - _gpu.Renderer.Texture.LockCache(); - } - - private void UnlockCaches() - { - _gpu.Renderer.Buffer.UnlockCache(); - _gpu.Renderer.Rasterizer.UnlockCaches(); - _gpu.Renderer.Texture.UnlockCache(); - } - - private void ClearBuffers(NvGpuVmm vmm, GpuMethodCall methCall) - { - Profile.Begin(Profiles.GPU.Engine3d.ClearBuffers); - - int attachment = (methCall.Argument >> 6) & 0xf; - - GalClearBufferFlags flags = (GalClearBufferFlags)(methCall.Argument & 0x3f); - - float red = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 0); - float green = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 1); - float blue = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 2); - float alpha = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 3); - - float depth = ReadRegisterFloat(NvGpuEngine3dReg.ClearDepth); - - int stencil = ReadRegister(NvGpuEngine3dReg.ClearStencil); - - SetFrameBuffer(vmm, attachment); - - SetZeta(vmm); - - SetRenderTargets(); - - _gpu.Renderer.RenderTarget.Bind(); - - _gpu.Renderer.Rasterizer.ClearBuffers(flags, attachment, red, green, blue, alpha, depth, stencil); - - _gpu.Renderer.Pipeline.ResetDepthMask(); - _gpu.Renderer.Pipeline.ResetColorMask(attachment); - - Profile.End(Profiles.GPU.Engine3d.ClearBuffers); - } - - private void SetFrameBuffer(NvGpuVmm vmm, int fbIndex) - { - ProfileConfig profile = Profiles.GPU.Engine3d.SetFrameBuffer; - - profile.SessionItem = fbIndex.ToString(); - - Profile.Begin(profile); - - long va = MakeInt64From2xInt32(NvGpuEngine3dReg.FrameBufferNAddress + fbIndex * 0x10); - - int surfFormat = ReadRegister(NvGpuEngine3dReg.FrameBufferNFormat + fbIndex * 0x10); - - if (va == 0 || surfFormat == 0) - { - _gpu.Renderer.RenderTarget.UnbindColor(fbIndex); - - Profile.End(profile); - - return; - } - - long key = vmm.GetPhysicalAddress(va); - - int width = ReadRegister(NvGpuEngine3dReg.FrameBufferNWidth + fbIndex * 0x10); - int height = ReadRegister(NvGpuEngine3dReg.FrameBufferNHeight + fbIndex * 0x10); - - int arrayMode = ReadRegister(NvGpuEngine3dReg.FrameBufferNArrayMode + fbIndex * 0x10); - int layerCount = arrayMode & 0xFFFF; - int layerStride = ReadRegister(NvGpuEngine3dReg.FrameBufferNLayerStride + fbIndex * 0x10); - int baseLayer = ReadRegister(NvGpuEngine3dReg.FrameBufferNBaseLayer + fbIndex * 0x10); - int blockDim = ReadRegister(NvGpuEngine3dReg.FrameBufferNBlockDim + fbIndex * 0x10); - - int gobBlockHeight = 1 << ((blockDim >> 4) & 7); - - GalMemoryLayout layout = (GalMemoryLayout)((blockDim >> 12) & 1); - - float tx = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateX + fbIndex * 8); - float ty = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateY + fbIndex * 8); - - float sx = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleX + fbIndex * 8); - float sy = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleY + fbIndex * 8); - - _viewportX0 = (int)MathF.Max(0, tx - MathF.Abs(sx)); - _viewportY0 = (int)MathF.Max(0, ty - MathF.Abs(sy)); - - _viewportX1 = (int)(tx + MathF.Abs(sx)); - _viewportY1 = (int)(ty + MathF.Abs(sy)); - - GalImageFormat format = ImageUtils.ConvertSurface((GalSurfaceFormat)surfFormat); - - GalImage image = new GalImage(width, height, 1, 1, 1, gobBlockHeight, 1, layout, format, GalTextureTarget.TwoD); - - _gpu.ResourceManager.SendColorBuffer(vmm, key, fbIndex, image); - - _gpu.Renderer.RenderTarget.SetViewport(fbIndex, _viewportX0, _viewportY0, _viewportX1 - _viewportX0, _viewportY1 - _viewportY0); - - Profile.End(profile); - } - - private void SetFrameBuffer(GalPipelineState state) - { - state.FramebufferSrgb = ReadRegisterBool(NvGpuEngine3dReg.FrameBufferSrgb); - - state.FlipX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX); - state.FlipY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY); - - int screenYControl = ReadRegister(NvGpuEngine3dReg.ScreenYControl); - - bool negateY = (screenYControl & 1) != 0; - - if (negateY) - { - state.FlipY = -state.FlipY; - } - } - - private void SetZeta(NvGpuVmm vmm) - { - Profile.Begin(Profiles.GPU.Engine3d.SetZeta); - - long va = MakeInt64From2xInt32(NvGpuEngine3dReg.ZetaAddress); - - int zetaFormat = ReadRegister(NvGpuEngine3dReg.ZetaFormat); - - int blockDim = ReadRegister(NvGpuEngine3dReg.ZetaBlockDimensions); - - int gobBlockHeight = 1 << ((blockDim >> 4) & 7); - - GalMemoryLayout layout = (GalMemoryLayout)((blockDim >> 12) & 1); //? - - bool zetaEnable = ReadRegisterBool(NvGpuEngine3dReg.ZetaEnable); - - if (va == 0 || zetaFormat == 0 || !zetaEnable) - { - _gpu.Renderer.RenderTarget.UnbindZeta(); - - Profile.End(Profiles.GPU.Engine3d.SetZeta); - - return; - } - - long key = vmm.GetPhysicalAddress(va); - - int width = ReadRegister(NvGpuEngine3dReg.ZetaHoriz); - int height = ReadRegister(NvGpuEngine3dReg.ZetaVert); - - GalImageFormat format = ImageUtils.ConvertZeta((GalZetaFormat)zetaFormat); - - // TODO: Support non 2D? - GalImage image = new GalImage(width, height, 1, 1, 1, gobBlockHeight, 1, layout, format, GalTextureTarget.TwoD); - - _gpu.ResourceManager.SendZetaBuffer(vmm, key, image); - - Profile.End(Profiles.GPU.Engine3d.SetZeta); - } - - private long[] UploadShaders(NvGpuVmm vmm) - { - Profile.Begin(Profiles.GPU.Engine3d.UploadShaders); - - long[] keys = new long[5]; - - long basePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress); - - int index = 1; - - int vpAControl = ReadRegister(NvGpuEngine3dReg.ShaderNControl); - - bool vpAEnable = (vpAControl & 1) != 0; - - if (vpAEnable) - { - // Note: The maxwell supports 2 vertex programs, usually - // only VP B is used, but in some cases VP A is also used. - // In this case, it seems to function as an extra vertex - // shader stage. - // The graphics abstraction layer has a special overload for this - // case, which should merge the two shaders into one vertex shader. - int vpAOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset); - int vpBOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + 0x10); - - long vpAPos = basePosition + (uint)vpAOffset; - long vpBPos = basePosition + (uint)vpBOffset; - - keys[(int)GalShaderType.Vertex] = vpBPos; - - _gpu.Renderer.Shader.Create(vmm, vpAPos, vpBPos, GalShaderType.Vertex); - _gpu.Renderer.Shader.Bind(vpBPos); - - index = 2; - } - - for (; index < 6; index++) - { - GalShaderType type = GetTypeFromProgram(index); - - int control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + index * 0x10); - int offset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + index * 0x10); - - // Note: Vertex Program (B) is always enabled. - bool enable = (control & 1) != 0 || index == 1; - - if (!enable) - { - _gpu.Renderer.Shader.Unbind(type); - - continue; - } - - long key = basePosition + (uint)offset; - - keys[(int)type] = key; - - _gpu.Renderer.Shader.Create(vmm, key, type); - _gpu.Renderer.Shader.Bind(key); - } - - Profile.End(Profiles.GPU.Engine3d.UploadShaders); - - return keys; - } - - private static GalShaderType GetTypeFromProgram(int program) - { - switch (program) - { - case 0: - case 1: return GalShaderType.Vertex; - case 2: return GalShaderType.TessControl; - case 3: return GalShaderType.TessEvaluation; - case 4: return GalShaderType.Geometry; - case 5: return GalShaderType.Fragment; - } - - throw new ArgumentOutOfRangeException(nameof(program)); - } - - private void SetFrontFace(GalPipelineState state) - { - float signX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX); - float signY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY); - - GalFrontFace frontFace = (GalFrontFace)ReadRegister(NvGpuEngine3dReg.FrontFace); - - // Flipping breaks facing. Flipping front facing too fixes it - if (signX != signY) - { - switch (frontFace) - { - case GalFrontFace.Cw: frontFace = GalFrontFace.Ccw; break; - case GalFrontFace.Ccw: frontFace = GalFrontFace.Cw; break; - } - } - - state.FrontFace = frontFace; - } - - private void SetCullFace(GalPipelineState state) - { - state.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable); - - if (state.CullFaceEnabled) - { - state.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace); - } - } - - private void SetDepth(GalPipelineState state) - { - state.DepthTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthTestEnable); - - state.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable); - - if (state.DepthTestEnabled) - { - state.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction); - } - - state.DepthRangeNear = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNNear); - state.DepthRangeFar = ReadRegisterFloat(NvGpuEngine3dReg.DepthRangeNFar); - } - - private void SetStencil(GalPipelineState state) - { - state.StencilTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.StencilEnable); - - if (state.StencilTestEnabled) - { - state.StencilBackFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilBackFuncFunc); - state.StencilBackFuncRef = ReadRegister(NvGpuEngine3dReg.StencilBackFuncRef); - state.StencilBackFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackFuncMask); - state.StencilBackOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpFail); - state.StencilBackOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZFail); - state.StencilBackOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZPass); - state.StencilBackMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackMask); - - state.StencilFrontFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncFunc); - state.StencilFrontFuncRef = ReadRegister(NvGpuEngine3dReg.StencilFrontFuncRef); - state.StencilFrontFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncMask); - state.StencilFrontOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpFail); - state.StencilFrontOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZFail); - state.StencilFrontOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZPass); - state.StencilFrontMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontMask); - } - } - - private void SetScissor(GalPipelineState state) - { - int count = 0; - - for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) - { - state.ScissorTestEnabled[index] = ReadRegisterBool(NvGpuEngine3dReg.ScissorEnable + index * 4); - - if (state.ScissorTestEnabled[index]) - { - uint scissorHorizontal = (uint)ReadRegister(NvGpuEngine3dReg.ScissorHorizontal + index * 4); - uint scissorVertical = (uint)ReadRegister(NvGpuEngine3dReg.ScissorVertical + index * 4); - - int left = (int)(scissorHorizontal & 0xFFFF); // Left, lower 16 bits - int right = (int)(scissorHorizontal >> 16); // Right, upper 16 bits - - int bottom = (int)(scissorVertical & 0xFFFF); // Bottom, lower 16 bits - int top = (int)(scissorVertical >> 16); // Top, upper 16 bits - - int width = Math.Abs(right - left); - int height = Math.Abs(top - bottom); - - // If the scissor test covers the whole possible viewport, i.e. uninitialized, disable scissor test - if ((width > NvGpu.MaxViewportSize && height > NvGpu.MaxViewportSize) || width <= 0 || height <= 0) - { - state.ScissorTestEnabled[index] = false; - continue; - } - - // Keep track of how many scissor tests are active. - // If only 1, and it's the first user should apply to all viewports - count++; - - // Flip X - if (state.FlipX == -1) - { - left = _viewportX1 - (left - _viewportX0); - right = _viewportX1 - (right - _viewportX0); - } - - // Ensure X is in the right order - if (left > right) - { - int temp = left; - left = right; - right = temp; - } - - // Flip Y - if (state.FlipY == -1) - { - bottom = _viewportY1 - (bottom - _viewportY0); - top = _viewportY1 - (top - _viewportY0); - } - - // Ensure Y is in the right order - if (bottom > top) - { - int temp = top; - top = bottom; - bottom = temp; - } - - // Handle out of active viewport dimensions - left = Math.Clamp(left, _viewportX0, _viewportX1); - right = Math.Clamp(right, _viewportX0, _viewportX1); - top = Math.Clamp(top, _viewportY0, _viewportY1); - bottom = Math.Clamp(bottom, _viewportY0, _viewportY1); - - // Save values to state - state.ScissorTestX[index] = left; - state.ScissorTestY[index] = bottom; - - state.ScissorTestWidth[index] = right - left; - state.ScissorTestHeight[index] = top - bottom; - } - } - - state.ScissorTestCount = count; - } - - private void SetBlending(GalPipelineState state) - { - bool blendIndependent = ReadRegisterBool(NvGpuEngine3dReg.BlendIndependent); - - state.BlendIndependent = blendIndependent; - - for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) - { - if (blendIndependent) - { - state.Blends[index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable + index); - - if (state.Blends[index].Enabled) - { - state.Blends[index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha + index * 8); - - state.Blends[index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationRgb + index * 8); - state.Blends[index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcRgb + index * 8); - state.Blends[index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstRgb + index * 8); - state.Blends[index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.IBlendNEquationAlpha + index * 8); - state.Blends[index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncSrcAlpha + index * 8); - state.Blends[index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.IBlendNFuncDstAlpha + index * 8); - } - } - else - { - // It seems that even when independent blend is disabled, the first IBlend enable - // register is still set to indicate whenever blend is enabled or not (?). - state.Blends[index].Enabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable); - - if (state.Blends[index].Enabled) - { - state.Blends[index].SeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.BlendSeparateAlpha); - - state.Blends[index].EquationRgb = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationRgb); - state.Blends[index].FuncSrcRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcRgb); - state.Blends[index].FuncDstRgb = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstRgb); - state.Blends[index].EquationAlpha = ReadBlendEquation(NvGpuEngine3dReg.BlendEquationAlpha); - state.Blends[index].FuncSrcAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncSrcAlpha); - state.Blends[index].FuncDstAlpha = ReadBlendFactor (NvGpuEngine3dReg.BlendFuncDstAlpha); - } - } - } - } - - private GalBlendEquation ReadBlendEquation(NvGpuEngine3dReg register) - { - return (GalBlendEquation)ReadRegister(register); - } - - private GalBlendFactor ReadBlendFactor(NvGpuEngine3dReg register) - { - return (GalBlendFactor)ReadRegister(register); - } - - private void SetColorMask(GalPipelineState state) - { - bool colorMaskCommon = ReadRegisterBool(NvGpuEngine3dReg.ColorMaskCommon); - - state.ColorMaskCommon = colorMaskCommon; - - for (int index = 0; index < GalPipelineState.RenderTargetsCount; index++) - { - int colorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + (colorMaskCommon ? 0 : index)); - - state.ColorMasks[index].Red = ((colorMask >> 0) & 0xf) != 0; - state.ColorMasks[index].Green = ((colorMask >> 4) & 0xf) != 0; - state.ColorMasks[index].Blue = ((colorMask >> 8) & 0xf) != 0; - state.ColorMasks[index].Alpha = ((colorMask >> 12) & 0xf) != 0; - } - } - - private void SetPrimitiveRestart(GalPipelineState state) - { - state.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable); - - if (state.PrimitiveRestartEnabled) - { - state.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex); - } - } - - private void SetRenderTargets() - { - // Commercial games do not seem to - // bool SeparateFragData = ReadRegisterBool(NvGpuEngine3dReg.RTSeparateFragData); - - uint control = (uint)(ReadRegister(NvGpuEngine3dReg.RtControl)); - - uint count = control & 0xf; - - if (count > 0) - { - int[] map = new int[count]; - - for (int index = 0; index < count; index++) - { - int shift = 4 + index * 3; - - map[index] = (int)((control >> shift) & 7); - } - - _gpu.Renderer.RenderTarget.SetMap(map); - } - else - { - _gpu.Renderer.RenderTarget.SetMap(null); - } - } - - private void UploadTextures(NvGpuVmm vmm, GalPipelineState state, long[] keys) - { - Profile.Begin(Profiles.GPU.Engine3d.UploadTextures); - - long baseShPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress); - - int textureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex); - - List<(long, GalImage, GalTextureSampler)> unboundTextures = new List<(long, GalImage, GalTextureSampler)>(); - - for (int index = 0; index < keys.Length; index++) - { - foreach (TextureDescriptor desc in _gpu.Renderer.Shader.GetTextureUsage(keys[index])) - { - int textureHandle; - - if (desc.IsBindless) - { - long position = _constBuffers[index][desc.CbufSlot].Position; - - textureHandle = vmm.ReadInt32(position + desc.CbufOffset * 4); - } - else - { - long position = _constBuffers[index][textureCbIndex].Position; - - textureHandle = vmm.ReadInt32(position + desc.HandleIndex * 4); - } - - unboundTextures.Add(UploadTexture(vmm, textureHandle)); - } - } - - for (int index = 0; index < unboundTextures.Count; index++) - { - (long key, GalImage image, GalTextureSampler sampler) = unboundTextures[index]; - - if (key == 0) - { - continue; - } - - _gpu.Renderer.Texture.Bind(key, index, image); - _gpu.Renderer.Texture.SetSampler(image, sampler); - } - - Profile.End(Profiles.GPU.Engine3d.UploadTextures); - } - - private (long, GalImage, GalTextureSampler) UploadTexture(NvGpuVmm vmm, int textureHandle) - { - if (textureHandle == 0) - { - // FIXME: Some games like puyo puyo will use handles with the value 0. - // This is a bug, most likely caused by sync issues. - return (0, default(GalImage), default(GalTextureSampler)); - } - - Profile.Begin(Profiles.GPU.Engine3d.UploadTexture); - - bool linkedTsc = ReadRegisterBool(NvGpuEngine3dReg.LinkedTsc); - - int ticIndex = (textureHandle >> 0) & 0xfffff; - - int tscIndex = linkedTsc ? ticIndex : (textureHandle >> 20) & 0xfff; - - long ticPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexHeaderPoolOffset); - long tscPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexSamplerPoolOffset); - - ticPosition += ticIndex * 0x20; - tscPosition += tscIndex * 0x20; - - GalImage image = TextureFactory.MakeTexture(vmm, ticPosition); - - GalTextureSampler sampler = TextureFactory.MakeSampler(_gpu, vmm, tscPosition); - - long key = vmm.ReadInt64(ticPosition + 4) & 0xffffffffffff; - - if (image.Layout == GalMemoryLayout.BlockLinear) - { - key &= ~0x1ffL; - } - else if (image.Layout == GalMemoryLayout.Pitch) - { - key &= ~0x1fL; - } - - key = vmm.GetPhysicalAddress(key); - - if (key == -1) - { - Profile.End(Profiles.GPU.Engine3d.UploadTexture); - - // FIXME: Shouldn't ignore invalid addresses. - return (0, default(GalImage), default(GalTextureSampler)); - } - - _gpu.ResourceManager.SendTexture(vmm, key, image); - - Profile.End(Profiles.GPU.Engine3d.UploadTexture); - - return (key, image, sampler); - } - - private void UploadConstBuffers(NvGpuVmm vmm, GalPipelineState state, long[] keys) - { - Profile.Begin(Profiles.GPU.Engine3d.UploadConstBuffers); - - for (int stage = 0; stage < keys.Length; stage++) - { - foreach (CBufferDescriptor desc in _gpu.Renderer.Shader.GetConstBufferUsage(keys[stage])) - { - ConstBuffer cb = _constBuffers[stage][desc.Slot]; - - if (!cb.Enabled) - { - continue; - } - - long key = vmm.GetPhysicalAddress(cb.Position); - - if (_gpu.ResourceManager.MemoryRegionModified(vmm, key, cb.Size, NvGpuBufferType.ConstBuffer)) - { - if (vmm.TryGetHostAddress(cb.Position, cb.Size, out IntPtr cbPtr)) - { - _gpu.Renderer.Buffer.SetData(key, cb.Size, cbPtr); - } - else - { - _gpu.Renderer.Buffer.SetData(key, vmm.ReadBytes(cb.Position, cb.Size)); - } - } - - state.ConstBufferKeys[stage][desc.Slot] = key; - } - } - - Profile.End(Profiles.GPU.Engine3d.UploadConstBuffers); - } - - private void UploadVertexArrays(NvGpuVmm vmm, GalPipelineState state) - { - Profile.Begin(Profiles.GPU.Engine3d.UploadVertexArrays); - - long ibPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress); - - long iboKey = vmm.GetPhysicalAddress(ibPosition); - - int indexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat); - int indexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount); - int primCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl); - - GalPrimitiveType primType = (GalPrimitiveType)(primCtrl & 0xffff); - - GalIndexFormat indexFormat = (GalIndexFormat)indexEntryFmt; - - int indexEntrySize = 1 << indexEntryFmt; - - if (indexEntrySize > 4) - { - throw new InvalidOperationException("Invalid index entry size \"" + indexEntrySize + "\"!"); - } - - if (indexCount != 0) - { - int ibSize = indexCount * indexEntrySize; - - bool iboCached = _gpu.Renderer.Rasterizer.IsIboCached(iboKey, (uint)ibSize); - - bool usesLegacyQuads = - primType == GalPrimitiveType.Quads || - primType == GalPrimitiveType.QuadStrip; - - if (!iboCached || _gpu.ResourceManager.MemoryRegionModified(vmm, iboKey, (uint)ibSize, NvGpuBufferType.Index)) - { - if (!usesLegacyQuads) - { - if (vmm.TryGetHostAddress(ibPosition, ibSize, out IntPtr ibPtr)) - { - _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, ibPtr); - } - else - { - _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, vmm.ReadBytes(ibPosition, ibSize)); - } - } - else - { - byte[] buffer = vmm.ReadBytes(ibPosition, ibSize); - - if (primType == GalPrimitiveType.Quads) - { - buffer = QuadHelper.ConvertQuadsToTris(buffer, indexEntrySize, indexCount); - } - else /* if (PrimType == GalPrimitiveType.QuadStrip) */ - { - buffer = QuadHelper.ConvertQuadStripToTris(buffer, indexEntrySize, indexCount); - } - - _gpu.Renderer.Rasterizer.CreateIbo(iboKey, ibSize, buffer); - } - } - - if (!usesLegacyQuads) - { - _gpu.Renderer.Rasterizer.SetIndexArray(ibSize, indexFormat); - } - else - { - if (primType == GalPrimitiveType.Quads) - { - _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadsToTris(ibSize), indexFormat); - } - else /* if (PrimType == GalPrimitiveType.QuadStrip) */ - { - _gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertSizeQuadStripToTris(ibSize), indexFormat); - } - } - } - - List<GalVertexAttrib>[] attribs = new List<GalVertexAttrib>[32]; - - for (int attr = 0; attr < 16; attr++) - { - int packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + attr); - - int arrayIndex = packed & 0x1f; - - if (attribs[arrayIndex] == null) - { - attribs[arrayIndex] = new List<GalVertexAttrib>(); - } - - long vbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + arrayIndex * 4); - - if (vbPosition == 0) - { - continue; - } - - bool isConst = ((packed >> 6) & 1) != 0; - - int offset = (packed >> 7) & 0x3fff; - - GalVertexAttribSize size = (GalVertexAttribSize)((packed >> 21) & 0x3f); - GalVertexAttribType type = (GalVertexAttribType)((packed >> 27) & 0x7); - - bool isRgba = ((packed >> 31) & 1) != 0; - - // Check vertex array is enabled to avoid out of bounds exception when reading bytes - bool enable = (ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + arrayIndex * 4) & 0x1000) != 0; - - // Note: 16 is the maximum size of an attribute, - // having a component size of 32-bits with 4 elements (a vec4). - if (enable) - { - byte[] data = vmm.ReadBytes(vbPosition + offset, 16); - - attribs[arrayIndex].Add(new GalVertexAttrib(attr, isConst, offset, data, size, type, isRgba)); - } - } - - state.VertexBindings = new GalVertexBinding[32]; - - for (int index = 0; index < 32; index++) - { - if (attribs[index] == null) - { - continue; - } - - int control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + index * 4); - - bool enable = (control & 0x1000) != 0; - - if (!enable) - { - continue; - } - - long vbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + index * 4); - long vbEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + index * 2); - - int vertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + index * 4); - - bool instanced = ReadRegisterBool(NvGpuEngine3dReg.VertexArrayNInstance + index); - - int stride = control & 0xfff; - - if (instanced && vertexDivisor != 0) - { - vbPosition += stride * (_currentInstance / vertexDivisor); - } - - if (vbPosition > vbEndPos) - { - // Instance is invalid, ignore the draw call - continue; - } - - long vboKey = vmm.GetPhysicalAddress(vbPosition); - - long vbSize = (vbEndPos - vbPosition) + 1; - int modifiedVbSize = (int)vbSize; - - - // If quads convert size to triangle length - if (stride == 0) - { - if (primType == GalPrimitiveType.Quads) - { - modifiedVbSize = QuadHelper.ConvertSizeQuadsToTris(modifiedVbSize); - } - else if (primType == GalPrimitiveType.QuadStrip) - { - modifiedVbSize = QuadHelper.ConvertSizeQuadStripToTris(modifiedVbSize); - } - } - - bool vboCached = _gpu.Renderer.Rasterizer.IsVboCached(vboKey, modifiedVbSize); - - if (!vboCached || _gpu.ResourceManager.MemoryRegionModified(vmm, vboKey, vbSize, NvGpuBufferType.Vertex)) - { - if ((primType == GalPrimitiveType.Quads | primType == GalPrimitiveType.QuadStrip) && stride != 0) - { - // Convert quad buffer to triangles - byte[] data = vmm.ReadBytes(vbPosition, vbSize); - - if (primType == GalPrimitiveType.Quads) - { - data = QuadHelper.ConvertQuadsToTris(data, stride, (int)(vbSize / stride)); - } - else - { - data = QuadHelper.ConvertQuadStripToTris(data, stride, (int)(vbSize / stride)); - } - _gpu.Renderer.Rasterizer.CreateVbo(vboKey, data); - } - else if (vmm.TryGetHostAddress(vbPosition, vbSize, out IntPtr vbPtr)) - { - _gpu.Renderer.Rasterizer.CreateVbo(vboKey, (int)vbSize, vbPtr); - } - else - { - _gpu.Renderer.Rasterizer.CreateVbo(vboKey, vmm.ReadBytes(vbPosition, vbSize)); - } - } - - state.VertexBindings[index].Enabled = true; - state.VertexBindings[index].Stride = stride; - state.VertexBindings[index].VboKey = vboKey; - state.VertexBindings[index].Instanced = instanced; - state.VertexBindings[index].Divisor = vertexDivisor; - state.VertexBindings[index].Attribs = attribs[index].ToArray(); - } - - Profile.End(Profiles.GPU.Engine3d.UploadVertexArrays); - } - - private void DispatchRender(NvGpuVmm vmm, GalPipelineState state) - { - int indexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount); - int primCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl); - - GalPrimitiveType primType = (GalPrimitiveType)(primCtrl & 0xffff); - - bool instanceNext = ((primCtrl >> 26) & 1) != 0; - bool instanceCont = ((primCtrl >> 27) & 1) != 0; - - if (instanceNext && instanceCont) - { - throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time"); - } - - if (instanceNext) - { - _currentInstance++; - } - else if (!instanceCont) - { - _currentInstance = 0; - } - - state.Instance = _currentInstance; - - _gpu.Renderer.Pipeline.Bind(state); - - _gpu.Renderer.RenderTarget.Bind(); - - if (indexCount != 0) - { - int indexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat); - int indexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst); - int vertexBase = ReadRegister(NvGpuEngine3dReg.VertexArrayElemBase); - - long indexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress); - - long iboKey = vmm.GetPhysicalAddress(indexPosition); - - // Quad primitive types were deprecated on OpenGL 3.x, - // they are converted to a triangles index buffer on IB creation, - // so we should use the triangles type here too. - if (primType == GalPrimitiveType.Quads || primType == GalPrimitiveType.QuadStrip) - { - // Note: We assume that index first points to the first - // vertex of a quad, if it points to the middle of a - // quad (First % 4 != 0 for Quads) then it will not work properly. - if (primType == GalPrimitiveType.Quads) - { - indexFirst = QuadHelper.ConvertSizeQuadsToTris(indexFirst); - } - else // QuadStrip - { - indexFirst = QuadHelper.ConvertSizeQuadStripToTris(indexFirst); - } - - primType = GalPrimitiveType.Triangles; - } - - _gpu.Renderer.Rasterizer.DrawElements(iboKey, indexFirst, vertexBase, primType); - } - else - { - int vertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst); - int vertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount); - - // Quad primitive types were deprecated on OpenGL 3.x, - // they are converted to a triangles index buffer on IB creation, - // so we should use the triangles type here too. - if (primType == GalPrimitiveType.Quads || primType == GalPrimitiveType.QuadStrip) - { - // Note: We assume that index first points to the first - // vertex of a quad, if it points to the middle of a - // quad (First % 4 != 0 for Quads) then it will not work properly. - if (primType == GalPrimitiveType.Quads) - { - vertexFirst = QuadHelper.ConvertSizeQuadsToTris(vertexFirst); - } - else // QuadStrip - { - vertexFirst = QuadHelper.ConvertSizeQuadStripToTris(vertexFirst); - } - - primType = GalPrimitiveType.Triangles; - vertexCount = QuadHelper.ConvertSizeQuadsToTris(vertexCount); - } - - _gpu.Renderer.Rasterizer.DrawArrays(vertexFirst, vertexCount, primType); - } - - // Reset pipeline for host OpenGL calls - _gpu.Renderer.Pipeline.Unbind(state); - - // Is the GPU really clearing those registers after draw? - WriteRegister(NvGpuEngine3dReg.IndexBatchFirst, 0); - WriteRegister(NvGpuEngine3dReg.IndexBatchCount, 0); - } - - private enum QueryMode - { - WriteSeq, - Sync, - WriteCounterAndTimestamp - } - - private void QueryControl(NvGpuVmm vmm, GpuMethodCall methCall) - { - WriteRegister(methCall); - - long position = MakeInt64From2xInt32(NvGpuEngine3dReg.QueryAddress); - - int seq = Registers[(int)NvGpuEngine3dReg.QuerySequence]; - int ctrl = Registers[(int)NvGpuEngine3dReg.QueryControl]; - - QueryMode mode = (QueryMode)(ctrl & 3); - - switch (mode) - { - case QueryMode.WriteSeq: vmm.WriteInt32(position, seq); break; - - case QueryMode.WriteCounterAndTimestamp: - { - // TODO: Implement counters. - long counter = 1; - - long timestamp = PerformanceCounter.ElapsedMilliseconds; - - vmm.WriteInt64(position + 0, counter); - vmm.WriteInt64(position + 8, timestamp); - - break; - } - } - } - - private void CbData(NvGpuVmm vmm, GpuMethodCall methCall) - { - long position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress); - - int offset = ReadRegister(NvGpuEngine3dReg.ConstBufferOffset); - - vmm.WriteInt32(position + offset, methCall.Argument); - - WriteRegister(NvGpuEngine3dReg.ConstBufferOffset, offset + 4); - - _gpu.ResourceManager.ClearPbCache(NvGpuBufferType.ConstBuffer); - } - - private void CbBind(NvGpuVmm vmm, GpuMethodCall methCall) - { - int stage = (methCall.Method - 0x904) >> 3; - - int index = methCall.Argument; - - bool enabled = (index & 1) != 0; - - index = (index >> 4) & 0x1f; - - long position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress); - - long cbKey = vmm.GetPhysicalAddress(position); - - int size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize); - - if (!_gpu.Renderer.Buffer.IsCached(cbKey, size)) - { - _gpu.Renderer.Buffer.Create(cbKey, size); - } - - ConstBuffer cb = _constBuffers[stage][index]; - - if (cb.Position != position || cb.Enabled != enabled || cb.Size != size) - { - _constBuffers[stage][index].Position = position; - _constBuffers[stage][index].Enabled = enabled; - _constBuffers[stage][index].Size = size; - } - } - - private float GetFlipSign(NvGpuEngine3dReg reg) - { - return MathF.Sign(ReadRegisterFloat(reg)); - } - - private long MakeInt64From2xInt32(NvGpuEngine3dReg reg) - { - return - (long)Registers[(int)reg + 0] << 32 | - (uint)Registers[(int)reg + 1]; - } - - private void WriteRegister(GpuMethodCall methCall) - { - Registers[methCall.Method] = methCall.Argument; - } - - private int ReadRegister(NvGpuEngine3dReg reg) - { - return Registers[(int)reg]; - } - - private float ReadRegisterFloat(NvGpuEngine3dReg reg) - { - return BitConverter.Int32BitsToSingle(ReadRegister(reg)); - } - - private bool ReadRegisterBool(NvGpuEngine3dReg reg) - { - return (ReadRegister(reg) & 1) != 0; - } - - private void WriteRegister(NvGpuEngine3dReg reg, int value) - { - Registers[(int)reg] = value; - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3dReg.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngine3dReg.cs deleted file mode 100644 index c6596a30..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngine3dReg.cs +++ /dev/null @@ -1,116 +0,0 @@ -namespace Ryujinx.Graphics.Graphics3d -{ - enum NvGpuEngine3dReg - { - FrameBufferNAddress = 0x200, - FrameBufferNWidth = 0x202, - FrameBufferNHeight = 0x203, - FrameBufferNFormat = 0x204, - FrameBufferNBlockDim = 0x205, - FrameBufferNArrayMode = 0x206, - FrameBufferNLayerStride = 0x207, - FrameBufferNBaseLayer = 0x208, - ViewportNScaleX = 0x280, - ViewportNScaleY = 0x281, - ViewportNScaleZ = 0x282, - ViewportNTranslateX = 0x283, - ViewportNTranslateY = 0x284, - ViewportNTranslateZ = 0x285, - ViewportNHoriz = 0x300, - ViewportNVert = 0x301, - DepthRangeNNear = 0x302, - DepthRangeNFar = 0x303, - VertexArrayFirst = 0x35d, - VertexArrayCount = 0x35e, - ClearNColor = 0x360, - ClearDepth = 0x364, - ClearStencil = 0x368, - ScissorEnable = 0x380, - ScissorHorizontal = 0x381, - ScissorVertical = 0x382, - StencilBackFuncRef = 0x3d5, - StencilBackMask = 0x3d6, - StencilBackFuncMask = 0x3d7, - ColorMaskCommon = 0x3e4, - RtSeparateFragData = 0x3eb, - ZetaAddress = 0x3f8, - ZetaFormat = 0x3fa, - ZetaBlockDimensions = 0x3fb, - ZetaLayerStride = 0x3fc, - VertexAttribNFormat = 0x458, - RtControl = 0x487, - ZetaHoriz = 0x48a, - ZetaVert = 0x48b, - ZetaArrayMode = 0x48c, - LinkedTsc = 0x48d, - DepthTestEnable = 0x4b3, - BlendIndependent = 0x4b9, - DepthWriteEnable = 0x4ba, - DepthTestFunction = 0x4c3, - BlendSeparateAlpha = 0x4cf, - BlendEquationRgb = 0x4d0, - BlendFuncSrcRgb = 0x4d1, - BlendFuncDstRgb = 0x4d2, - BlendEquationAlpha = 0x4d3, - BlendFuncSrcAlpha = 0x4d4, - BlendFuncDstAlpha = 0x4d6, - BlendEnable = 0x4d7, - IBlendNEnable = 0x4d8, - StencilEnable = 0x4e0, - StencilFrontOpFail = 0x4e1, - StencilFrontOpZFail = 0x4e2, - StencilFrontOpZPass = 0x4e3, - StencilFrontFuncFunc = 0x4e4, - StencilFrontFuncRef = 0x4e5, - StencilFrontFuncMask = 0x4e6, - StencilFrontMask = 0x4e7, - ScreenYControl = 0x4eb, - VertexArrayElemBase = 0x50d, - VertexArrayInstBase = 0x50e, - ZetaEnable = 0x54e, - TexHeaderPoolOffset = 0x55d, - TexSamplerPoolOffset = 0x557, - StencilTwoSideEnable = 0x565, - StencilBackOpFail = 0x566, - StencilBackOpZFail = 0x567, - StencilBackOpZPass = 0x568, - StencilBackFuncFunc = 0x569, - FrameBufferSrgb = 0x56e, - ShaderAddress = 0x582, - VertexBeginGl = 0x586, - PrimRestartEnable = 0x591, - PrimRestartIndex = 0x592, - IndexArrayAddress = 0x5f2, - IndexArrayEndAddr = 0x5f4, - IndexArrayFormat = 0x5f6, - IndexBatchFirst = 0x5f7, - IndexBatchCount = 0x5f8, - VertexArrayNInstance = 0x620, - CullFaceEnable = 0x646, - FrontFace = 0x647, - CullFace = 0x648, - ColorMaskN = 0x680, - QueryAddress = 0x6c0, - QuerySequence = 0x6c2, - QueryControl = 0x6c3, - VertexArrayNControl = 0x700, - VertexArrayNAddress = 0x701, - VertexArrayNDivisor = 0x703, - IBlendNSeparateAlpha = 0x780, - IBlendNEquationRgb = 0x781, - IBlendNFuncSrcRgb = 0x782, - IBlendNFuncDstRgb = 0x783, - IBlendNEquationAlpha = 0x784, - IBlendNFuncSrcAlpha = 0x785, - IBlendNFuncDstAlpha = 0x786, - VertexArrayNEndAddr = 0x7c0, - ShaderNControl = 0x800, - ShaderNOffset = 0x801, - ShaderNMaxGprs = 0x803, - ShaderNType = 0x804, - ConstBufferSize = 0x8e0, - ConstBufferAddress = 0x8e1, - ConstBufferOffset = 0x8e3, - TextureCbIndex = 0x982 - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mf.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mf.cs deleted file mode 100644 index fca8ae22..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mf.cs +++ /dev/null @@ -1,214 +0,0 @@ -using Ryujinx.Graphics.Memory; -using Ryujinx.Graphics.Texture; -using System.Collections.Generic; -using Ryujinx.Profiler; - -namespace Ryujinx.Graphics.Graphics3d -{ - class NvGpuEngineM2mf : INvGpuEngine - { - public int[] Registers { get; private set; } - - private NvGpu _gpu; - - private Dictionary<int, NvGpuMethod> _methods; - - public NvGpuEngineM2mf(NvGpu gpu) - { - _gpu = gpu; - - Registers = new int[0x1d6]; - - _methods = new Dictionary<int, NvGpuMethod>(); - - void AddMethod(int meth, int count, int stride, NvGpuMethod method) - { - while (count-- > 0) - { - _methods.Add(meth, method); - - meth += stride; - } - } - - AddMethod(0xc0, 1, 1, Execute); - } - - public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - if (_methods.TryGetValue(methCall.Method, out NvGpuMethod method)) - { - ProfileConfig profile = Profiles.GPU.EngineM2mf.CallMethod; - - profile.SessionItem = method.Method.Name; - - Profile.Begin(profile); - method(vmm, methCall); - Profile.End(profile); - } - else - { - WriteRegister(methCall); - } - } - - private void Execute(NvGpuVmm vmm, GpuMethodCall methCall) - { - Profile.Begin(Profiles.GPU.EngineM2mf.Execute); - - // TODO: Some registers and copy modes are still not implemented. - int control = methCall.Argument; - - bool srcLinear = ((control >> 7) & 1) != 0; - bool dstLinear = ((control >> 8) & 1) != 0; - bool copy2D = ((control >> 9) & 1) != 0; - - long srcAddress = MakeInt64From2xInt32(NvGpuEngineM2mfReg.SrcAddress); - long dstAddress = MakeInt64From2xInt32(NvGpuEngineM2mfReg.DstAddress); - - int srcPitch = ReadRegister(NvGpuEngineM2mfReg.SrcPitch); - int dstPitch = ReadRegister(NvGpuEngineM2mfReg.DstPitch); - - int xCount = ReadRegister(NvGpuEngineM2mfReg.XCount); - int yCount = ReadRegister(NvGpuEngineM2mfReg.YCount); - - int swizzle = ReadRegister(NvGpuEngineM2mfReg.Swizzle); - - int dstBlkDim = ReadRegister(NvGpuEngineM2mfReg.DstBlkDim); - int dstSizeX = ReadRegister(NvGpuEngineM2mfReg.DstSizeX); - int dstSizeY = ReadRegister(NvGpuEngineM2mfReg.DstSizeY); - int dstSizeZ = ReadRegister(NvGpuEngineM2mfReg.DstSizeZ); - int dstPosXY = ReadRegister(NvGpuEngineM2mfReg.DstPosXY); - int dstPosZ = ReadRegister(NvGpuEngineM2mfReg.DstPosZ); - - int srcBlkDim = ReadRegister(NvGpuEngineM2mfReg.SrcBlkDim); - int srcSizeX = ReadRegister(NvGpuEngineM2mfReg.SrcSizeX); - int srcSizeY = ReadRegister(NvGpuEngineM2mfReg.SrcSizeY); - int srcSizeZ = ReadRegister(NvGpuEngineM2mfReg.SrcSizeZ); - int srcPosXY = ReadRegister(NvGpuEngineM2mfReg.SrcPosXY); - int srcPosZ = ReadRegister(NvGpuEngineM2mfReg.SrcPosZ); - - int srcCpp = ((swizzle >> 20) & 7) + 1; - int dstCpp = ((swizzle >> 24) & 7) + 1; - - int dstPosX = (dstPosXY >> 0) & 0xffff; - int dstPosY = (dstPosXY >> 16) & 0xffff; - - int srcPosX = (srcPosXY >> 0) & 0xffff; - int srcPosY = (srcPosXY >> 16) & 0xffff; - - int srcBlockHeight = 1 << ((srcBlkDim >> 4) & 0xf); - int dstBlockHeight = 1 << ((dstBlkDim >> 4) & 0xf); - - long srcPa = vmm.GetPhysicalAddress(srcAddress); - long dstPa = vmm.GetPhysicalAddress(dstAddress); - - if (copy2D) - { - if (srcLinear) - { - srcPosX = srcPosY = srcPosZ = 0; - } - - if (dstLinear) - { - dstPosX = dstPosY = dstPosZ = 0; - } - - if (srcLinear && dstLinear) - { - for (int y = 0; y < yCount; y++) - { - int srcOffset = (srcPosY + y) * srcPitch + srcPosX * srcCpp; - int dstOffset = (dstPosY + y) * dstPitch + dstPosX * dstCpp; - - long src = srcPa + (uint)srcOffset; - long dst = dstPa + (uint)dstOffset; - - vmm.Memory.CopyBytes(src, dst, xCount * srcCpp); - } - } - else - { - ISwizzle srcSwizzle; - - if (srcLinear) - { - srcSwizzle = new LinearSwizzle(srcPitch, srcCpp, srcSizeX, srcSizeY); - } - else - { - srcSwizzle = new BlockLinearSwizzle( - srcSizeX, - srcSizeY, 1, - srcBlockHeight, 1, - srcCpp); - } - - ISwizzle dstSwizzle; - - if (dstLinear) - { - dstSwizzle = new LinearSwizzle(dstPitch, dstCpp, srcSizeX, srcSizeY); - } - else - { - dstSwizzle = new BlockLinearSwizzle( - dstSizeX, - dstSizeY, 1, - dstBlockHeight, 1, - dstCpp); - } - - // Calculate the bits per pixel - int bpp = srcPitch / xCount; - - // Copying all the bits at the same time corrupts the texture, unknown why but probably because the texture isn't linear - // To avoid this we will simply loop more times to cover all the bits, - // this allows up to recalculate the memory locations for each iteration around the loop - xCount *= bpp / srcCpp; - - for (int y = 0; y < yCount; y++) - for (int x = 0; x < xCount; x++) - { - int srcOffset = srcSwizzle.GetSwizzleOffset(srcPosX + x, srcPosY + y, 0); - int dstOffset = dstSwizzle.GetSwizzleOffset(dstPosX + x, dstPosY + y, 0); - - long src = srcPa + (uint)srcOffset; - long dst = dstPa + (uint)dstOffset; - - vmm.Memory.CopyBytes(src, dst, srcCpp); - } - } - } - else - { - vmm.Memory.CopyBytes(srcPa, dstPa, xCount); - } - - Profile.End(Profiles.GPU.EngineM2mf.Execute); - } - - private long MakeInt64From2xInt32(NvGpuEngineM2mfReg reg) - { - return - (long)Registers[(int)reg + 0] << 32 | - (uint)Registers[(int)reg + 1]; - } - - private void WriteRegister(GpuMethodCall methCall) - { - Registers[methCall.Method] = methCall.Argument; - } - - private int ReadRegister(NvGpuEngineM2mfReg reg) - { - return Registers[(int)reg]; - } - - private void WriteRegister(NvGpuEngineM2mfReg reg, int value) - { - Registers[(int)reg] = value; - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mfReg.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mfReg.cs deleted file mode 100644 index 4bef8d9e..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngineM2mfReg.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace Ryujinx.Graphics.Graphics3d -{ - enum NvGpuEngineM2mfReg - { - SrcAddress = 0x100, - DstAddress = 0x102, - SrcPitch = 0x104, - DstPitch = 0x105, - XCount = 0x106, - YCount = 0x107, - Swizzle = 0x1c2, - DstBlkDim = 0x1c3, - DstSizeX = 0x1c4, - DstSizeY = 0x1c5, - DstSizeZ = 0x1c6, - DstPosZ = 0x1c7, - DstPosXY = 0x1c8, - SrcBlkDim = 0x1ca, - SrcSizeX = 0x1cb, - SrcSizeY = 0x1cc, - SrcSizeZ = 0x1cd, - SrcPosZ = 0x1ce, - SrcPosXY = 0x1cf - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mf.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mf.cs deleted file mode 100644 index 2b2c7b5f..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mf.cs +++ /dev/null @@ -1,179 +0,0 @@ -using Ryujinx.Graphics.Memory; -using Ryujinx.Graphics.Texture; -using System.Collections.Generic; -using Ryujinx.Profiler; - -namespace Ryujinx.Graphics.Graphics3d -{ - class NvGpuEngineP2mf : INvGpuEngine - { - public int[] Registers { get; private set; } - - private NvGpu _gpu; - - private Dictionary<int, NvGpuMethod> _methods; - - private int _copyStartX; - private int _copyStartY; - - private int _copyWidth; - private int _copyHeight; - private int _copyGobBlockHeight; - - private long _copyAddress; - - private int _copyOffset; - private int _copySize; - - private bool _copyLinear; - - private byte[] _buffer; - - public NvGpuEngineP2mf(NvGpu gpu) - { - _gpu = gpu; - - Registers = new int[0x80]; - - _methods = new Dictionary<int, NvGpuMethod>(); - - void AddMethod(int meth, int count, int stride, NvGpuMethod method) - { - while (count-- > 0) - { - _methods.Add(meth, method); - - meth += stride; - } - } - - AddMethod(0x6c, 1, 1, Execute); - AddMethod(0x6d, 1, 1, PushData); - } - - public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - if (_methods.TryGetValue(methCall.Method, out NvGpuMethod method)) - { - ProfileConfig profile = Profiles.GPU.EngineP2mf.PushData; - - profile.SessionItem = method.Method.Name; - - Profile.Begin(profile); - method(vmm, methCall); - Profile.End(profile); - } - else - { - WriteRegister(methCall); - } - } - - private void Execute(NvGpuVmm vmm, GpuMethodCall methCall) - { - Profile.Begin(Profiles.GPU.EngineP2mf.Execute); - - // TODO: Some registers and copy modes are still not implemented. - int control = methCall.Argument; - - long dstAddress = MakeInt64From2xInt32(NvGpuEngineP2mfReg.DstAddress); - - int dstPitch = ReadRegister(NvGpuEngineP2mfReg.DstPitch); - int dstBlkDim = ReadRegister(NvGpuEngineP2mfReg.DstBlockDim); - - int dstX = ReadRegister(NvGpuEngineP2mfReg.DstX); - int dstY = ReadRegister(NvGpuEngineP2mfReg.DstY); - - int dstWidth = ReadRegister(NvGpuEngineP2mfReg.DstWidth); - int dstHeight = ReadRegister(NvGpuEngineP2mfReg.DstHeight); - - int lineLengthIn = ReadRegister(NvGpuEngineP2mfReg.LineLengthIn); - int lineCount = ReadRegister(NvGpuEngineP2mfReg.LineCount); - - _copyLinear = (control & 1) != 0; - - _copyGobBlockHeight = 1 << ((dstBlkDim >> 4) & 0xf); - - _copyStartX = dstX; - _copyStartY = dstY; - - _copyWidth = dstWidth; - _copyHeight = dstHeight; - - _copyAddress = dstAddress; - - _copyOffset = 0; - _copySize = lineLengthIn * lineCount; - - _buffer = new byte[_copySize]; - - Profile.End(Profiles.GPU.EngineP2mf.Execute); - } - - private void PushData(NvGpuVmm vmm, GpuMethodCall methCall) - { - if (_buffer == null) - { - return; - } - - Profile.Begin(Profiles.GPU.EngineP2mf.PushData); - - for (int shift = 0; shift < 32 && _copyOffset < _copySize; shift += 8, _copyOffset++) - { - _buffer[_copyOffset] = (byte)(methCall.Argument >> shift); - } - - if (methCall.IsLastCall) - { - if (_copyLinear) - { - vmm.WriteBytes(_copyAddress, _buffer); - } - else - { - BlockLinearSwizzle swizzle = new BlockLinearSwizzle( - _copyWidth, - _copyHeight, 1, - _copyGobBlockHeight, 1, 1); - - int srcOffset = 0; - - for (int y = _copyStartY; y < _copyHeight && srcOffset < _copySize; y++) - for (int x = _copyStartX; x < _copyWidth && srcOffset < _copySize; x++) - { - int dstOffset = swizzle.GetSwizzleOffset(x, y, 0); - - vmm.WriteByte(_copyAddress + dstOffset, _buffer[srcOffset++]); - } - } - - _buffer = null; - } - - Profile.End(Profiles.GPU.EngineP2mf.PushData); - } - - private long MakeInt64From2xInt32(NvGpuEngineP2mfReg reg) - { - return - (long)Registers[(int)reg + 0] << 32 | - (uint)Registers[(int)reg + 1]; - } - - private void WriteRegister(GpuMethodCall methCall) - { - Registers[methCall.Method] = methCall.Argument; - } - - private int ReadRegister(NvGpuEngineP2mfReg reg) - { - return Registers[(int)reg]; - } - - private void WriteRegister(NvGpuEngineP2mfReg reg, int value) - { - Registers[(int)reg] = value; - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mfReg.cs b/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mfReg.cs deleted file mode 100644 index ab3a304d..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuEngineP2mfReg.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Ryujinx.Graphics.Graphics3d -{ - enum NvGpuEngineP2mfReg - { - LineLengthIn = 0x60, - LineCount = 0x61, - DstAddress = 0x62, - DstPitch = 0x64, - DstBlockDim = 0x65, - DstWidth = 0x66, - DstHeight = 0x67, - DstDepth = 0x68, - DstZ = 0x69, - DstX = 0x6a, - DstY = 0x6b - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs b/Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs deleted file mode 100644 index 23bfd0b3..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuFifo.cs +++ /dev/null @@ -1,176 +0,0 @@ -using Ryujinx.Graphics.Memory; - -namespace Ryujinx.Graphics.Graphics3d -{ - class NvGpuFifo - { - private const int MacrosCount = 0x80; - private const int MacroIndexMask = MacrosCount - 1; - - // Note: The size of the macro memory is unknown, we just make - // a guess here and use 256kb as the size. Increase if needed. - private const int MmeWords = 256 * 256; - - private NvGpu _gpu; - - private NvGpuEngine[] _subChannels; - - private struct CachedMacro - { - public int Position { get; private set; } - - private bool _executionPending; - private int _argument; - - private MacroInterpreter _interpreter; - - public CachedMacro(NvGpuFifo pFifo, INvGpuEngine engine, int position) - { - Position = position; - - _executionPending = false; - _argument = 0; - - _interpreter = new MacroInterpreter(pFifo, engine); - } - - public void StartExecution(int argument) - { - _argument = argument; - - _executionPending = true; - } - - public void Execute(NvGpuVmm vmm, int[] mme) - { - if (_executionPending) - { - _executionPending = false; - - _interpreter?.Execute(vmm, mme, Position, _argument); - } - } - - public void PushArgument(int argument) - { - _interpreter?.Fifo.Enqueue(argument); - } - } - - private int _currMacroPosition; - private int _currMacroBindIndex; - - private CachedMacro[] _macros; - - private int[] _mme; - - public NvGpuFifo(NvGpu gpu) - { - _gpu = gpu; - - _subChannels = new NvGpuEngine[8]; - - _macros = new CachedMacro[MacrosCount]; - - _mme = new int[MmeWords]; - } - - public void CallMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - if ((NvGpuFifoMeth)methCall.Method == NvGpuFifoMeth.BindChannel) - { - NvGpuEngine engine = (NvGpuEngine)methCall.Argument; - - _subChannels[methCall.SubChannel] = engine; - } - else - { - switch (_subChannels[methCall.SubChannel]) - { - case NvGpuEngine._2d: Call2dMethod (vmm, methCall); break; - case NvGpuEngine._3d: Call3dMethod (vmm, methCall); break; - case NvGpuEngine.P2mf: CallP2mfMethod(vmm, methCall); break; - case NvGpuEngine.M2mf: CallM2mfMethod(vmm, methCall); break; - } - } - } - - private void Call2dMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - _gpu.Engine2d.CallMethod(vmm, methCall); - } - - private void Call3dMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - if (methCall.Method < 0x80) - { - switch ((NvGpuFifoMeth)methCall.Method) - { - case NvGpuFifoMeth.SetMacroUploadAddress: - { - _currMacroPosition = methCall.Argument; - - break; - } - - case NvGpuFifoMeth.SendMacroCodeData: - { - _mme[_currMacroPosition++] = methCall.Argument; - - break; - } - - case NvGpuFifoMeth.SetMacroBindingIndex: - { - _currMacroBindIndex = methCall.Argument; - - break; - } - - case NvGpuFifoMeth.BindMacro: - { - int position = methCall.Argument; - - _macros[_currMacroBindIndex++] = new CachedMacro(this, _gpu.Engine3d, position); - - break; - } - - default: CallP2mfMethod(vmm, methCall); break; - } - } - else if (methCall.Method < 0xe00) - { - _gpu.Engine3d.CallMethod(vmm, methCall); - } - else - { - int macroIndex = (methCall.Method >> 1) & MacroIndexMask; - - if ((methCall.Method & 1) != 0) - { - _macros[macroIndex].PushArgument(methCall.Argument); - } - else - { - _macros[macroIndex].StartExecution(methCall.Argument); - } - - if (methCall.IsLastCall) - { - _macros[macroIndex].Execute(vmm, _mme); - } - } - } - - private void CallP2mfMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - _gpu.EngineP2mf.CallMethod(vmm, methCall); - } - - private void CallM2mfMethod(NvGpuVmm vmm, GpuMethodCall methCall) - { - _gpu.EngineM2mf.CallMethod(vmm, methCall); - } - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuFifoMeth.cs b/Ryujinx.Graphics/Graphics3d/NvGpuFifoMeth.cs deleted file mode 100644 index 9bf528b3..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuFifoMeth.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Ryujinx.Graphics.Graphics3d -{ - enum NvGpuFifoMeth - { - BindChannel = 0, - SetMacroUploadAddress = 0x45, - SendMacroCodeData = 0x46, - SetMacroBindingIndex = 0x47, - BindMacro = 0x48 - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs b/Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs deleted file mode 100644 index 23185c81..00000000 --- a/Ryujinx.Graphics/Graphics3d/NvGpuMethod.cs +++ /dev/null @@ -1,6 +0,0 @@ -using Ryujinx.Graphics.Memory; - -namespace Ryujinx.Graphics.Graphics3d -{ - delegate void NvGpuMethod(NvGpuVmm vmm, GpuMethodCall methCall); -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs b/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs deleted file mode 100644 index 3e68be7d..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs +++ /dev/null @@ -1,1385 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; - -namespace Ryujinx.Graphics.Texture -{ - public class AstcDecoderException : Exception - { - public AstcDecoderException(string exMsg) : base(exMsg) { } - } - - // https://github.com/GammaUNC/FasTC/blob/master/ASTCEncoder/src/Decompressor.cpp - public static class AstcDecoder - { - struct TexelWeightParams - { - public int Width; - public int Height; - public bool DualPlane; - public int MaxWeight; - public bool Error; - public bool VoidExtentLdr; - public bool VoidExtentHdr; - - public int GetPackedBitSize() - { - // How many indices do we have? - int indices = Height * Width; - - if (DualPlane) - { - indices *= 2; - } - - IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(MaxWeight); - - return intEncoded.GetBitLength(indices); - } - - public int GetNumWeightValues() - { - int ret = Width * Height; - - if (DualPlane) - { - ret *= 2; - } - - return ret; - } - } - - public static byte[] DecodeToRgba8888( - byte[] inputBuffer, - int blockX, - int blockY, - int blockZ, - int x, - int y, - int z) - { - using (MemoryStream inputStream = new MemoryStream(inputBuffer)) - { - BinaryReader binReader = new BinaryReader(inputStream); - - if (blockX > 12 || blockY > 12) - { - throw new AstcDecoderException("Block size unsupported!"); - } - - if (blockZ != 1 || z != 1) - { - // TODO: Support 3D textures? - throw new AstcDecoderException("3D compressed textures unsupported!"); - } - - using (MemoryStream outputStream = new MemoryStream()) - { - int blockIndex = 0; - - for (int j = 0; j < y; j += blockY) - { - for (int i = 0; i < x; i += blockX) - { - int[] decompressedData = new int[144]; - - DecompressBlock(binReader.ReadBytes(0x10), decompressedData, blockX, blockY); - - int decompressedWidth = Math.Min(blockX, x - i); - int decompressedHeight = Math.Min(blockY, y - j); - int baseOffsets = (j * x + i) * 4; - - for (int jj = 0; jj < decompressedHeight; jj++) - { - outputStream.Seek(baseOffsets + jj * x * 4, SeekOrigin.Begin); - - byte[] outputBuffer = new byte[decompressedData.Length * sizeof(int)]; - Buffer.BlockCopy(decompressedData, 0, outputBuffer, 0, outputBuffer.Length); - - outputStream.Write(outputBuffer, jj * blockX * 4, decompressedWidth * 4); - } - - blockIndex++; - } - } - - return outputStream.ToArray(); - } - } - } - - public static bool DecompressBlock( - byte[] inputBuffer, - int[] outputBuffer, - int blockWidth, - int blockHeight) - { - BitArrayStream bitStream = new BitArrayStream(new BitArray(inputBuffer)); - TexelWeightParams texelParams = DecodeBlockInfo(bitStream); - - if (texelParams.Error) - { - throw new AstcDecoderException("Invalid block mode"); - } - - if (texelParams.VoidExtentLdr) - { - FillVoidExtentLdr(bitStream, outputBuffer, blockWidth, blockHeight); - - return true; - } - - if (texelParams.VoidExtentHdr) - { - throw new AstcDecoderException("HDR void extent blocks are unsupported!"); - } - - if (texelParams.Width > blockWidth) - { - throw new AstcDecoderException("Texel weight grid width should be smaller than block width"); - } - - if (texelParams.Height > blockHeight) - { - throw new AstcDecoderException("Texel weight grid height should be smaller than block height"); - } - - // Read num partitions - int numberPartitions = bitStream.ReadBits(2) + 1; - Debug.Assert(numberPartitions <= 4); - - if (numberPartitions == 4 && texelParams.DualPlane) - { - throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks"); - } - - // Based on the number of partitions, read the color endpoint mode for - // each partition. - - // Determine partitions, partition index, and color endpoint modes - int planeIndices = -1; - int partitionIndex; - uint[] colorEndpointMode = { 0, 0, 0, 0 }; - - BitArrayStream colorEndpointStream = new BitArrayStream(new BitArray(16 * 8)); - - // Read extra config data... - uint baseColorEndpointMode = 0; - - if (numberPartitions == 1) - { - colorEndpointMode[0] = (uint)bitStream.ReadBits(4); - partitionIndex = 0; - } - else - { - partitionIndex = bitStream.ReadBits(10); - baseColorEndpointMode = (uint)bitStream.ReadBits(6); - } - - uint baseMode = (baseColorEndpointMode & 3); - - // Remaining bits are color endpoint data... - int numberWeightBits = texelParams.GetPackedBitSize(); - int remainingBits = 128 - numberWeightBits - bitStream.Position; - - // Consider extra bits prior to texel data... - uint extraColorEndpointModeBits = 0; - - if (baseMode != 0) - { - switch (numberPartitions) - { - case 2: extraColorEndpointModeBits += 2; break; - case 3: extraColorEndpointModeBits += 5; break; - case 4: extraColorEndpointModeBits += 8; break; - default: Debug.Assert(false); break; - } - } - - remainingBits -= (int)extraColorEndpointModeBits; - - // Do we have a dual plane situation? - int planeSelectorBits = 0; - - if (texelParams.DualPlane) - { - planeSelectorBits = 2; - } - - remainingBits -= planeSelectorBits; - - // Read color data... - int colorDataBits = remainingBits; - - while (remainingBits > 0) - { - int numberBits = Math.Min(remainingBits, 8); - int bits = bitStream.ReadBits(numberBits); - colorEndpointStream.WriteBits(bits, numberBits); - remainingBits -= 8; - } - - // Read the plane selection bits - planeIndices = bitStream.ReadBits(planeSelectorBits); - - // Read the rest of the CEM - if (baseMode != 0) - { - uint extraColorEndpointMode = (uint)bitStream.ReadBits((int)extraColorEndpointModeBits); - uint tempColorEndpointMode = (extraColorEndpointMode << 6) | baseColorEndpointMode; - tempColorEndpointMode >>= 2; - - bool[] c = new bool[4]; - - for (int i = 0; i < numberPartitions; i++) - { - c[i] = (tempColorEndpointMode & 1) != 0; - tempColorEndpointMode >>= 1; - } - - byte[] m = new byte[4]; - - for (int i = 0; i < numberPartitions; i++) - { - m[i] = (byte)(tempColorEndpointMode & 3); - tempColorEndpointMode >>= 2; - Debug.Assert(m[i] <= 3); - } - - for (int i = 0; i < numberPartitions; i++) - { - colorEndpointMode[i] = baseMode; - if (!(c[i])) colorEndpointMode[i] -= 1; - colorEndpointMode[i] <<= 2; - colorEndpointMode[i] |= m[i]; - } - } - else if (numberPartitions > 1) - { - uint tempColorEndpointMode = baseColorEndpointMode >> 2; - - for (uint i = 0; i < numberPartitions; i++) - { - colorEndpointMode[i] = tempColorEndpointMode; - } - } - - // Make sure everything up till here is sane. - for (int i = 0; i < numberPartitions; i++) - { - Debug.Assert(colorEndpointMode[i] < 16); - } - Debug.Assert(bitStream.Position + texelParams.GetPackedBitSize() == 128); - - // Decode both color data and texel weight data - int[] colorValues = new int[32]; // Four values * two endpoints * four maximum partitions - DecodeColorValues(colorValues, colorEndpointStream.ToByteArray(), colorEndpointMode, numberPartitions, colorDataBits); - - AstcPixel[][] endPoints = new AstcPixel[4][]; - endPoints[0] = new AstcPixel[2]; - endPoints[1] = new AstcPixel[2]; - endPoints[2] = new AstcPixel[2]; - endPoints[3] = new AstcPixel[2]; - - int colorValuesPosition = 0; - - for (int i = 0; i < numberPartitions; i++) - { - ComputeEndpoints(endPoints[i], colorValues, colorEndpointMode[i], ref colorValuesPosition); - } - - // Read the texel weight data. - byte[] texelWeightData = (byte[])inputBuffer.Clone(); - - // Reverse everything - for (int i = 0; i < 8; i++) - { - byte a = ReverseByte(texelWeightData[i]); - byte b = ReverseByte(texelWeightData[15 - i]); - - texelWeightData[i] = b; - texelWeightData[15 - i] = a; - } - - // Make sure that higher non-texel bits are set to zero - int clearByteStart = (texelParams.GetPackedBitSize() >> 3) + 1; - texelWeightData[clearByteStart - 1] &= (byte)((1 << (texelParams.GetPackedBitSize() % 8)) - 1); - - int cLen = 16 - clearByteStart; - for (int i = clearByteStart; i < clearByteStart + cLen; i++) texelWeightData[i] = 0; - - List<IntegerEncoded> texelWeightValues = new List<IntegerEncoded>(); - BitArrayStream weightBitStream = new BitArrayStream(new BitArray(texelWeightData)); - - IntegerEncoded.DecodeIntegerSequence(texelWeightValues, weightBitStream, texelParams.MaxWeight, texelParams.GetNumWeightValues()); - - // Blocks can be at most 12x12, so we can have as many as 144 weights - int[][] weights = new int[2][]; - weights[0] = new int[144]; - weights[1] = new int[144]; - - UnquantizeTexelWeights(weights, texelWeightValues, texelParams, blockWidth, blockHeight); - - // Now that we have endpoints and weights, we can interpolate and generate - // the proper decoding... - for (int j = 0; j < blockHeight; j++) - { - for (int i = 0; i < blockWidth; i++) - { - int partition = Select2dPartition(partitionIndex, i, j, numberPartitions, ((blockHeight * blockWidth) < 32)); - Debug.Assert(partition < numberPartitions); - - AstcPixel pixel = new AstcPixel(0, 0, 0, 0); - for (int component = 0; component < 4; component++) - { - int component0 = endPoints[partition][0].GetComponent(component); - component0 = BitArrayStream.Replicate(component0, 8, 16); - int component1 = endPoints[partition][1].GetComponent(component); - component1 = BitArrayStream.Replicate(component1, 8, 16); - - int plane = 0; - - if (texelParams.DualPlane && (((planeIndices + 1) & 3) == component)) - { - plane = 1; - } - - int weight = weights[plane][j * blockWidth + i]; - int finalComponent = (component0 * (64 - weight) + component1 * weight + 32) / 64; - - if (finalComponent == 65535) - { - pixel.SetComponent(component, 255); - } - else - { - double finalComponentFloat = finalComponent; - pixel.SetComponent(component, (int)(255.0 * (finalComponentFloat / 65536.0) + 0.5)); - } - } - - outputBuffer[j * blockWidth + i] = pixel.Pack(); - } - } - - return true; - } - - private static int Select2dPartition(int seed, int x, int y, int partitionCount, bool isSmallBlock) - { - return SelectPartition(seed, x, y, 0, partitionCount, isSmallBlock); - } - - private static int SelectPartition(int seed, int x, int y, int z, int partitionCount, bool isSmallBlock) - { - if (partitionCount == 1) - { - return 0; - } - - if (isSmallBlock) - { - x <<= 1; - y <<= 1; - z <<= 1; - } - - seed += (partitionCount - 1) * 1024; - - int rightNum = Hash52((uint)seed); - byte seed01 = (byte)(rightNum & 0xF); - byte seed02 = (byte)((rightNum >> 4) & 0xF); - byte seed03 = (byte)((rightNum >> 8) & 0xF); - byte seed04 = (byte)((rightNum >> 12) & 0xF); - byte seed05 = (byte)((rightNum >> 16) & 0xF); - byte seed06 = (byte)((rightNum >> 20) & 0xF); - byte seed07 = (byte)((rightNum >> 24) & 0xF); - byte seed08 = (byte)((rightNum >> 28) & 0xF); - byte seed09 = (byte)((rightNum >> 18) & 0xF); - byte seed10 = (byte)((rightNum >> 22) & 0xF); - byte seed11 = (byte)((rightNum >> 26) & 0xF); - byte seed12 = (byte)(((rightNum >> 30) | (rightNum << 2)) & 0xF); - - seed01 *= seed01; seed02 *= seed02; - seed03 *= seed03; seed04 *= seed04; - seed05 *= seed05; seed06 *= seed06; - seed07 *= seed07; seed08 *= seed08; - seed09 *= seed09; seed10 *= seed10; - seed11 *= seed11; seed12 *= seed12; - - int seedHash1, seedHash2, seedHash3; - - if ((seed & 1) != 0) - { - seedHash1 = (seed & 2) != 0 ? 4 : 5; - seedHash2 = (partitionCount == 3) ? 6 : 5; - } - else - { - seedHash1 = (partitionCount == 3) ? 6 : 5; - seedHash2 = (seed & 2) != 0 ? 4 : 5; - } - - seedHash3 = (seed & 0x10) != 0 ? seedHash1 : seedHash2; - - seed01 >>= seedHash1; seed02 >>= seedHash2; seed03 >>= seedHash1; seed04 >>= seedHash2; - seed05 >>= seedHash1; seed06 >>= seedHash2; seed07 >>= seedHash1; seed08 >>= seedHash2; - seed09 >>= seedHash3; seed10 >>= seedHash3; seed11 >>= seedHash3; seed12 >>= seedHash3; - - int a = seed01 * x + seed02 * y + seed11 * z + (rightNum >> 14); - int b = seed03 * x + seed04 * y + seed12 * z + (rightNum >> 10); - int c = seed05 * x + seed06 * y + seed09 * z + (rightNum >> 6); - int d = seed07 * x + seed08 * y + seed10 * z + (rightNum >> 2); - - a &= 0x3F; b &= 0x3F; c &= 0x3F; d &= 0x3F; - - if (partitionCount < 4) d = 0; - if (partitionCount < 3) c = 0; - - if (a >= b && a >= c && a >= d) return 0; - else if (b >= c && b >= d) return 1; - else if (c >= d) return 2; - return 3; - } - - static int Hash52(uint val) - { - val ^= val >> 15; val -= val << 17; val += val << 7; val += val << 4; - val ^= val >> 5; val += val << 16; val ^= val >> 7; val ^= val >> 3; - val ^= val << 6; val ^= val >> 17; - - return (int)val; - } - - static void UnquantizeTexelWeights( - int[][] outputBuffer, - List<IntegerEncoded> weights, - TexelWeightParams texelParams, - int blockWidth, - int blockHeight) - { - int weightIndices = 0; - int[][] unquantized = new int[2][]; - unquantized[0] = new int[144]; - unquantized[1] = new int[144]; - - for (int i = 0; i < weights.Count; i++) - { - unquantized[0][weightIndices] = UnquantizeTexelWeight(weights[i]); - - if (texelParams.DualPlane) - { - i++; - unquantized[1][weightIndices] = UnquantizeTexelWeight(weights[i]); - - if (i == weights.Count) - { - break; - } - } - - if (++weightIndices >= (texelParams.Width * texelParams.Height)) break; - } - - // Do infill if necessary (Section C.2.18) ... - int ds = (1024 + (blockWidth / 2)) / (blockWidth - 1); - int dt = (1024 + (blockHeight / 2)) / (blockHeight - 1); - - int planeScale = texelParams.DualPlane ? 2 : 1; - - for (int plane = 0; plane < planeScale; plane++) - { - for (int t = 0; t < blockHeight; t++) - { - for (int s = 0; s < blockWidth; s++) - { - int cs = ds * s; - int ct = dt * t; - - int gs = (cs * (texelParams.Width - 1) + 32) >> 6; - int gt = (ct * (texelParams.Height - 1) + 32) >> 6; - - int js = gs >> 4; - int fs = gs & 0xF; - - int jt = gt >> 4; - int ft = gt & 0x0F; - - int w11 = (fs * ft + 8) >> 4; - int w10 = ft - w11; - int w01 = fs - w11; - int w00 = 16 - fs - ft + w11; - - int v0 = js + jt * texelParams.Width; - - int p00 = 0; - int p01 = 0; - int p10 = 0; - int p11 = 0; - - if (v0 < (texelParams.Width * texelParams.Height)) - { - p00 = unquantized[plane][v0]; - } - - if (v0 + 1 < (texelParams.Width * texelParams.Height)) - { - p01 = unquantized[plane][v0 + 1]; - } - - if (v0 + texelParams.Width < (texelParams.Width * texelParams.Height)) - { - p10 = unquantized[plane][v0 + texelParams.Width]; - } - - if (v0 + texelParams.Width + 1 < (texelParams.Width * texelParams.Height)) - { - p11 = unquantized[plane][v0 + texelParams.Width + 1]; - } - - outputBuffer[plane][t * blockWidth + s] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4; - } - } - } - } - - static int UnquantizeTexelWeight(IntegerEncoded intEncoded) - { - int bitValue = intEncoded.BitValue; - int bitLength = intEncoded.NumberBits; - - int a = BitArrayStream.Replicate(bitValue & 1, 1, 7); - int b = 0, c = 0, d = 0; - - int result = 0; - - switch (intEncoded.GetEncoding()) - { - case IntegerEncoded.EIntegerEncoding.JustBits: - result = BitArrayStream.Replicate(bitValue, bitLength, 6); - break; - - case IntegerEncoded.EIntegerEncoding.Trit: - { - d = intEncoded.TritValue; - Debug.Assert(d < 3); - - switch (bitLength) - { - case 0: - { - int[] results = { 0, 32, 63 }; - result = results[d]; - - break; - } - - case 1: - { - c = 50; - break; - } - - case 2: - { - c = 23; - int b2 = (bitValue >> 1) & 1; - b = (b2 << 6) | (b2 << 2) | b2; - - break; - } - - case 3: - { - c = 11; - int cb = (bitValue >> 1) & 3; - b = (cb << 5) | cb; - - break; - } - - default: - throw new AstcDecoderException("Invalid trit encoding for texel weight"); - } - - break; - } - - case IntegerEncoded.EIntegerEncoding.Quint: - { - d = intEncoded.QuintValue; - Debug.Assert(d < 5); - - switch (bitLength) - { - case 0: - { - int[] results = { 0, 16, 32, 47, 63 }; - result = results[d]; - - break; - } - - case 1: - { - c = 28; - - break; - } - - case 2: - { - c = 13; - int b2 = (bitValue >> 1) & 1; - b = (b2 << 6) | (b2 << 1); - - break; - } - - default: - throw new AstcDecoderException("Invalid quint encoding for texel weight"); - } - - break; - } - } - - if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && bitLength > 0) - { - // Decode the value... - result = d * c + b; - result ^= a; - result = (a & 0x20) | (result >> 2); - } - - Debug.Assert(result < 64); - - // Change from [0,63] to [0,64] - if (result > 32) - { - result += 1; - } - - return result; - } - - static byte ReverseByte(byte b) - { - // Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits - return (byte)((((b) * 0x80200802L) & 0x0884422110L) * 0x0101010101L >> 32); - } - - static uint[] ReadUintColorValues(int number, int[] colorValues, ref int colorValuesPosition) - { - uint[] ret = new uint[number]; - - for (int i = 0; i < number; i++) - { - ret[i] = (uint)colorValues[colorValuesPosition++]; - } - - return ret; - } - - static int[] ReadIntColorValues(int number, int[] colorValues, ref int colorValuesPosition) - { - int[] ret = new int[number]; - - for (int i = 0; i < number; i++) - { - ret[i] = colorValues[colorValuesPosition++]; - } - - return ret; - } - - static void ComputeEndpoints( - AstcPixel[] endPoints, - int[] colorValues, - uint colorEndpointMode, - ref int colorValuesPosition) - { - switch (colorEndpointMode) - { - case 0: - { - uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition); - - endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[0], (short)val[0]); - endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[1], (short)val[1]); - - break; - } - - - case 1: - { - uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition); - int l0 = (int)((val[0] >> 2) | (val[1] & 0xC0)); - int l1 = (int)Math.Max(l0 + (val[1] & 0x3F), 0xFFU); - - endPoints[0] = new AstcPixel(0xFF, (short)l0, (short)l0, (short)l0); - endPoints[1] = new AstcPixel(0xFF, (short)l1, (short)l1, (short)l1); - - break; - } - - case 4: - { - uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition); - - endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]); - endPoints[1] = new AstcPixel((short)val[3], (short)val[1], (short)val[1], (short)val[1]); - - break; - } - - case 5: - { - int[] val = ReadIntColorValues(4, colorValues, ref colorValuesPosition); - - BitArrayStream.BitTransferSigned(ref val[1], ref val[0]); - BitArrayStream.BitTransferSigned(ref val[3], ref val[2]); - - endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]); - endPoints[1] = new AstcPixel((short)(val[2] + val[3]), (short)(val[0] + val[1]), (short)(val[0] + val[1]), (short)(val[0] + val[1])); - - endPoints[0].ClampByte(); - endPoints[1].ClampByte(); - - break; - } - - case 6: - { - uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition); - - endPoints[0] = new AstcPixel(0xFF, (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8)); - endPoints[1] = new AstcPixel(0xFF, (short)val[0], (short)val[1], (short)val[2]); - - break; - } - - case 8: - { - uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition); - - if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4]) - { - endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]); - endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[3], (short)val[5]); - } - else - { - endPoints[0] = AstcPixel.BlueContract(0xFF, (short)val[1], (short)val[3], (short)val[5]); - endPoints[1] = AstcPixel.BlueContract(0xFF, (short)val[0], (short)val[2], (short)val[4]); - } - - break; - } - - case 9: - { - int[] val = ReadIntColorValues(6, colorValues, ref colorValuesPosition); - - BitArrayStream.BitTransferSigned(ref val[1], ref val[0]); - BitArrayStream.BitTransferSigned(ref val[3], ref val[2]); - BitArrayStream.BitTransferSigned(ref val[5], ref val[4]); - - if (val[1] + val[3] + val[5] >= 0) - { - endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]); - endPoints[1] = new AstcPixel(0xFF, (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5])); - } - else - { - endPoints[0] = AstcPixel.BlueContract(0xFF, val[0] + val[1], val[2] + val[3], val[4] + val[5]); - endPoints[1] = AstcPixel.BlueContract(0xFF, val[0], val[2], val[4]); - } - - endPoints[0].ClampByte(); - endPoints[1].ClampByte(); - - break; - } - - case 10: - { - uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition); - - endPoints[0] = new AstcPixel((short)val[4], (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8)); - endPoints[1] = new AstcPixel((short)val[5], (short)val[0], (short)val[1], (short)val[2]); - - break; - } - - case 12: - { - uint[] val = ReadUintColorValues(8, colorValues, ref colorValuesPosition); - - if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4]) - { - endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]); - endPoints[1] = new AstcPixel((short)val[7], (short)val[1], (short)val[3], (short)val[5]); - } - else - { - endPoints[0] = AstcPixel.BlueContract((short)val[7], (short)val[1], (short)val[3], (short)val[5]); - endPoints[1] = AstcPixel.BlueContract((short)val[6], (short)val[0], (short)val[2], (short)val[4]); - } - - break; - } - - case 13: - { - int[] val = ReadIntColorValues(8, colorValues, ref colorValuesPosition); - - BitArrayStream.BitTransferSigned(ref val[1], ref val[0]); - BitArrayStream.BitTransferSigned(ref val[3], ref val[2]); - BitArrayStream.BitTransferSigned(ref val[5], ref val[4]); - BitArrayStream.BitTransferSigned(ref val[7], ref val[6]); - - if (val[1] + val[3] + val[5] >= 0) - { - endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]); - endPoints[1] = new AstcPixel((short)(val[7] + val[6]), (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5])); - } - else - { - endPoints[0] = AstcPixel.BlueContract(val[6] + val[7], val[0] + val[1], val[2] + val[3], val[4] + val[5]); - endPoints[1] = AstcPixel.BlueContract(val[6], val[0], val[2], val[4]); - } - - endPoints[0].ClampByte(); - endPoints[1].ClampByte(); - - break; - } - - default: - throw new AstcDecoderException("Unsupported color endpoint mode (is it HDR?)"); - } - } - - static void DecodeColorValues( - int[] outputValues, - byte[] inputData, - uint[] modes, - int numberPartitions, - int numberBitsForColorData) - { - // First figure out how many color values we have - int numberValues = 0; - - for (int i = 0; i < numberPartitions; i++) - { - numberValues += (int)((modes[i] >> 2) + 1) << 1; - } - - // Then based on the number of values and the remaining number of bits, - // figure out the max value for each of them... - int range = 256; - - while (--range > 0) - { - IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(range); - int bitLength = intEncoded.GetBitLength(numberValues); - - if (bitLength <= numberBitsForColorData) - { - // Find the smallest possible range that matches the given encoding - while (--range > 0) - { - IntegerEncoded newIntEncoded = IntegerEncoded.CreateEncoding(range); - if (!newIntEncoded.MatchesEncoding(intEncoded)) - { - break; - } - } - - // Return to last matching range. - range++; - break; - } - } - - // We now have enough to decode our integer sequence. - List<IntegerEncoded> integerEncodedSequence = new List<IntegerEncoded>(); - BitArrayStream colorBitStream = new BitArrayStream(new BitArray(inputData)); - - IntegerEncoded.DecodeIntegerSequence(integerEncodedSequence, colorBitStream, range, numberValues); - - // Once we have the decoded values, we need to dequantize them to the 0-255 range - // This procedure is outlined in ASTC spec C.2.13 - int outputIndices = 0; - - foreach (IntegerEncoded intEncoded in integerEncodedSequence) - { - int bitLength = intEncoded.NumberBits; - int bitValue = intEncoded.BitValue; - - Debug.Assert(bitLength >= 1); - - int a = 0, b = 0, c = 0, d = 0; - // A is just the lsb replicated 9 times. - a = BitArrayStream.Replicate(bitValue & 1, 1, 9); - - switch (intEncoded.GetEncoding()) - { - case IntegerEncoded.EIntegerEncoding.JustBits: - { - outputValues[outputIndices++] = BitArrayStream.Replicate(bitValue, bitLength, 8); - - break; - } - - case IntegerEncoded.EIntegerEncoding.Trit: - { - d = intEncoded.TritValue; - - switch (bitLength) - { - case 1: - { - c = 204; - - break; - } - - case 2: - { - c = 93; - // B = b000b0bb0 - int b2 = (bitValue >> 1) & 1; - b = (b2 << 8) | (b2 << 4) | (b2 << 2) | (b2 << 1); - - break; - } - - case 3: - { - c = 44; - // B = cb000cbcb - int cb = (bitValue >> 1) & 3; - b = (cb << 7) | (cb << 2) | cb; - - break; - } - - - case 4: - { - c = 22; - // B = dcb000dcb - int dcb = (bitValue >> 1) & 7; - b = (dcb << 6) | dcb; - - break; - } - - case 5: - { - c = 11; - // B = edcb000ed - int edcb = (bitValue >> 1) & 0xF; - b = (edcb << 5) | (edcb >> 2); - - break; - } - - case 6: - { - c = 5; - // B = fedcb000f - int fedcb = (bitValue >> 1) & 0x1F; - b = (fedcb << 4) | (fedcb >> 4); - - break; - } - - default: - throw new AstcDecoderException("Unsupported trit encoding for color values!"); - } - - break; - } - - case IntegerEncoded.EIntegerEncoding.Quint: - { - d = intEncoded.QuintValue; - - switch (bitLength) - { - case 1: - { - c = 113; - - break; - } - - case 2: - { - c = 54; - // B = b0000bb00 - int b2 = (bitValue >> 1) & 1; - b = (b2 << 8) | (b2 << 3) | (b2 << 2); - - break; - } - - case 3: - { - c = 26; - // B = cb0000cbc - int cb = (bitValue >> 1) & 3; - b = (cb << 7) | (cb << 1) | (cb >> 1); - - break; - } - - case 4: - { - c = 13; - // B = dcb0000dc - int dcb = (bitValue >> 1) & 7; - b = (dcb << 6) | (dcb >> 1); - - break; - } - - case 5: - { - c = 6; - // B = edcb0000e - int edcb = (bitValue >> 1) & 0xF; - b = (edcb << 5) | (edcb >> 3); - - break; - } - - default: - throw new AstcDecoderException("Unsupported quint encoding for color values!"); - } - break; - } - } - - if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits) - { - int T = d * c + b; - T ^= a; - T = (a & 0x80) | (T >> 2); - - outputValues[outputIndices++] = T; - } - } - - // Make sure that each of our values is in the proper range... - for (int i = 0; i < numberValues; i++) - { - Debug.Assert(outputValues[i] <= 255); - } - } - - static void FillVoidExtentLdr(BitArrayStream bitStream, int[] outputBuffer, int blockWidth, int blockHeight) - { - // Don't actually care about the void extent, just read the bits... - for (int i = 0; i < 4; ++i) - { - bitStream.ReadBits(13); - } - - // Decode the RGBA components and renormalize them to the range [0, 255] - ushort r = (ushort)bitStream.ReadBits(16); - ushort g = (ushort)bitStream.ReadBits(16); - ushort b = (ushort)bitStream.ReadBits(16); - ushort a = (ushort)bitStream.ReadBits(16); - - int rgba = (r >> 8) | (g & 0xFF00) | ((b) & 0xFF00) << 8 | ((a) & 0xFF00) << 16; - - for (int j = 0; j < blockHeight; j++) - { - for (int i = 0; i < blockWidth; i++) - { - outputBuffer[j * blockWidth + i] = rgba; - } - } - } - - static TexelWeightParams DecodeBlockInfo(BitArrayStream bitStream) - { - TexelWeightParams texelParams = new TexelWeightParams(); - - // Read the entire block mode all at once - ushort modeBits = (ushort)bitStream.ReadBits(11); - - // Does this match the void extent block mode? - if ((modeBits & 0x01FF) == 0x1FC) - { - if ((modeBits & 0x200) != 0) - { - texelParams.VoidExtentHdr = true; - } - else - { - texelParams.VoidExtentLdr = true; - } - - // Next two bits must be one. - if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0) - { - texelParams.Error = true; - } - - return texelParams; - } - - // First check if the last four bits are zero - if ((modeBits & 0xF) == 0) - { - texelParams.Error = true; - return texelParams; - } - - // If the last two bits are zero, then if bits - // [6-8] are all ones, this is also reserved. - if ((modeBits & 0x3) == 0 && (modeBits & 0x1C0) == 0x1C0) - { - texelParams.Error = true; - - return texelParams; - } - - // Otherwise, there is no error... Figure out the layout - // of the block mode. Layout is determined by a number - // between 0 and 9 corresponding to table C.2.8 of the - // ASTC spec. - int layout = 0; - - if ((modeBits & 0x1) != 0 || (modeBits & 0x2) != 0) - { - // layout is in [0-4] - if ((modeBits & 0x8) != 0) - { - // layout is in [2-4] - if ((modeBits & 0x4) != 0) - { - // layout is in [3-4] - if ((modeBits & 0x100) != 0) - { - layout = 4; - } - else - { - layout = 3; - } - } - else - { - layout = 2; - } - } - else - { - // layout is in [0-1] - if ((modeBits & 0x4) != 0) - { - layout = 1; - } - else - { - layout = 0; - } - } - } - else - { - // layout is in [5-9] - if ((modeBits & 0x100) != 0) - { - // layout is in [7-9] - if ((modeBits & 0x80) != 0) - { - // layout is in [7-8] - Debug.Assert((modeBits & 0x40) == 0); - - if ((modeBits & 0x20) != 0) - { - layout = 8; - } - else - { - layout = 7; - } - } - else - { - layout = 9; - } - } - else - { - // layout is in [5-6] - if ((modeBits & 0x80) != 0) - { - layout = 6; - } - else - { - layout = 5; - } - } - } - - Debug.Assert(layout < 10); - - // Determine R - int r = (modeBits >> 4) & 1; - if (layout < 5) - { - r |= (modeBits & 0x3) << 1; - } - else - { - r |= (modeBits & 0xC) >> 1; - } - - Debug.Assert(2 <= r && r <= 7); - - // Determine width & height - switch (layout) - { - case 0: - { - int a = (modeBits >> 5) & 0x3; - int b = (modeBits >> 7) & 0x3; - - texelParams.Width = b + 4; - texelParams.Height = a + 2; - - break; - } - - case 1: - { - int a = (modeBits >> 5) & 0x3; - int b = (modeBits >> 7) & 0x3; - - texelParams.Width = b + 8; - texelParams.Height = a + 2; - - break; - } - - case 2: - { - int a = (modeBits >> 5) & 0x3; - int b = (modeBits >> 7) & 0x3; - - texelParams.Width = a + 2; - texelParams.Height = b + 8; - - break; - } - - case 3: - { - int a = (modeBits >> 5) & 0x3; - int b = (modeBits >> 7) & 0x1; - - texelParams.Width = a + 2; - texelParams.Height = b + 6; - - break; - } - - case 4: - { - int a = (modeBits >> 5) & 0x3; - int b = (modeBits >> 7) & 0x1; - - texelParams.Width = b + 2; - texelParams.Height = a + 2; - - break; - } - - case 5: - { - int a = (modeBits >> 5) & 0x3; - - texelParams.Width = 12; - texelParams.Height = a + 2; - - break; - } - - case 6: - { - int a = (modeBits >> 5) & 0x3; - - texelParams.Width = a + 2; - texelParams.Height = 12; - - break; - } - - case 7: - { - texelParams.Width = 6; - texelParams.Height = 10; - - break; - } - - case 8: - { - texelParams.Width = 10; - texelParams.Height = 6; - break; - } - - case 9: - { - int a = (modeBits >> 5) & 0x3; - int b = (modeBits >> 9) & 0x3; - - texelParams.Width = a + 6; - texelParams.Height = b + 6; - - break; - } - - default: - // Don't know this layout... - texelParams.Error = true; - break; - } - - // Determine whether or not we're using dual planes - // and/or high precision layouts. - bool d = ((layout != 9) && ((modeBits & 0x400) != 0)); - bool h = (layout != 9) && ((modeBits & 0x200) != 0); - - if (h) - { - int[] maxWeights = { 9, 11, 15, 19, 23, 31 }; - texelParams.MaxWeight = maxWeights[r - 2]; - } - else - { - int[] maxWeights = { 1, 2, 3, 4, 5, 7 }; - texelParams.MaxWeight = maxWeights[r - 2]; - } - - texelParams.DualPlane = d; - - return texelParams; - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs b/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs deleted file mode 100644 index 2f73c62b..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Diagnostics; - -namespace Ryujinx.Graphics.Texture -{ - class AstcPixel - { - public short R { get; set; } - public short G { get; set; } - public short B { get; set; } - public short A { get; set; } - - byte[] _bitDepth = new byte[4]; - - public AstcPixel(short a, short r, short g, short b) - { - A = a; - R = r; - G = g; - B = b; - - for (int i = 0; i < 4; i++) - _bitDepth[i] = 8; - } - - public void ClampByte() - { - R = Math.Min(Math.Max(R, (short)0), (short)255); - G = Math.Min(Math.Max(G, (short)0), (short)255); - B = Math.Min(Math.Max(B, (short)0), (short)255); - A = Math.Min(Math.Max(A, (short)0), (short)255); - } - - public short GetComponent(int index) - { - switch(index) - { - case 0: return A; - case 1: return R; - case 2: return G; - case 3: return B; - } - - return 0; - } - - public void SetComponent(int index, int value) - { - switch (index) - { - case 0: - A = (short)value; - break; - case 1: - R = (short)value; - break; - case 2: - G = (short)value; - break; - case 3: - B = (short)value; - break; - } - } - - public void ChangeBitDepth(byte[] depth) - { - for (int i = 0; i< 4; i++) - { - int value = ChangeBitDepth(GetComponent(i), _bitDepth[i], depth[i]); - - SetComponent(i, value); - _bitDepth[i] = depth[i]; - } - } - - short ChangeBitDepth(short value, byte oldDepth, byte newDepth) - { - Debug.Assert(newDepth <= 8); - Debug.Assert(oldDepth <= 8); - - if (oldDepth == newDepth) - { - // Do nothing - return value; - } - else if (oldDepth == 0 && newDepth != 0) - { - return (short)((1 << newDepth) - 1); - } - else if (newDepth > oldDepth) - { - return (short)BitArrayStream.Replicate(value, oldDepth, newDepth); - } - else - { - // oldDepth > newDepth - if (newDepth == 0) - { - return 0xFF; - } - else - { - byte bitsWasted = (byte)(oldDepth - newDepth); - short tempValue = value; - - tempValue = (short)((tempValue + (1 << (bitsWasted - 1))) >> bitsWasted); - tempValue = Math.Min(Math.Max((short)0, tempValue), (short)((1 << newDepth) - 1)); - - return (byte)(tempValue); - } - } - } - - public int Pack() - { - AstcPixel newPixel = new AstcPixel(A, R, G, B); - byte[] eightBitDepth = { 8, 8, 8, 8 }; - - newPixel.ChangeBitDepth(eightBitDepth); - - return (byte)newPixel.A << 24 | - (byte)newPixel.B << 16 | - (byte)newPixel.G << 8 | - (byte)newPixel.R << 0; - } - - // Adds more precision to the blue channel as described - // in C.2.14 - public static AstcPixel BlueContract(int a, int r, int g, int b) - { - return new AstcPixel((short)(a), - (short)((r + b) >> 1), - (short)((g + b) >> 1), - (short)(b)); - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs b/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs deleted file mode 100644 index 24069d72..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections; - -namespace Ryujinx.Graphics.Texture -{ - public class BitArrayStream - { - public BitArray BitsArray; - - public int Position { get; private set; } - - public BitArrayStream(BitArray bitArray) - { - BitsArray = bitArray; - Position = 0; - } - - public short ReadBits(int length) - { - int retValue = 0; - for (int i = Position; i < Position + length; i++) - { - if (BitsArray[i]) - { - retValue |= 1 << (i - Position); - } - } - - Position += length; - return (short)retValue; - } - - public int ReadBits(int start, int end) - { - int retValue = 0; - for (int i = start; i <= end; i++) - { - if (BitsArray[i]) - { - retValue |= 1 << (i - start); - } - } - - return retValue; - } - - public int ReadBit(int index) - { - return Convert.ToInt32(BitsArray[index]); - } - - public void WriteBits(int value, int length) - { - for (int i = Position; i < Position + length; i++) - { - BitsArray[i] = ((value >> (i - Position)) & 1) != 0; - } - - Position += length; - } - - public byte[] ToByteArray() - { - byte[] retArray = new byte[(BitsArray.Length + 7) / 8]; - BitsArray.CopyTo(retArray, 0); - return retArray; - } - - public static int Replicate(int value, int numberBits, int toBit) - { - if (numberBits == 0) return 0; - if (toBit == 0) return 0; - - int tempValue = value & ((1 << numberBits) - 1); - int retValue = tempValue; - int resLength = numberBits; - - while (resLength < toBit) - { - int comp = 0; - if (numberBits > toBit - resLength) - { - int newShift = toBit - resLength; - comp = numberBits - newShift; - numberBits = newShift; - } - retValue <<= numberBits; - retValue |= tempValue >> comp; - resLength += numberBits; - } - return retValue; - } - - public static int PopCnt(int number) - { - int counter; - for (counter = 0; number != 0; counter++) - { - number &= number - 1; - } - return counter; - } - - public static void Swap<T>(ref T lhs, ref T rhs) - { - T temp = lhs; - lhs = rhs; - rhs = temp; - } - - // Transfers a bit as described in C.2.14 - public static void BitTransferSigned(ref int a, ref int b) - { - b >>= 1; - b |= a & 0x80; - a >>= 1; - a &= 0x3F; - if ((a & 0x20) != 0) a -= 0x40; - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/BlockLinearSwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/BlockLinearSwizzle.cs deleted file mode 100644 index 682f7d67..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/BlockLinearSwizzle.cs +++ /dev/null @@ -1,186 +0,0 @@ -using Ryujinx.Common; -using System; - -namespace Ryujinx.Graphics.Texture -{ - class BlockLinearSwizzle : ISwizzle - { - private const int GobWidth = 64; - private const int GobHeight = 8; - - private const int GobSize = GobWidth * GobHeight; - - private int _texWidth; - private int _texHeight; - private int _texDepth; - private int _texGobBlockHeight; - private int _texGobBlockDepth; - private int _texBpp; - - private int _bhMask; - private int _bdMask; - - private int _bhShift; - private int _bdShift; - private int _bppShift; - - private int _xShift; - - private int _robSize; - private int _sliceSize; - - private int _baseOffset; - - public BlockLinearSwizzle( - int width, - int height, - int depth, - int gobBlockHeight, - int gobBlockDepth, - int bpp) - { - _texWidth = width; - _texHeight = height; - _texDepth = depth; - _texGobBlockHeight = gobBlockHeight; - _texGobBlockDepth = gobBlockDepth; - _texBpp = bpp; - - _bppShift = BitUtils.CountTrailingZeros32(bpp); - - SetMipLevel(0); - } - - public void SetMipLevel(int level) - { - _baseOffset = GetMipOffset(level); - - int width = Math.Max(1, _texWidth >> level); - int height = Math.Max(1, _texHeight >> level); - int depth = Math.Max(1, _texDepth >> level); - - GobBlockSizes gbSizes = AdjustGobBlockSizes(height, depth); - - _bhMask = gbSizes.Height - 1; - _bdMask = gbSizes.Depth - 1; - - _bhShift = BitUtils.CountTrailingZeros32(gbSizes.Height); - _bdShift = BitUtils.CountTrailingZeros32(gbSizes.Depth); - - _xShift = BitUtils.CountTrailingZeros32(GobSize * gbSizes.Height * gbSizes.Depth); - - RobAndSliceSizes gsSizes = GetRobAndSliceSizes(width, height, gbSizes); - - _robSize = gsSizes.RobSize; - _sliceSize = gsSizes.SliceSize; - } - - public int GetImageSize(int mipsCount) - { - int size = GetMipOffset(mipsCount); - - size = (size + 0x1fff) & ~0x1fff; - - return size; - } - - public int GetMipOffset(int level) - { - int totalSize = 0; - - for (int index = 0; index < level; index++) - { - int width = Math.Max(1, _texWidth >> index); - int height = Math.Max(1, _texHeight >> index); - int depth = Math.Max(1, _texDepth >> index); - - GobBlockSizes gbSizes = AdjustGobBlockSizes(height, depth); - - RobAndSliceSizes rsSizes = GetRobAndSliceSizes(width, height, gbSizes); - - totalSize += BitUtils.DivRoundUp(depth, gbSizes.Depth) * rsSizes.SliceSize; - } - - return totalSize; - } - - private struct GobBlockSizes - { - public int Height; - public int Depth; - - public GobBlockSizes(int gobBlockHeight, int gobBlockDepth) - { - Height = gobBlockHeight; - Depth = gobBlockDepth; - } - } - - private GobBlockSizes AdjustGobBlockSizes(int height, int depth) - { - int gobBlockHeight = _texGobBlockHeight; - int gobBlockDepth = _texGobBlockDepth; - - int pow2Height = BitUtils.Pow2RoundUp(height); - int pow2Depth = BitUtils.Pow2RoundUp(depth); - - while (gobBlockHeight * GobHeight > pow2Height && gobBlockHeight > 1) - { - gobBlockHeight >>= 1; - } - - while (gobBlockDepth > pow2Depth && gobBlockDepth > 1) - { - gobBlockDepth >>= 1; - } - - return new GobBlockSizes(gobBlockHeight, gobBlockDepth); - } - - private struct RobAndSliceSizes - { - public int RobSize; - public int SliceSize; - - public RobAndSliceSizes(int robSize, int sliceSize) - { - RobSize = robSize; - SliceSize = sliceSize; - } - } - - private RobAndSliceSizes GetRobAndSliceSizes(int width, int height, GobBlockSizes gbSizes) - { - int widthInGobs = BitUtils.DivRoundUp(width * _texBpp, GobWidth); - - int robSize = GobSize * gbSizes.Height * gbSizes.Depth * widthInGobs; - - int sliceSize = BitUtils.DivRoundUp(height, gbSizes.Height * GobHeight) * robSize; - - return new RobAndSliceSizes(robSize, sliceSize); - } - - public int GetSwizzleOffset(int x, int y, int z) - { - x <<= _bppShift; - - int yh = y / GobHeight; - - int position = (z >> _bdShift) * _sliceSize + (yh >> _bhShift) * _robSize; - - position += (x / GobWidth) << _xShift; - - position += (yh & _bhMask) * GobSize; - - position += ((z & _bdMask) * GobSize) << _bhShift; - - position += ((x & 0x3f) >> 5) << 8; - position += ((y & 0x07) >> 1) << 6; - position += ((x & 0x1f) >> 4) << 5; - position += ((y & 0x01) >> 0) << 4; - position += ((x & 0x0f) >> 0) << 0; - - return _baseOffset + position; - } - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/ISwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/ISwizzle.cs deleted file mode 100644 index fae3eada..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/ISwizzle.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Ryujinx.Graphics.Texture -{ - interface ISwizzle - { - int GetSwizzleOffset(int x, int y, int z); - - void SetMipLevel(int level); - - int GetMipOffset(int level); - - int GetImageSize(int mipsCount); - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/ImageUtils.cs b/Ryujinx.Graphics/Graphics3d/Texture/ImageUtils.cs deleted file mode 100644 index 10c36fe1..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/ImageUtils.cs +++ /dev/null @@ -1,561 +0,0 @@ -using ARMeilleure.Memory; -using OpenTK.Graphics.OpenGL; -using Ryujinx.Graphics.Gal; -using Ryujinx.Graphics.Memory; -using System; -using System.Collections.Generic; - -namespace Ryujinx.Graphics.Texture -{ - public static class ImageUtils - { - [Flags] - private enum TargetBuffer - { - Color = 1 << 0, - Depth = 1 << 1, - Stencil = 1 << 2, - - DepthStencil = Depth | Stencil - } - - private struct ImageDescriptor - { - public int BytesPerPixel { get; private set; } - public int BlockWidth { get; private set; } - public int BlockHeight { get; private set; } - public int BlockDepth { get; private set; } - - public TargetBuffer Target { get; private set; } - - public ImageDescriptor(int bytesPerPixel, int blockWidth, int blockHeight, int blockDepth, TargetBuffer target) - { - BytesPerPixel = bytesPerPixel; - BlockWidth = blockWidth; - BlockHeight = blockHeight; - BlockDepth = blockDepth; - Target = target; - } - } - - private const GalImageFormat Snorm = GalImageFormat.Snorm; - private const GalImageFormat Unorm = GalImageFormat.Unorm; - private const GalImageFormat Sint = GalImageFormat.Sint; - private const GalImageFormat Uint = GalImageFormat.Uint; - private const GalImageFormat Float = GalImageFormat.Float; - private const GalImageFormat Srgb = GalImageFormat.Srgb; - - private static readonly Dictionary<GalTextureFormat, GalImageFormat> TextureTable = - new Dictionary<GalTextureFormat, GalImageFormat>() - { - { GalTextureFormat.Rgba32, GalImageFormat.Rgba32 | Sint | Uint | Float }, - { GalTextureFormat.Rgba16, GalImageFormat.Rgba16 | Snorm | Unorm | Sint | Uint | Float }, - { GalTextureFormat.Rg32, GalImageFormat.Rg32 | Sint | Uint | Float }, - { GalTextureFormat.Rgba8, GalImageFormat.Rgba8 | Snorm | Unorm | Sint | Uint | Srgb }, - { GalTextureFormat.Rgb10A2, GalImageFormat.Rgb10A2 | Snorm | Unorm | Sint | Uint }, - { GalTextureFormat.Rg8, GalImageFormat.Rg8 | Snorm | Unorm | Sint | Uint }, - { GalTextureFormat.R16, GalImageFormat.R16 | Snorm | Unorm | Sint | Uint | Float }, - { GalTextureFormat.R8, GalImageFormat.R8 | Snorm | Unorm | Sint | Uint }, - { GalTextureFormat.Rg16, GalImageFormat.Rg16 | Snorm | Unorm | Sint | Float }, - { GalTextureFormat.R32, GalImageFormat.R32 | Sint | Uint | Float }, - { GalTextureFormat.Rgba4, GalImageFormat.Rgba4 | Unorm }, - { GalTextureFormat.Rgb5A1, GalImageFormat.Rgb5A1 | Unorm }, - { GalTextureFormat.Rgb565, GalImageFormat.Rgb565 | Unorm }, - { GalTextureFormat.R11G11B10F, GalImageFormat.R11G11B10 | Float }, - { GalTextureFormat.D24S8, GalImageFormat.D24S8 | Unorm | Uint }, - { GalTextureFormat.D32F, GalImageFormat.D32 | Float }, - { GalTextureFormat.D32Fx24S8, GalImageFormat.D32S8 | Float }, - { GalTextureFormat.D16, GalImageFormat.D16 | Unorm }, - - // Compressed formats - { GalTextureFormat.BptcSfloat, GalImageFormat.BptcSfloat | Float }, - { GalTextureFormat.BptcUfloat, GalImageFormat.BptcUfloat | Float }, - { GalTextureFormat.BptcUnorm, GalImageFormat.BptcUnorm | Unorm | Srgb }, - { GalTextureFormat.BC1, GalImageFormat.BC1 | Unorm | Srgb }, - { GalTextureFormat.BC2, GalImageFormat.BC2 | Unorm | Srgb }, - { GalTextureFormat.BC3, GalImageFormat.BC3 | Unorm | Srgb }, - { GalTextureFormat.BC4, GalImageFormat.BC4 | Unorm | Snorm }, - { GalTextureFormat.BC5, GalImageFormat.BC5 | Unorm | Snorm }, - { GalTextureFormat.Astc2D4x4, GalImageFormat.Astc2D4x4 | Unorm | Srgb }, - { GalTextureFormat.Astc2D5x5, GalImageFormat.Astc2D5x5 | Unorm | Srgb }, - { GalTextureFormat.Astc2D6x6, GalImageFormat.Astc2D6x6 | Unorm | Srgb }, - { GalTextureFormat.Astc2D8x8, GalImageFormat.Astc2D8x8 | Unorm | Srgb }, - { GalTextureFormat.Astc2D10x10, GalImageFormat.Astc2D10x10 | Unorm | Srgb }, - { GalTextureFormat.Astc2D12x12, GalImageFormat.Astc2D12x12 | Unorm | Srgb }, - { GalTextureFormat.Astc2D5x4, GalImageFormat.Astc2D5x4 | Unorm | Srgb }, - { GalTextureFormat.Astc2D6x5, GalImageFormat.Astc2D6x5 | Unorm | Srgb }, - { GalTextureFormat.Astc2D8x6, GalImageFormat.Astc2D8x6 | Unorm | Srgb }, - { GalTextureFormat.Astc2D10x8, GalImageFormat.Astc2D10x8 | Unorm | Srgb }, - { GalTextureFormat.Astc2D12x10, GalImageFormat.Astc2D12x10 | Unorm | Srgb }, - { GalTextureFormat.Astc2D8x5, GalImageFormat.Astc2D8x5 | Unorm | Srgb }, - { GalTextureFormat.Astc2D10x5, GalImageFormat.Astc2D10x5 | Unorm | Srgb }, - { GalTextureFormat.Astc2D10x6, GalImageFormat.Astc2D10x6 | Unorm | Srgb } - }; - - private static readonly Dictionary<GalImageFormat, ImageDescriptor> ImageTable = - new Dictionary<GalImageFormat, ImageDescriptor>() - { - { GalImageFormat.Rgba32, new ImageDescriptor(16, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rgba16, new ImageDescriptor(8, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rg32, new ImageDescriptor(8, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rgbx8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rgba8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Bgra8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rgb10A2, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.R32, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rgba4, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.BptcSfloat, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.BptcUfloat, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.Bgr5A1, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rgb5A1, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rgb565, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Bgr565, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.BptcUnorm, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.Rg16, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.Rg8, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.R16, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.R8, new ImageDescriptor(1, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.R11G11B10, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Color) }, - { GalImageFormat.BC1, new ImageDescriptor(8, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.BC2, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.BC3, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.BC4, new ImageDescriptor(8, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.BC5, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D4x4, new ImageDescriptor(16, 4, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D5x5, new ImageDescriptor(16, 5, 5, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D6x6, new ImageDescriptor(16, 6, 6, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D8x8, new ImageDescriptor(16, 8, 8, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D10x10, new ImageDescriptor(16, 10, 10, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D12x12, new ImageDescriptor(16, 12, 12, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D5x4, new ImageDescriptor(16, 5, 4, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D6x5, new ImageDescriptor(16, 6, 5, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D8x6, new ImageDescriptor(16, 8, 6, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D10x8, new ImageDescriptor(16, 10, 8, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D12x10, new ImageDescriptor(16, 12, 10, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D8x5, new ImageDescriptor(16, 8, 5, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D10x5, new ImageDescriptor(16, 10, 5, 1, TargetBuffer.Color) }, - { GalImageFormat.Astc2D10x6, new ImageDescriptor(16, 10, 6, 1, TargetBuffer.Color) }, - - { GalImageFormat.D16, new ImageDescriptor(2, 1, 1, 1, TargetBuffer.Depth) }, - { GalImageFormat.D24, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Depth) }, - { GalImageFormat.D24S8, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.DepthStencil) }, - { GalImageFormat.D32, new ImageDescriptor(4, 1, 1, 1, TargetBuffer.Depth) }, - { GalImageFormat.D32S8, new ImageDescriptor(8, 1, 1, 1, TargetBuffer.DepthStencil) } - }; - - public static GalImageFormat ConvertTexture( - GalTextureFormat format, - GalTextureType rType, - GalTextureType gType, - GalTextureType bType, - GalTextureType aType, - bool convSrgb) - { - if (!TextureTable.TryGetValue(format, out GalImageFormat imageFormat)) - { - throw new NotImplementedException($"Format 0x{((int)format):x} not implemented!"); - } - - if (!HasDepth(imageFormat) && (rType != gType || rType != bType || rType != aType)) - { - throw new NotImplementedException("Per component types are not implemented!"); - } - - GalImageFormat formatType = convSrgb ? Srgb : GetFormatType(rType); - - GalImageFormat combinedFormat = (imageFormat & GalImageFormat.FormatMask) | formatType; - - if (!imageFormat.HasFlag(formatType)) - { - throw new NotImplementedException($"Format \"{combinedFormat}\" not implemented!"); - } - - return combinedFormat; - } - - public static GalImageFormat ConvertSurface(GalSurfaceFormat format) - { - switch (format) - { - case GalSurfaceFormat.Rgba32Float: return GalImageFormat.Rgba32 | Float; - case GalSurfaceFormat.Rgba32Uint: return GalImageFormat.Rgba32 | Uint; - case GalSurfaceFormat.Rgba16Float: return GalImageFormat.Rgba16 | Float; - case GalSurfaceFormat.Rgba16Uint: return GalImageFormat.Rgba16 | Uint; - case GalSurfaceFormat.Rgba16Unorm: return GalImageFormat.Rgba16 | Unorm; - case GalSurfaceFormat.Rg32Float: return GalImageFormat.Rg32 | Float; - case GalSurfaceFormat.Rg32Sint: return GalImageFormat.Rg32 | Sint; - case GalSurfaceFormat.Rg32Uint: return GalImageFormat.Rg32 | Uint; - case GalSurfaceFormat.Bgra8Unorm: return GalImageFormat.Bgra8 | Unorm; - case GalSurfaceFormat.Bgra8Srgb: return GalImageFormat.Bgra8 | Srgb; - case GalSurfaceFormat.Rgb10A2Unorm: return GalImageFormat.Rgb10A2 | Unorm; - case GalSurfaceFormat.Rgba8Unorm: return GalImageFormat.Rgba8 | Unorm; - case GalSurfaceFormat.Rgba8Srgb: return GalImageFormat.Rgba8 | Srgb; - case GalSurfaceFormat.Rgba8Snorm: return GalImageFormat.Rgba8 | Snorm; - case GalSurfaceFormat.Rg16Snorm: return GalImageFormat.Rg16 | Snorm; - case GalSurfaceFormat.Rg16Unorm: return GalImageFormat.Rg16 | Unorm; - case GalSurfaceFormat.Rg16Sint: return GalImageFormat.Rg16 | Sint; - case GalSurfaceFormat.Rg16Float: return GalImageFormat.Rg16 | Float; - case GalSurfaceFormat.R11G11B10Float: return GalImageFormat.R11G11B10 | Float; - case GalSurfaceFormat.R32Float: return GalImageFormat.R32 | Float; - case GalSurfaceFormat.R32Uint: return GalImageFormat.R32 | Uint; - case GalSurfaceFormat.Rg8Unorm: return GalImageFormat.Rg8 | Unorm; - case GalSurfaceFormat.Rg8Snorm: return GalImageFormat.Rg8 | Snorm; - case GalSurfaceFormat.R16Float: return GalImageFormat.R16 | Float; - case GalSurfaceFormat.R16Unorm: return GalImageFormat.R16 | Unorm; - case GalSurfaceFormat.R16Uint: return GalImageFormat.R16 | Uint; - case GalSurfaceFormat.R8Unorm: return GalImageFormat.R8 | Unorm; - case GalSurfaceFormat.R8Uint: return GalImageFormat.R8 | Uint; - case GalSurfaceFormat.B5G6R5Unorm: return GalImageFormat.Rgb565 | Unorm; - case GalSurfaceFormat.Bgr5A1Unorm: return GalImageFormat.Bgr5A1 | Unorm; - case GalSurfaceFormat.Rgbx8Unorm: return GalImageFormat.Rgbx8 | Unorm; - } - - throw new NotImplementedException(format.ToString()); - } - - public static GalImageFormat ConvertZeta(GalZetaFormat format) - { - switch (format) - { - case GalZetaFormat.D32Float: return GalImageFormat.D32 | Float; - case GalZetaFormat.S8D24Unorm: return GalImageFormat.D24S8 | Unorm; - case GalZetaFormat.D16Unorm: return GalImageFormat.D16 | Unorm; - case GalZetaFormat.D24X8Unorm: return GalImageFormat.D24 | Unorm; - case GalZetaFormat.D24S8Unorm: return GalImageFormat.D24S8 | Unorm; - case GalZetaFormat.D32S8X24Float: return GalImageFormat.D32S8 | Float; - } - - throw new NotImplementedException(format.ToString()); - } - - public static byte[] ReadTexture(IMemory memory, GalImage image, long position) - { - MemoryManager cpuMemory; - - if (memory is NvGpuVmm vmm) - { - cpuMemory = vmm.Memory; - } - else - { - cpuMemory = (MemoryManager)memory; - } - - ISwizzle swizzle = TextureHelper.GetSwizzle(image); - - ImageDescriptor desc = GetImageDescriptor(image.Format); - - (int width, int height, int depth) = GetImageSizeInBlocks(image); - - int bytesPerPixel = desc.BytesPerPixel; - - // Note: Each row of the texture needs to be aligned to 4 bytes. - int pitch = (width * bytesPerPixel + 3) & ~3; - - int dataLayerSize = height * pitch * depth; - byte[] data = new byte[dataLayerSize * image.LayerCount]; - - int targetMipLevel = image.MaxMipmapLevel <= 1 ? 1 : image.MaxMipmapLevel - 1; - int layerOffset = GetLayerOffset(image, targetMipLevel); - - for (int layer = 0; layer < image.LayerCount; layer++) - { - for (int z = 0; z < depth; z++) - { - for (int y = 0; y < height; y++) - { - int outOffs = (dataLayerSize * layer) + y * pitch + (z * width * height * bytesPerPixel); - - for (int x = 0; x < width; x++) - { - long offset = (uint)swizzle.GetSwizzleOffset(x, y, z); - - cpuMemory.ReadBytes(position + (layerOffset * layer) + offset, data, outOffs, bytesPerPixel); - - outOffs += bytesPerPixel; - } - } - } - } - - return data; - } - - public static void WriteTexture(NvGpuVmm vmm, GalImage image, long position, byte[] data) - { - ISwizzle swizzle = TextureHelper.GetSwizzle(image); - - ImageDescriptor desc = GetImageDescriptor(image.Format); - - (int width, int height, int depth) = GetImageSizeInBlocks(image); - - int bytesPerPixel = desc.BytesPerPixel; - - int inOffs = 0; - - for (int z = 0; z < depth; z++) - for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) - { - long offset = (uint)swizzle.GetSwizzleOffset(x, y, z); - - vmm.Memory.WriteBytes(position + offset, data, inOffs, bytesPerPixel); - - inOffs += bytesPerPixel; - } - } - - // TODO: Support non 2D - public static bool CopyTexture( - NvGpuVmm vmm, - GalImage srcImage, - GalImage dstImage, - long srcAddress, - long dstAddress, - int srcX, - int srcY, - int dstX, - int dstY, - int width, - int height) - { - ISwizzle srcSwizzle = TextureHelper.GetSwizzle(srcImage); - ISwizzle dstSwizzle = TextureHelper.GetSwizzle(dstImage); - - ImageDescriptor desc = GetImageDescriptor(srcImage.Format); - - if (GetImageDescriptor(dstImage.Format).BytesPerPixel != desc.BytesPerPixel) - { - return false; - } - - int bytesPerPixel = desc.BytesPerPixel; - - for (int y = 0; y < height; y++) - for (int x = 0; x < width; x++) - { - long srcOffset = (uint)srcSwizzle.GetSwizzleOffset(srcX + x, srcY + y, 0); - long dstOffset = (uint)dstSwizzle.GetSwizzleOffset(dstX + x, dstY + y, 0); - - byte[] texel = vmm.ReadBytes(srcAddress + srcOffset, bytesPerPixel); - - vmm.WriteBytes(dstAddress + dstOffset, texel); - } - - return true; - } - - public static int GetSize(GalImage image) - { - ImageDescriptor desc = GetImageDescriptor(image.Format); - - int componentCount = GetCoordsCountTextureTarget(image.TextureTarget); - - if (IsArray(image.TextureTarget)) - componentCount--; - - int width = DivRoundUp(image.Width, desc.BlockWidth); - int height = DivRoundUp(image.Height, desc.BlockHeight); - int depth = DivRoundUp(image.Depth, desc.BlockDepth); - - switch (componentCount) - { - case 1: - return desc.BytesPerPixel * width * image.LayerCount; - case 2: - return desc.BytesPerPixel * width * height * image.LayerCount; - case 3: - return desc.BytesPerPixel * width * height * depth * image.LayerCount; - default: - throw new InvalidOperationException($"Invalid component count: {componentCount}"); - } - } - - public static int GetGpuSize(GalImage image, bool forcePitch = false) - { - return TextureHelper.GetSwizzle(image).GetImageSize(image.MaxMipmapLevel) * image.LayerCount; - } - - public static int GetLayerOffset(GalImage image, int mipLevel) - { - if (mipLevel <= 0) - { - mipLevel = 1; - } - - return TextureHelper.GetSwizzle(image).GetMipOffset(mipLevel); - } - - public static int GetPitch(GalImageFormat format, int width) - { - ImageDescriptor desc = GetImageDescriptor(format); - - int pitch = desc.BytesPerPixel * DivRoundUp(width, desc.BlockWidth); - - pitch = (pitch + 0x1f) & ~0x1f; - - return pitch; - } - - public static int GetBlockWidth(GalImageFormat format) - { - return GetImageDescriptor(format).BlockWidth; - } - - public static int GetBlockHeight(GalImageFormat format) - { - return GetImageDescriptor(format).BlockHeight; - } - - public static int GetBlockDepth(GalImageFormat format) - { - return GetImageDescriptor(format).BlockDepth; - } - - public static int GetAlignedWidth(GalImage image) - { - ImageDescriptor desc = GetImageDescriptor(image.Format); - - int alignMask; - - if (image.Layout == GalMemoryLayout.BlockLinear) - { - alignMask = image.TileWidth * (64 / desc.BytesPerPixel) - 1; - } - else - { - alignMask = (32 / desc.BytesPerPixel) - 1; - } - - return (image.Width + alignMask) & ~alignMask; - } - - public static (int Width, int Height, int Depth) GetImageSizeInBlocks(GalImage image) - { - ImageDescriptor desc = GetImageDescriptor(image.Format); - - return (DivRoundUp(image.Width, desc.BlockWidth), - DivRoundUp(image.Height, desc.BlockHeight), - DivRoundUp(image.Depth, desc.BlockDepth)); - } - - public static int GetBytesPerPixel(GalImageFormat format) - { - return GetImageDescriptor(format).BytesPerPixel; - } - - private static int DivRoundUp(int lhs, int rhs) - { - return (lhs + (rhs - 1)) / rhs; - } - - public static bool HasColor(GalImageFormat format) - { - return (GetImageDescriptor(format).Target & TargetBuffer.Color) != 0; - } - - public static bool HasDepth(GalImageFormat format) - { - return (GetImageDescriptor(format).Target & TargetBuffer.Depth) != 0; - } - - public static bool HasStencil(GalImageFormat format) - { - return (GetImageDescriptor(format).Target & TargetBuffer.Stencil) != 0; - } - - public static bool IsCompressed(GalImageFormat format) - { - ImageDescriptor desc = GetImageDescriptor(format); - - return (desc.BlockWidth | desc.BlockHeight) != 1; - } - - private static ImageDescriptor GetImageDescriptor(GalImageFormat format) - { - GalImageFormat pixelFormat = format & GalImageFormat.FormatMask; - - if (ImageTable.TryGetValue(pixelFormat, out ImageDescriptor descriptor)) - { - return descriptor; - } - - throw new NotImplementedException($"Format \"{pixelFormat}\" not implemented!"); - } - - private static GalImageFormat GetFormatType(GalTextureType type) - { - switch (type) - { - case GalTextureType.Snorm: return Snorm; - case GalTextureType.Unorm: return Unorm; - case GalTextureType.Sint: return Sint; - case GalTextureType.Uint: return Uint; - case GalTextureType.Float: return Float; - - default: throw new NotImplementedException(((int)type).ToString()); - } - } - - public static TextureTarget GetTextureTarget(GalTextureTarget galTextureTarget) - { - switch (galTextureTarget) - { - case GalTextureTarget.OneD: - return TextureTarget.Texture1D; - case GalTextureTarget.TwoD: - case GalTextureTarget.TwoDNoMipMap: - return TextureTarget.Texture2D; - case GalTextureTarget.ThreeD: - return TextureTarget.Texture3D; - case GalTextureTarget.OneDArray: - return TextureTarget.Texture1DArray; - case GalTextureTarget.OneDBuffer: - return TextureTarget.TextureBuffer; - case GalTextureTarget.TwoDArray: - return TextureTarget.Texture2DArray; - case GalTextureTarget.CubeMap: - return TextureTarget.TextureCubeMap; - case GalTextureTarget.CubeArray: - return TextureTarget.TextureCubeMapArray; - default: - throw new NotSupportedException($"Texture target {galTextureTarget} currently not supported!"); - } - } - - public static bool IsArray(GalTextureTarget textureTarget) - { - switch (textureTarget) - { - case GalTextureTarget.OneDArray: - case GalTextureTarget.TwoDArray: - case GalTextureTarget.CubeArray: - return true; - default: - return false; - } - } - - public static int GetCoordsCountTextureTarget(GalTextureTarget textureTarget) - { - switch (textureTarget) - { - case GalTextureTarget.OneD: - return 1; - case GalTextureTarget.OneDArray: - case GalTextureTarget.OneDBuffer: - case GalTextureTarget.TwoD: - case GalTextureTarget.TwoDNoMipMap: - return 2; - case GalTextureTarget.ThreeD: - case GalTextureTarget.TwoDArray: - case GalTextureTarget.CubeMap: - return 3; - case GalTextureTarget.CubeArray: - return 4; - default: - throw new NotImplementedException($"TextureTarget.{textureTarget} not implemented yet."); - } - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs b/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs deleted file mode 100644 index e6d67058..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs +++ /dev/null @@ -1,269 +0,0 @@ -using System.Collections; -using System.Collections.Generic; - -namespace Ryujinx.Graphics.Texture -{ - public struct IntegerEncoded - { - public enum EIntegerEncoding - { - JustBits, - Quint, - Trit - } - - EIntegerEncoding _encoding; - public int NumberBits { get; private set; } - public int BitValue { get; private set; } - public int TritValue { get; private set; } - public int QuintValue { get; private set; } - - public IntegerEncoded(EIntegerEncoding encoding, int numBits) - { - _encoding = encoding; - NumberBits = numBits; - BitValue = 0; - TritValue = 0; - QuintValue = 0; - } - - public bool MatchesEncoding(IntegerEncoded other) - { - return _encoding == other._encoding && NumberBits == other.NumberBits; - } - - public EIntegerEncoding GetEncoding() - { - return _encoding; - } - - public int GetBitLength(int numberVals) - { - int totalBits = NumberBits * numberVals; - if (_encoding == EIntegerEncoding.Trit) - { - totalBits += (numberVals * 8 + 4) / 5; - } - else if (_encoding == EIntegerEncoding.Quint) - { - totalBits += (numberVals * 7 + 2) / 3; - } - return totalBits; - } - - public static IntegerEncoded CreateEncoding(int maxVal) - { - while (maxVal > 0) - { - int check = maxVal + 1; - - // Is maxVal a power of two? - if ((check & (check - 1)) == 0) - { - return new IntegerEncoded(EIntegerEncoding.JustBits, BitArrayStream.PopCnt(maxVal)); - } - - // Is maxVal of the type 3*2^n - 1? - if ((check % 3 == 0) && ((check / 3) & ((check / 3) - 1)) == 0) - { - return new IntegerEncoded(EIntegerEncoding.Trit, BitArrayStream.PopCnt(check / 3 - 1)); - } - - // Is maxVal of the type 5*2^n - 1? - if ((check % 5 == 0) && ((check / 5) & ((check / 5) - 1)) == 0) - { - return new IntegerEncoded(EIntegerEncoding.Quint, BitArrayStream.PopCnt(check / 5 - 1)); - } - - // Apparently it can't be represented with a bounded integer sequence... - // just iterate. - maxVal--; - } - - return new IntegerEncoded(EIntegerEncoding.JustBits, 0); - } - - public static void DecodeTritBlock( - BitArrayStream bitStream, - List<IntegerEncoded> listIntegerEncoded, - int numberBitsPerValue) - { - // Implement the algorithm in section C.2.12 - int[] m = new int[5]; - int[] t = new int[5]; - int T; - - // Read the trit encoded block according to - // table C.2.14 - m[0] = bitStream.ReadBits(numberBitsPerValue); - T = bitStream.ReadBits(2); - m[1] = bitStream.ReadBits(numberBitsPerValue); - T |= bitStream.ReadBits(2) << 2; - m[2] = bitStream.ReadBits(numberBitsPerValue); - T |= bitStream.ReadBits(1) << 4; - m[3] = bitStream.ReadBits(numberBitsPerValue); - T |= bitStream.ReadBits(2) << 5; - m[4] = bitStream.ReadBits(numberBitsPerValue); - T |= bitStream.ReadBits(1) << 7; - - int c = 0; - - BitArrayStream tb = new BitArrayStream(new BitArray(new int[] { T })); - if (tb.ReadBits(2, 4) == 7) - { - c = (tb.ReadBits(5, 7) << 2) | tb.ReadBits(0, 1); - t[4] = t[3] = 2; - } - else - { - c = tb.ReadBits(0, 4); - if (tb.ReadBits(5, 6) == 3) - { - t[4] = 2; - t[3] = tb.ReadBit(7); - } - else - { - t[4] = tb.ReadBit(7); - t[3] = tb.ReadBits(5, 6); - } - } - - BitArrayStream cb = new BitArrayStream(new BitArray(new int[] { c })); - if (cb.ReadBits(0, 1) == 3) - { - t[2] = 2; - t[1] = cb.ReadBit(4); - t[0] = (cb.ReadBit(3) << 1) | (cb.ReadBit(2) & ~cb.ReadBit(3)); - } - else if (cb.ReadBits(2, 3) == 3) - { - t[2] = 2; - t[1] = 2; - t[0] = cb.ReadBits(0, 1); - } - else - { - t[2] = cb.ReadBit(4); - t[1] = cb.ReadBits(2, 3); - t[0] = (cb.ReadBit(1) << 1) | (cb.ReadBit(0) & ~cb.ReadBit(1)); - } - - for (int i = 0; i < 5; i++) - { - IntegerEncoded intEncoded = new IntegerEncoded(EIntegerEncoding.Trit, numberBitsPerValue) - { - BitValue = m[i], - TritValue = t[i] - }; - listIntegerEncoded.Add(intEncoded); - } - } - - public static void DecodeQuintBlock( - BitArrayStream bitStream, - List<IntegerEncoded> listIntegerEncoded, - int numberBitsPerValue) - { - // Implement the algorithm in section C.2.12 - int[] m = new int[3]; - int[] qa = new int[3]; - int q; - - // Read the trit encoded block according to - // table C.2.15 - m[0] = bitStream.ReadBits(numberBitsPerValue); - q = bitStream.ReadBits(3); - m[1] = bitStream.ReadBits(numberBitsPerValue); - q |= bitStream.ReadBits(2) << 3; - m[2] = bitStream.ReadBits(numberBitsPerValue); - q |= bitStream.ReadBits(2) << 5; - - BitArrayStream qb = new BitArrayStream(new BitArray(new int[] { q })); - if (qb.ReadBits(1, 2) == 3 && qb.ReadBits(5, 6) == 0) - { - qa[0] = qa[1] = 4; - qa[2] = (qb.ReadBit(0) << 2) | ((qb.ReadBit(4) & ~qb.ReadBit(0)) << 1) | (qb.ReadBit(3) & ~qb.ReadBit(0)); - } - else - { - int c = 0; - if (qb.ReadBits(1, 2) == 3) - { - qa[2] = 4; - c = (qb.ReadBits(3, 4) << 3) | ((~qb.ReadBits(5, 6) & 3) << 1) | qb.ReadBit(0); - } - else - { - qa[2] = qb.ReadBits(5, 6); - c = qb.ReadBits(0, 4); - } - - BitArrayStream cb = new BitArrayStream(new BitArray(new int[] { c })); - if (cb.ReadBits(0, 2) == 5) - { - qa[1] = 4; - qa[0] = cb.ReadBits(3, 4); - } - else - { - qa[1] = cb.ReadBits(3, 4); - qa[0] = cb.ReadBits(0, 2); - } - } - - for (int i = 0; i < 3; i++) - { - IntegerEncoded intEncoded = new IntegerEncoded(EIntegerEncoding.Quint, numberBitsPerValue) - { - BitValue = m[i], - QuintValue = qa[i] - }; - listIntegerEncoded.Add(intEncoded); - } - } - - public static void DecodeIntegerSequence( - List<IntegerEncoded> decodeIntegerSequence, - BitArrayStream bitStream, - int maxRange, - int numberValues) - { - // Determine encoding parameters - IntegerEncoded intEncoded = CreateEncoding(maxRange); - - // Start decoding - int numberValuesDecoded = 0; - while (numberValuesDecoded < numberValues) - { - switch (intEncoded.GetEncoding()) - { - case EIntegerEncoding.Quint: - { - DecodeQuintBlock(bitStream, decodeIntegerSequence, intEncoded.NumberBits); - numberValuesDecoded += 3; - - break; - } - - case EIntegerEncoding.Trit: - { - DecodeTritBlock(bitStream, decodeIntegerSequence, intEncoded.NumberBits); - numberValuesDecoded += 5; - - break; - } - - case EIntegerEncoding.JustBits: - { - intEncoded.BitValue = bitStream.ReadBits(intEncoded.NumberBits); - decodeIntegerSequence.Add(intEncoded); - numberValuesDecoded++; - - break; - } - } - } - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/LinearSwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/LinearSwizzle.cs deleted file mode 100644 index fb1bd098..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/LinearSwizzle.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; - -namespace Ryujinx.Graphics.Texture -{ - class LinearSwizzle : ISwizzle - { - private int _pitch; - private int _bpp; - - private int _sliceSize; - - public LinearSwizzle(int pitch, int bpp, int width, int height) - { - _pitch = pitch; - _bpp = bpp; - _sliceSize = width * height * bpp; - } - - public void SetMipLevel(int level) - { - throw new NotImplementedException(); - } - - public int GetMipOffset(int level) - { - if (level == 1) - return _sliceSize; - throw new NotImplementedException(); - } - - public int GetImageSize(int mipsCount) - { - int size = GetMipOffset(mipsCount); - - size = (size + 0x1fff) & ~0x1fff; - - return size; - } - - public int GetSwizzleOffset(int x, int y, int z) - { - return z * _sliceSize + x * _bpp + y * _pitch; - } - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/TextureFactory.cs b/Ryujinx.Graphics/Graphics3d/Texture/TextureFactory.cs deleted file mode 100644 index 28c90502..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/TextureFactory.cs +++ /dev/null @@ -1,166 +0,0 @@ -using Ryujinx.Graphics.Gal; -using Ryujinx.Graphics.Memory; -using System; - -namespace Ryujinx.Graphics.Texture -{ - static class TextureFactory - { - public static GalImage MakeTexture(NvGpuVmm vmm, long ticPosition) - { - int[] tic = ReadWords(vmm, ticPosition, 8); - - GalImageFormat format = GetImageFormat(tic); - - GalTextureTarget textureTarget = (GalTextureTarget)((tic[4] >> 23) & 0xF); - - GalTextureSource xSource = (GalTextureSource)((tic[0] >> 19) & 7); - GalTextureSource ySource = (GalTextureSource)((tic[0] >> 22) & 7); - GalTextureSource zSource = (GalTextureSource)((tic[0] >> 25) & 7); - GalTextureSource wSource = (GalTextureSource)((tic[0] >> 28) & 7); - - TextureSwizzle swizzle = (TextureSwizzle)((tic[2] >> 21) & 7); - - int maxMipmapLevel = (tic[3] >> 28) & 0xF + 1; - - GalMemoryLayout layout; - - if (swizzle == TextureSwizzle.BlockLinear || - swizzle == TextureSwizzle.BlockLinearColorKey) - { - layout = GalMemoryLayout.BlockLinear; - } - else - { - layout = GalMemoryLayout.Pitch; - } - - int gobBlockHeightLog2 = (tic[3] >> 3) & 7; - int gobBlockDepthLog2 = (tic[3] >> 6) & 7; - int tileWidthLog2 = (tic[3] >> 10) & 7; - - int gobBlockHeight = 1 << gobBlockHeightLog2; - int gobBlockDepth = 1 << gobBlockDepthLog2; - int tileWidth = 1 << tileWidthLog2; - - int width = ((tic[4] >> 0) & 0xffff) + 1; - int height = ((tic[5] >> 0) & 0xffff) + 1; - int depth = ((tic[5] >> 16) & 0x3fff) + 1; - - int layoutCount = 1; - - // TODO: check this - if (ImageUtils.IsArray(textureTarget)) - { - layoutCount = depth; - depth = 1; - } - - if (textureTarget == GalTextureTarget.OneD) - { - height = 1; - } - - if (textureTarget == GalTextureTarget.TwoD || textureTarget == GalTextureTarget.OneD) - { - depth = 1; - } - else if (textureTarget == GalTextureTarget.CubeMap) - { - // FIXME: This is a bit hacky but I guess it's fine for now - layoutCount = 6; - depth = 1; - } - else if (textureTarget == GalTextureTarget.CubeArray) - { - // FIXME: This is a really really hacky but I guess it's fine for now - layoutCount *= 6; - depth = 1; - } - - GalImage image = new GalImage( - width, - height, - depth, - layoutCount, - tileWidth, - gobBlockHeight, - gobBlockDepth, - layout, - format, - textureTarget, - maxMipmapLevel, - xSource, - ySource, - zSource, - wSource); - - if (layout == GalMemoryLayout.Pitch) - { - image.Pitch = (tic[3] & 0xffff) << 5; - } - - return image; - } - - public static GalTextureSampler MakeSampler(NvGpu gpu, NvGpuVmm vmm, long tscPosition) - { - int[] tsc = ReadWords(vmm, tscPosition, 8); - - GalTextureWrap addressU = (GalTextureWrap)((tsc[0] >> 0) & 7); - GalTextureWrap addressV = (GalTextureWrap)((tsc[0] >> 3) & 7); - GalTextureWrap addressP = (GalTextureWrap)((tsc[0] >> 6) & 7); - - bool depthCompare = ((tsc[0] >> 9) & 1) == 1; - - DepthCompareFunc depthCompareFunc = (DepthCompareFunc)((tsc[0] >> 10) & 7); - - GalTextureFilter magFilter = (GalTextureFilter) ((tsc[1] >> 0) & 3); - GalTextureFilter minFilter = (GalTextureFilter) ((tsc[1] >> 4) & 3); - GalTextureMipFilter mipFilter = (GalTextureMipFilter)((tsc[1] >> 6) & 3); - - GalColorF borderColor = new GalColorF( - BitConverter.Int32BitsToSingle(tsc[4]), - BitConverter.Int32BitsToSingle(tsc[5]), - BitConverter.Int32BitsToSingle(tsc[6]), - BitConverter.Int32BitsToSingle(tsc[7])); - - return new GalTextureSampler( - addressU, - addressV, - addressP, - minFilter, - magFilter, - mipFilter, - borderColor, - depthCompare, - depthCompareFunc); - } - - private static GalImageFormat GetImageFormat(int[] tic) - { - GalTextureType rType = (GalTextureType)((tic[0] >> 7) & 7); - GalTextureType gType = (GalTextureType)((tic[0] >> 10) & 7); - GalTextureType bType = (GalTextureType)((tic[0] >> 13) & 7); - GalTextureType aType = (GalTextureType)((tic[0] >> 16) & 7); - - GalTextureFormat format = (GalTextureFormat)(tic[0] & 0x7f); - - bool convSrgb = ((tic[4] >> 22) & 1) != 0; - - return ImageUtils.ConvertTexture(format, rType, gType, bType, aType, convSrgb); - } - - private static int[] ReadWords(NvGpuVmm vmm, long position, int count) - { - int[] words = new int[count]; - - for (int index = 0; index < count; index++, position += 4) - { - words[index] = vmm.ReadInt32(position); - } - - return words; - } - } -}
\ No newline at end of file diff --git a/Ryujinx.Graphics/Graphics3d/Texture/TextureHelper.cs b/Ryujinx.Graphics/Graphics3d/Texture/TextureHelper.cs deleted file mode 100644 index e07eb037..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/TextureHelper.cs +++ /dev/null @@ -1,53 +0,0 @@ -using ARMeilleure.Memory; -using Ryujinx.Common; -using Ryujinx.Graphics.Gal; -using Ryujinx.Graphics.Memory; - -namespace Ryujinx.Graphics.Texture -{ - static class TextureHelper - { - public static ISwizzle GetSwizzle(GalImage image) - { - int blockWidth = ImageUtils.GetBlockWidth (image.Format); - int blockHeight = ImageUtils.GetBlockHeight (image.Format); - int blockDepth = ImageUtils.GetBlockDepth (image.Format); - int bytesPerPixel = ImageUtils.GetBytesPerPixel(image.Format); - - int width = BitUtils.DivRoundUp(image.Width, blockWidth); - int height = BitUtils.DivRoundUp(image.Height, blockHeight); - int depth = BitUtils.DivRoundUp(image.Depth, blockDepth); - - if (image.Layout == GalMemoryLayout.BlockLinear) - { - int alignMask = image.TileWidth * (64 / bytesPerPixel) - 1; - - width = (width + alignMask) & ~alignMask; - - return new BlockLinearSwizzle( - width, - height, - depth, - image.GobBlockHeight, - image.GobBlockDepth, - bytesPerPixel); - } - else - { - return new LinearSwizzle(image.Pitch, bytesPerPixel, width, height); - } - } - - public static (MemoryManager Memory, long Position) GetMemoryAndPosition( - IMemory memory, - long position) - { - if (memory is NvGpuVmm vmm) - { - return (vmm.Memory, vmm.GetPhysicalAddress(position)); - } - - return ((MemoryManager)memory, position); - } - } -} diff --git a/Ryujinx.Graphics/Graphics3d/Texture/TextureSwizzle.cs b/Ryujinx.Graphics/Graphics3d/Texture/TextureSwizzle.cs deleted file mode 100644 index 2cc426ab..00000000 --- a/Ryujinx.Graphics/Graphics3d/Texture/TextureSwizzle.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Ryujinx.Graphics.Texture -{ - public enum TextureSwizzle - { - _1DBuffer = 0, - PitchColorKey = 1, - Pitch = 2, - BlockLinear = 3, - BlockLinearColorKey = 4 - } -}
\ No newline at end of file |
