diff --git a/ARMeilleure/Instructions/InstEmitMemoryHelper.cs b/ARMeilleure/Instructions/InstEmitMemoryHelper.cs
index 0ae5e3f26..e0b44353b 100644
--- a/ARMeilleure/Instructions/InstEmitMemoryHelper.cs
+++ b/ARMeilleure/Instructions/InstEmitMemoryHelper.cs
@@ -355,12 +355,9 @@ namespace ARMeilleure.Instructions
}
while (bit < context.Memory.AddressSpaceBits);
- if (!context.Memory.HasWriteWatchSupport)
- {
- Operand hasFlagSet = context.BitwiseAnd(pte, Const((long)MemoryManager.PteFlagsMask));
+ Operand hasFlagSet = context.BitwiseAnd(pte, Const((long)MemoryManager.PteFlagsMask));
- context.BranchIfTrue(lblFallbackPath, hasFlagSet);
- }
+ context.BranchIfTrue(lblFallbackPath, hasFlagSet);
Operand pageOffset = context.BitwiseAnd(address, Const(address.Type, MemoryManager.PageMask));
diff --git a/ARMeilleure/Memory/IMemory.cs b/ARMeilleure/Memory/IMemory.cs
deleted file mode 100644
index 0c3849c07..000000000
--- a/ARMeilleure/Memory/IMemory.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-namespace ARMeilleure.Memory
-{
- public interface IMemory
- {
- sbyte ReadSByte(long position);
-
- short ReadInt16(long position);
-
- int ReadInt32(long position);
-
- long ReadInt64(long position);
-
- byte ReadByte(long position);
-
- ushort ReadUInt16(long position);
-
- uint ReadUInt32(long position);
-
- ulong ReadUInt64(long position);
-
- void WriteSByte(long position, sbyte value);
-
- void WriteInt16(long position, short value);
-
- void WriteInt32(long position, int value);
-
- void WriteInt64(long position, long value);
-
- void WriteByte(long position, byte value);
-
- void WriteUInt16(long position, ushort value);
-
- void WriteUInt32(long position, uint value);
-
- void WriteUInt64(long position, ulong value);
- }
-}
\ No newline at end of file
diff --git a/ARMeilleure/Memory/MemoryManagement.cs b/ARMeilleure/Memory/MemoryManagement.cs
index bf0bd02ce..e299ae49d 100644
--- a/ARMeilleure/Memory/MemoryManagement.cs
+++ b/ARMeilleure/Memory/MemoryManagement.cs
@@ -6,8 +6,6 @@ namespace ARMeilleure.Memory
{
public static class MemoryManagement
{
- public static bool HasWriteWatchSupport => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
-
public static IntPtr Allocate(ulong size)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
@@ -88,27 +86,5 @@ namespace ARMeilleure.Memory
throw new PlatformNotSupportedException();
}
}
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool GetModifiedPages(
- IntPtr address,
- IntPtr size,
- IntPtr[] addresses,
- out ulong count)
- {
- // This is only supported on windows, but returning
- // false (failed) is also valid for platforms without
- // write tracking support on the OS.
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- return MemoryManagementWindows.GetModifiedPages(address, size, addresses, out count);
- }
- else
- {
- count = 0;
-
- return false;
- }
- }
}
}
\ No newline at end of file
diff --git a/ARMeilleure/Memory/MemoryManagementWindows.cs b/ARMeilleure/Memory/MemoryManagementWindows.cs
index c1a84c95b..ae64b5c62 100644
--- a/ARMeilleure/Memory/MemoryManagementWindows.cs
+++ b/ARMeilleure/Memory/MemoryManagementWindows.cs
@@ -36,12 +36,6 @@ namespace ARMeilleure.Memory
WriteCombineModifierflag = 0x400
}
- private enum WriteWatchFlags : uint
- {
- None = 0,
- Reset = 1
- }
-
[DllImport("kernel32.dll")]
private static extern IntPtr VirtualAlloc(
IntPtr lpAddress,
@@ -62,15 +56,6 @@ namespace ARMeilleure.Memory
IntPtr dwSize,
AllocationType dwFreeType);
- [DllImport("kernel32.dll")]
- private static extern int GetWriteWatch(
- WriteWatchFlags dwFlags,
- IntPtr lpBaseAddress,
- IntPtr dwRegionSize,
- IntPtr[] lpAddresses,
- ref ulong lpdwCount,
- out uint lpdwGranularity);
-
public static IntPtr Allocate(IntPtr size)
{
const AllocationType flags =
@@ -130,27 +115,5 @@ namespace ARMeilleure.Memory
{
return VirtualFree(address, IntPtr.Zero, AllocationType.Release);
}
-
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool GetModifiedPages(
- IntPtr address,
- IntPtr size,
- IntPtr[] addresses,
- out ulong count)
- {
- ulong pagesCount = (ulong)addresses.Length;
-
- int result = GetWriteWatch(
- WriteWatchFlags.Reset,
- address,
- size,
- addresses,
- ref pagesCount,
- out uint granularity);
-
- count = pagesCount;
-
- return result == 0;
- }
}
}
\ No newline at end of file
diff --git a/ARMeilleure/Memory/MemoryManager.cs b/ARMeilleure/Memory/MemoryManager.cs
index c62249881..2bdbc3094 100644
--- a/ARMeilleure/Memory/MemoryManager.cs
+++ b/ARMeilleure/Memory/MemoryManager.cs
@@ -1,5 +1,6 @@
using ARMeilleure.State;
using System;
+using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
@@ -29,8 +30,6 @@ namespace ARMeilleure.Memory
internal int PtLevelSize { get; }
internal int PtLevelMask { get; }
- public bool HasWriteWatchSupport => MemoryManagement.HasWriteWatchSupport;
-
public int AddressSpaceBits { get; }
public long AddressSpaceSize { get; }
@@ -254,119 +253,57 @@ namespace ARMeilleure.Memory
return ptePtr;
}
- public bool IsRegionModified(long position, long size)
+ public unsafe (ulong, ulong)[] GetModifiedRanges(ulong address, ulong size)
{
- if (!HasWriteWatchSupport)
+ List<(ulong, ulong)> ranges = new List<(ulong, ulong)>();
+
+ ulong endAddress = (address + size + PageMask) & ~(ulong)PageMask;
+
+ address &= ~(ulong)PageMask;
+
+ ulong currAddr = address;
+ ulong currSize = 0;
+
+ while (address < endAddress)
{
- return IsRegionModifiedFallback(position, size);
- }
-
- IntPtr address = Translate(position);
-
- IntPtr baseAddr = address;
- IntPtr expectedAddr = address;
-
- long pendingPages = 0;
-
- long pages = size / PageSize;
-
- bool modified = false;
-
- bool IsAnyPageModified()
- {
- IntPtr pendingSize = new IntPtr(pendingPages * PageSize);
-
- IntPtr[] addresses = new IntPtr[pendingPages];
-
- bool result = GetModifiedPages(baseAddr, pendingSize, addresses, out ulong count);
-
- if (result)
+ if (IsValidPosition((long)address))
{
- return count != 0;
- }
- else
- {
- return true;
- }
- }
-
- while (pages-- > 0)
- {
- if (address != expectedAddr)
- {
- modified |= IsAnyPageModified();
-
- baseAddr = address;
-
- pendingPages = 0;
- }
-
- expectedAddr = address + PageSize;
-
- pendingPages++;
-
- if (pages == 0)
- {
- break;
- }
-
- position += PageSize;
-
- address = Translate(position);
- }
-
- if (pendingPages != 0)
- {
- modified |= IsAnyPageModified();
- }
-
- return modified;
- }
-
- private unsafe bool IsRegionModifiedFallback(long position, long size)
- {
- long endAddr = (position + size + PageMask) & ~PageMask;
-
- bool modified = false;
-
- while ((ulong)position < (ulong)endAddr)
- {
- if (IsValidPosition(position))
- {
- byte* ptr = ((byte**)_pageTable)[position >> PageBits];
+ byte* ptr = ((byte**)_pageTable)[address >> PageBits];
ulong ptrUlong = (ulong)ptr;
if ((ptrUlong & PteFlagNotModified) == 0)
{
- modified = true;
+ // Modified.
+ currSize += PageSize;
- SetPtEntryFlag(position, PteFlagNotModified);
+ SetPtEntryFlag((long)address, PteFlagNotModified);
+ }
+ else
+ {
+ if (currSize != 0)
+ {
+ ranges.Add((currAddr, currSize));
+ }
+
+ currAddr = address + PageSize;
+ currSize = 0;
}
}
else
{
- modified = true;
+ currSize += PageSize;
}
- position += PageSize;
+ address += PageSize;
}
- return modified;
- }
-
- public bool TryGetHostAddress(long position, long size, out IntPtr ptr)
- {
- if (IsContiguous(position, size))
+ if (currSize != 0)
{
- ptr = (IntPtr)Translate(position);
-
- return true;
+ ranges.Add((currAddr, currSize));
}
- ptr = IntPtr.Zero;
-
- return false;
+ return ranges.ToArray();
}
private bool IsContiguous(long position, long size)
@@ -612,41 +549,6 @@ namespace ARMeilleure.Memory
return data;
}
- public void ReadBytes(long position, byte[] data, int startIndex, int size)
- {
- // Note: This will be moved later.
- long endAddr = position + size;
-
- if ((ulong)size > int.MaxValue)
- {
- throw new ArgumentOutOfRangeException(nameof(size));
- }
-
- if ((ulong)endAddr < (ulong)position)
- {
- throw new ArgumentOutOfRangeException(nameof(position));
- }
-
- int offset = startIndex;
-
- while ((ulong)position < (ulong)endAddr)
- {
- long pageLimit = (position + PageSize) & ~(long)PageMask;
-
- if ((ulong)pageLimit > (ulong)endAddr)
- {
- pageLimit = endAddr;
- }
-
- int copySize = (int)(pageLimit - position);
-
- Marshal.Copy(Translate(position), data, offset, copySize);
-
- position += copySize;
- offset += copySize;
- }
- }
-
public void WriteSByte(long position, sbyte value)
{
WriteByte(position, (byte)value);
@@ -746,53 +648,6 @@ namespace ARMeilleure.Memory
}
}
- public void WriteBytes(long position, byte[] data, int startIndex, int size)
- {
- // Note: This will be moved later.
- long endAddr = position + size;
-
- if ((ulong)endAddr < (ulong)position)
- {
- throw new ArgumentOutOfRangeException(nameof(position));
- }
-
- int offset = startIndex;
-
- while ((ulong)position < (ulong)endAddr)
- {
- long pageLimit = (position + PageSize) & ~(long)PageMask;
-
- if ((ulong)pageLimit > (ulong)endAddr)
- {
- pageLimit = endAddr;
- }
-
- int copySize = (int)(pageLimit - position);
-
- Marshal.Copy(data, offset, Translate(position), copySize);
-
- position += copySize;
- offset += copySize;
- }
- }
-
- public void CopyBytes(long src, long dst, long size)
- {
- // Note: This will be moved later.
- if (IsContiguous(src, size) &&
- IsContiguous(dst, size))
- {
- byte* srcPtr = (byte*)Translate(src);
- byte* dstPtr = (byte*)Translate(dst);
-
- Buffer.MemoryCopy(srcPtr, dstPtr, size, size);
- }
- else
- {
- WriteBytes(dst, ReadBytes(src, size));
- }
- }
-
public void Dispose()
{
Dispose(true);
diff --git a/Ryujinx.Common/PerformanceCounter.cs b/Ryujinx.Common/PerformanceCounter.cs
index 4c8ae6a75..1c2782e34 100644
--- a/Ryujinx.Common/PerformanceCounter.cs
+++ b/Ryujinx.Common/PerformanceCounter.cs
@@ -1,9 +1,11 @@
-using System.Diagnostics;
+using System.Diagnostics;
namespace Ryujinx.Common
{
public static class PerformanceCounter
{
+ private static double _ticksToNs;
+
///
/// Represents the number of ticks in 1 day.
///
@@ -53,6 +55,19 @@ namespace Ryujinx.Common
}
}
+ ///
+ /// Gets the number of nanoseconds elapsed since the system started.
+ ///
+ public static long ElapsedNanoseconds
+ {
+ get
+ {
+ long timestamp = Stopwatch.GetTimestamp();
+
+ return (long)(timestamp * _ticksToNs);
+ }
+ }
+
static PerformanceCounter()
{
TicksPerMillisecond = Stopwatch.Frequency / 1000;
@@ -60,6 +75,8 @@ namespace Ryujinx.Common
TicksPerMinute = TicksPerSecond * 60;
TicksPerHour = TicksPerMinute * 60;
TicksPerDay = TicksPerHour * 24;
+
+ _ticksToNs = 1000000000.0 / (double)Stopwatch.Frequency;
}
}
-}
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Blend/BlendDescriptor.cs b/Ryujinx.Graphics.GAL/Blend/BlendDescriptor.cs
new file mode 100644
index 000000000..d7ef80044
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Blend/BlendDescriptor.cs
@@ -0,0 +1,32 @@
+namespace Ryujinx.Graphics.GAL.Blend
+{
+ public struct BlendDescriptor
+ {
+ public bool Enable { get; }
+
+ public BlendOp ColorOp { get; }
+ public BlendFactor ColorSrcFactor { get; }
+ public BlendFactor ColorDstFactor { get; }
+ public BlendOp AlphaOp { get; }
+ public BlendFactor AlphaSrcFactor { get; }
+ public BlendFactor AlphaDstFactor { get; }
+
+ public BlendDescriptor(
+ bool enable,
+ BlendOp colorOp,
+ BlendFactor colorSrcFactor,
+ BlendFactor colorDstFactor,
+ BlendOp alphaOp,
+ BlendFactor alphaSrcFactor,
+ BlendFactor alphaDstFactor)
+ {
+ Enable = enable;
+ ColorOp = colorOp;
+ ColorSrcFactor = colorSrcFactor;
+ ColorDstFactor = colorDstFactor;
+ AlphaOp = alphaOp;
+ AlphaSrcFactor = alphaSrcFactor;
+ AlphaDstFactor = alphaDstFactor;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/Blend/BlendFactor.cs b/Ryujinx.Graphics.GAL/Blend/BlendFactor.cs
new file mode 100644
index 000000000..0eda08a7f
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Blend/BlendFactor.cs
@@ -0,0 +1,25 @@
+namespace Ryujinx.Graphics.GAL.Blend
+{
+ public enum BlendFactor
+ {
+ Zero = 1,
+ One,
+ SrcColor,
+ OneMinusSrcColor,
+ SrcAlpha,
+ OneMinusSrcAlpha,
+ DstAlpha,
+ OneMinusDstAlpha,
+ DstColor,
+ OneMinusDstColor,
+ SrcAlphaSaturate,
+ Src1Color = 0x10,
+ OneMinusSrc1Color,
+ Src1Alpha,
+ OneMinusSrc1Alpha,
+ ConstantColor = 0xc001,
+ OneMinusConstantColor,
+ ConstantAlpha,
+ OneMinusConstantAlpha
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Blend/BlendOp.cs b/Ryujinx.Graphics.GAL/Blend/BlendOp.cs
new file mode 100644
index 000000000..51a0062d7
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Blend/BlendOp.cs
@@ -0,0 +1,11 @@
+namespace Ryujinx.Graphics.GAL.Blend
+{
+ public enum BlendOp
+ {
+ Add = 1,
+ Subtract,
+ ReverseSubtract,
+ Minimum,
+ Maximum
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/BufferRange.cs b/Ryujinx.Graphics.GAL/BufferRange.cs
new file mode 100644
index 000000000..a35636aa7
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/BufferRange.cs
@@ -0,0 +1,21 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public struct BufferRange
+ {
+ private static BufferRange _empty = new BufferRange(null, 0, 0);
+
+ public BufferRange Empty => _empty;
+
+ public IBuffer Buffer { get; }
+
+ public int Offset { get; }
+ public int Size { get; }
+
+ public BufferRange(IBuffer buffer, int offset, int size)
+ {
+ Buffer = buffer;
+ Offset = offset;
+ Size = size;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Capabilities.cs b/Ryujinx.Graphics.GAL/Capabilities.cs
new file mode 100644
index 000000000..9640447be
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Capabilities.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public struct Capabilities
+ {
+ public bool SupportsAstcCompression { get; }
+
+ public Capabilities(bool supportsAstcCompression)
+ {
+ SupportsAstcCompression = supportsAstcCompression;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Color/ColorF.cs b/Ryujinx.Graphics.GAL/Color/ColorF.cs
new file mode 100644
index 000000000..bc4b32b87
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Color/ColorF.cs
@@ -0,0 +1,18 @@
+namespace Ryujinx.Graphics.GAL.Color
+{
+ public struct ColorF
+ {
+ public float Red { get; }
+ public float Green { get; }
+ public float Blue { get; }
+ public float Alpha { get; }
+
+ public ColorF(float red, float green, float blue, float alpha)
+ {
+ Red = red;
+ Green = green;
+ Blue = blue;
+ Alpha = alpha;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/Color/ColorSI.cs b/Ryujinx.Graphics.GAL/Color/ColorSI.cs
new file mode 100644
index 000000000..9cde0406b
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Color/ColorSI.cs
@@ -0,0 +1,18 @@
+namespace Ryujinx.Graphics.GAL.Color
+{
+ public struct ColorSI
+ {
+ public int Red { get; }
+ public int Green { get; }
+ public int Blue { get; }
+ public int Alpha { get; }
+
+ public ColorSI(int red, int green, int blue, int alpha)
+ {
+ Red = red;
+ Green = green;
+ Blue = blue;
+ Alpha = alpha;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/Color/ColorUI.cs b/Ryujinx.Graphics.GAL/Color/ColorUI.cs
new file mode 100644
index 000000000..3bac84ef9
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Color/ColorUI.cs
@@ -0,0 +1,18 @@
+namespace Ryujinx.Graphics.GAL.Color
+{
+ public struct ColorUI
+ {
+ public uint Red { get; }
+ public uint Green { get; }
+ public uint Blue { get; }
+ public uint Alpha { get; }
+
+ public ColorUI(uint red, uint green, uint blue, uint alpha)
+ {
+ Red = red;
+ Green = green;
+ Blue = blue;
+ Alpha = alpha;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/CompareOp.cs b/Ryujinx.Graphics.GAL/CompareOp.cs
new file mode 100644
index 000000000..da5d5067c
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/CompareOp.cs
@@ -0,0 +1,14 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public enum CompareOp
+ {
+ Never = 1,
+ Less,
+ Equal,
+ LessOrEqual,
+ Greater,
+ NotEqual,
+ GreaterOrEqual,
+ Always
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/CounterType.cs b/Ryujinx.Graphics.GAL/CounterType.cs
new file mode 100644
index 000000000..9d7b3b981
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/CounterType.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public enum CounterType
+ {
+ SamplesPassed,
+ PrimitivesGenerated,
+ TransformFeedbackPrimitivesWritten
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/DepthStencil/DepthStencilState.cs b/Ryujinx.Graphics.GAL/DepthStencil/DepthStencilState.cs
new file mode 100644
index 000000000..93b8d50ed
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/DepthStencil/DepthStencilState.cs
@@ -0,0 +1,47 @@
+namespace Ryujinx.Graphics.GAL.DepthStencil
+{
+ public struct DepthStencilState
+ {
+ public bool DepthTestEnable { get; }
+ public bool DepthWriteEnable { get; }
+ public bool StencilTestEnable { get; }
+
+ public CompareOp DepthFunc { get; }
+ public CompareOp StencilFrontFunc { get; }
+ public StencilOp StencilFrontSFail { get; }
+ public StencilOp StencilFrontDpPass { get; }
+ public StencilOp StencilFrontDpFail { get; }
+ public CompareOp StencilBackFunc { get; }
+ public StencilOp StencilBackSFail { get; }
+ public StencilOp StencilBackDpPass { get; }
+ public StencilOp StencilBackDpFail { get; }
+
+ public DepthStencilState(
+ bool depthTestEnable,
+ bool depthWriteEnable,
+ bool stencilTestEnable,
+ CompareOp depthFunc,
+ CompareOp stencilFrontFunc,
+ StencilOp stencilFrontSFail,
+ StencilOp stencilFrontDpPass,
+ StencilOp stencilFrontDpFail,
+ CompareOp stencilBackFunc,
+ StencilOp stencilBackSFail,
+ StencilOp stencilBackDpPass,
+ StencilOp stencilBackDpFail)
+ {
+ DepthTestEnable = depthTestEnable;
+ DepthWriteEnable = depthWriteEnable;
+ StencilTestEnable = stencilTestEnable;
+ DepthFunc = depthFunc;
+ StencilFrontFunc = stencilFrontFunc;
+ StencilFrontSFail = stencilFrontSFail;
+ StencilFrontDpPass = stencilFrontDpPass;
+ StencilFrontDpFail = stencilFrontDpFail;
+ StencilBackFunc = stencilBackFunc;
+ StencilBackSFail = stencilBackSFail;
+ StencilBackDpPass = stencilBackDpPass;
+ StencilBackDpFail = stencilBackDpFail;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/DepthStencil/DepthTestDescriptor.cs b/Ryujinx.Graphics.GAL/DepthStencil/DepthTestDescriptor.cs
new file mode 100644
index 000000000..98b1429bc
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/DepthStencil/DepthTestDescriptor.cs
@@ -0,0 +1,20 @@
+namespace Ryujinx.Graphics.GAL.DepthStencil
+{
+ public struct DepthTestDescriptor
+ {
+ public bool TestEnable { get; }
+ public bool WriteEnable { get; }
+
+ public CompareOp Func { get; }
+
+ public DepthTestDescriptor(
+ bool testEnable,
+ bool writeEnable,
+ CompareOp func)
+ {
+ TestEnable = testEnable;
+ WriteEnable = writeEnable;
+ Func = func;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/DepthStencil/StencilOp.cs b/Ryujinx.Graphics.GAL/DepthStencil/StencilOp.cs
new file mode 100644
index 000000000..3818c6a52
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/DepthStencil/StencilOp.cs
@@ -0,0 +1,14 @@
+namespace Ryujinx.Graphics.GAL.DepthStencil
+{
+ public enum StencilOp
+ {
+ Keep = 1,
+ Zero,
+ Replace,
+ IncrementAndClamp,
+ DecrementAndClamp,
+ Invert,
+ IncrementAndWrap,
+ DecrementAndWrap
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/DepthStencil/StencilTestDescriptor.cs b/Ryujinx.Graphics.GAL/DepthStencil/StencilTestDescriptor.cs
new file mode 100644
index 000000000..2db53172d
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/DepthStencil/StencilTestDescriptor.cs
@@ -0,0 +1,56 @@
+namespace Ryujinx.Graphics.GAL.DepthStencil
+{
+ public struct StencilTestDescriptor
+ {
+ public bool TestEnable { get; }
+
+ public CompareOp FrontFunc { get; }
+ public StencilOp FrontSFail { get; }
+ public StencilOp FrontDpPass { get; }
+ public StencilOp FrontDpFail { get; }
+ public int FrontFuncRef { get; }
+ public int FrontFuncMask { get; }
+ public int FrontMask { get; }
+ public CompareOp BackFunc { get; }
+ public StencilOp BackSFail { get; }
+ public StencilOp BackDpPass { get; }
+ public StencilOp BackDpFail { get; }
+ public int BackFuncRef { get; }
+ public int BackFuncMask { get; }
+ public int BackMask { get; }
+
+ public StencilTestDescriptor(
+ bool testEnable,
+ CompareOp frontFunc,
+ StencilOp frontSFail,
+ StencilOp frontDpPass,
+ StencilOp frontDpFail,
+ int frontFuncRef,
+ int frontFuncMask,
+ int frontMask,
+ CompareOp backFunc,
+ StencilOp backSFail,
+ StencilOp backDpPass,
+ StencilOp backDpFail,
+ int backFuncRef,
+ int backFuncMask,
+ int backMask)
+ {
+ TestEnable = testEnable;
+ FrontFunc = frontFunc;
+ FrontSFail = frontSFail;
+ FrontDpPass = frontDpPass;
+ FrontDpFail = frontDpFail;
+ FrontFuncRef = frontFuncRef;
+ FrontFuncMask = frontFuncMask;
+ FrontMask = frontMask;
+ BackFunc = backFunc;
+ BackSFail = backSFail;
+ BackDpPass = backDpPass;
+ BackDpFail = backDpFail;
+ BackFuncRef = backFuncRef;
+ BackFuncMask = backFuncMask;
+ BackMask = backMask;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/Extents2D.cs b/Ryujinx.Graphics.GAL/Extents2D.cs
new file mode 100644
index 000000000..e9e26af41
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Extents2D.cs
@@ -0,0 +1,18 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public struct Extents2D
+ {
+ public int X1 { get; }
+ public int Y1 { get; }
+ public int X2 { get; }
+ public int Y2 { get; }
+
+ public Extents2D(int x1, int y1, int x2, int y2)
+ {
+ X1 = x1;
+ Y1 = y1;
+ X2 = x2;
+ Y2 = y2;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalCullFace.cs b/Ryujinx.Graphics.GAL/Face.cs
similarity index 61%
rename from Ryujinx.Graphics/Gal/GalCullFace.cs
rename to Ryujinx.Graphics.GAL/Face.cs
index 4ab3e1742..0587641fa 100644
--- a/Ryujinx.Graphics/Gal/GalCullFace.cs
+++ b/Ryujinx.Graphics.GAL/Face.cs
@@ -1,9 +1,9 @@
-namespace Ryujinx.Graphics.Gal
+namespace Ryujinx.Graphics.GAL
{
- public enum GalCullFace
+ public enum Face
{
Front = 0x404,
Back = 0x405,
FrontAndBack = 0x408
}
-}
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Format.cs b/Ryujinx.Graphics.GAL/Format.cs
new file mode 100644
index 000000000..9f28cdfb8
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Format.cs
@@ -0,0 +1,218 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public enum Format
+ {
+ R8Unorm,
+ R8Snorm,
+ R8Uint,
+ R8Sint,
+ R16Float,
+ R16Unorm,
+ R16Snorm,
+ R16Uint,
+ R16Sint,
+ R32Float,
+ R32Uint,
+ R32Sint,
+ R8G8Unorm,
+ R8G8Snorm,
+ R8G8Uint,
+ R8G8Sint,
+ R16G16Float,
+ R16G16Unorm,
+ R16G16Snorm,
+ R16G16Uint,
+ R16G16Sint,
+ R32G32Float,
+ R32G32Uint,
+ R32G32Sint,
+ R8G8B8Unorm,
+ R8G8B8Snorm,
+ R8G8B8Uint,
+ R8G8B8Sint,
+ R16G16B16Float,
+ R16G16B16Unorm,
+ R16G16B16Snorm,
+ R16G16B16Uint,
+ R16G16B16Sint,
+ R32G32B32Float,
+ R32G32B32Uint,
+ R32G32B32Sint,
+ R8G8B8A8Unorm,
+ R8G8B8A8Snorm,
+ R8G8B8A8Uint,
+ R8G8B8A8Sint,
+ R16G16B16A16Float,
+ R16G16B16A16Unorm,
+ R16G16B16A16Snorm,
+ R16G16B16A16Uint,
+ R16G16B16A16Sint,
+ R32G32B32A32Float,
+ R32G32B32A32Uint,
+ R32G32B32A32Sint,
+ S8Uint,
+ D16Unorm,
+ D24X8Unorm,
+ D32Float,
+ D24UnormS8Uint,
+ D32FloatS8Uint,
+ R8G8B8X8Srgb,
+ R8G8B8A8Srgb,
+ R4G4B4A4Unorm,
+ R5G5B5X1Unorm,
+ R5G5B5A1Unorm,
+ R5G6B5Unorm,
+ R10G10B10A2Unorm,
+ R10G10B10A2Uint,
+ R11G11B10Float,
+ R9G9B9E5Float,
+ Bc1RgbUnorm,
+ Bc1RgbaUnorm,
+ Bc2Unorm,
+ Bc3Unorm,
+ Bc1RgbSrgb,
+ Bc1RgbaSrgb,
+ Bc2Srgb,
+ Bc3Srgb,
+ Bc4Unorm,
+ Bc4Snorm,
+ Bc5Unorm,
+ Bc5Snorm,
+ Bc7Unorm,
+ Bc7Srgb,
+ Bc6HUfloat,
+ Bc6HSfloat,
+ R8Uscaled,
+ R8Sscaled,
+ R16Uscaled,
+ R16Sscaled,
+ R32Uscaled,
+ R32Sscaled,
+ R8G8Uscaled,
+ R8G8Sscaled,
+ R16G16Uscaled,
+ R16G16Sscaled,
+ R32G32Uscaled,
+ R32G32Sscaled,
+ R8G8B8Uscaled,
+ R8G8B8Sscaled,
+ R16G16B16Uscaled,
+ R16G16B16Sscaled,
+ R32G32B32Uscaled,
+ R32G32B32Sscaled,
+ R8G8B8A8Uscaled,
+ R8G8B8A8Sscaled,
+ R16G16B16A16Uscaled,
+ R16G16B16A16Sscaled,
+ R32G32B32A32Uscaled,
+ R32G32B32A32Sscaled,
+ R10G10B10A2Snorm,
+ R10G10B10A2Sint,
+ R10G10B10A2Uscaled,
+ R10G10B10A2Sscaled,
+ R8G8B8X8Unorm,
+ R8G8B8X8Snorm,
+ R8G8B8X8Uint,
+ R8G8B8X8Sint,
+ R16G16B16X16Float,
+ R16G16B16X16Unorm,
+ R16G16B16X16Snorm,
+ R16G16B16X16Uint,
+ R16G16B16X16Sint,
+ R32G32B32X32Float,
+ R32G32B32X32Uint,
+ R32G32B32X32Sint,
+ Astc4x4Unorm,
+ Astc5x4Unorm,
+ Astc5x5Unorm,
+ Astc6x5Unorm,
+ Astc6x6Unorm,
+ Astc8x5Unorm,
+ Astc8x6Unorm,
+ Astc8x8Unorm,
+ Astc10x5Unorm,
+ Astc10x6Unorm,
+ Astc10x8Unorm,
+ Astc10x10Unorm,
+ Astc12x10Unorm,
+ Astc12x12Unorm,
+ Astc4x4Srgb,
+ Astc5x4Srgb,
+ Astc5x5Srgb,
+ Astc6x5Srgb,
+ Astc6x6Srgb,
+ Astc8x5Srgb,
+ Astc8x6Srgb,
+ Astc8x8Srgb,
+ Astc10x5Srgb,
+ Astc10x6Srgb,
+ Astc10x8Srgb,
+ Astc10x10Srgb,
+ Astc12x10Srgb,
+ Astc12x12Srgb,
+ B5G6R5Unorm,
+ B5G5R5X1Unorm,
+ B5G5R5A1Unorm,
+ A1B5G5R5Unorm,
+ B8G8R8X8Unorm,
+ B8G8R8A8Unorm,
+ B8G8R8X8Srgb,
+ B8G8R8A8Srgb
+ }
+
+ public static class FormatExtensions
+ {
+ public static bool IsAstc(this Format format)
+ {
+ return format.IsAstcUnorm() || format.IsAstcSrgb();
+ }
+
+ public static bool IsAstcUnorm(this Format format)
+ {
+ switch (format)
+ {
+ case Format.Astc4x4Unorm:
+ case Format.Astc5x4Unorm:
+ case Format.Astc5x5Unorm:
+ case Format.Astc6x5Unorm:
+ case Format.Astc6x6Unorm:
+ case Format.Astc8x5Unorm:
+ case Format.Astc8x6Unorm:
+ case Format.Astc8x8Unorm:
+ case Format.Astc10x5Unorm:
+ case Format.Astc10x6Unorm:
+ case Format.Astc10x8Unorm:
+ case Format.Astc10x10Unorm:
+ case Format.Astc12x10Unorm:
+ case Format.Astc12x12Unorm:
+ return true;
+ }
+
+ return false;
+ }
+
+ public static bool IsAstcSrgb(this Format format)
+ {
+ switch (format)
+ {
+ case Format.Astc4x4Srgb:
+ case Format.Astc5x4Srgb:
+ case Format.Astc5x5Srgb:
+ case Format.Astc6x5Srgb:
+ case Format.Astc6x6Srgb:
+ case Format.Astc8x5Srgb:
+ case Format.Astc8x6Srgb:
+ case Format.Astc8x8Srgb:
+ case Format.Astc10x5Srgb:
+ case Format.Astc10x6Srgb:
+ case Format.Astc10x8Srgb:
+ case Format.Astc10x10Srgb:
+ case Format.Astc12x10Srgb:
+ case Format.Astc12x12Srgb:
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/FrontFace.cs b/Ryujinx.Graphics.GAL/FrontFace.cs
new file mode 100644
index 000000000..aa6bfdc5b
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/FrontFace.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public enum FrontFace
+ {
+ Clockwise = 0x900,
+ CounterClockwise = 0x901
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/IBuffer.cs b/Ryujinx.Graphics.GAL/IBuffer.cs
new file mode 100644
index 000000000..000efd67a
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IBuffer.cs
@@ -0,0 +1,15 @@
+using System;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface IBuffer : IDisposable
+ {
+ void CopyTo(IBuffer destination, int srcOffset, int dstOffset, int size);
+
+ byte[] GetData(int offset, int size);
+
+ void SetData(Span data);
+
+ void SetData(int offset, Span data);
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/IComputePipeline.cs b/Ryujinx.Graphics.GAL/IComputePipeline.cs
new file mode 100644
index 000000000..e2d0b06ea
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IComputePipeline.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public interface IComputePipeline
+ {
+ void Dispatch(int groupsX, int groupsY, int groupsZ);
+
+ void SetProgram(IProgram program);
+
+ void SetStorageBuffer(int index, BufferRange buffer);
+ void SetUniformBuffer(int index, BufferRange buffer);
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/IGraphicsPipeline.cs b/Ryujinx.Graphics.GAL/IGraphicsPipeline.cs
new file mode 100644
index 000000000..13e6ab1a6
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IGraphicsPipeline.cs
@@ -0,0 +1,69 @@
+using Ryujinx.Graphics.GAL.Blend;
+using Ryujinx.Graphics.GAL.Color;
+using Ryujinx.Graphics.GAL.DepthStencil;
+using Ryujinx.Graphics.GAL.InputAssembler;
+using Ryujinx.Graphics.Shader;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface IGraphicsPipeline
+ {
+ void BindBlendState(int index, BlendDescriptor blend);
+
+ void BindIndexBuffer(BufferRange buffer, IndexType type);
+
+ void BindProgram(IProgram program);
+
+ void BindSampler(int index, ShaderStage stage, ISampler sampler);
+ void BindTexture(int index, ShaderStage stage, ITexture texture);
+
+ void BindStorageBuffers(int index, ShaderStage stage, BufferRange[] buffers);
+ void BindUniformBuffers(int index, ShaderStage stage, BufferRange[] buffers);
+
+ void BindVertexAttribs(VertexAttribDescriptor[] vertexAttribs);
+ void BindVertexBuffers(VertexBufferDescriptor[] vertexBuffers);
+
+ void ClearRenderTargetColor(int index, uint componentMask, ColorF color);
+ void ClearRenderTargetColor(int index, uint componentMask, ColorSI color);
+ void ClearRenderTargetColor(int index, uint componentMask, ColorUI color);
+
+ void ClearRenderTargetDepthStencil(
+ float depthValue,
+ bool depthMask,
+ int stencilValue,
+ int stencilMask);
+
+ void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance);
+ void DrawIndexed(
+ int indexCount,
+ int instanceCount,
+ int firstIndex,
+ int firstVertex,
+ int firstInstance);
+ void DrawIndirect (BufferRange buffer, ulong offset, int drawCount, int stride);
+ void DrawIndexedIndirect(BufferRange buffer, ulong offset, int drawCount, int stride);
+
+ void SetBlendColor(ColorF color);
+
+ void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp);
+
+ void SetDepthTest(DepthTestDescriptor depthTest);
+
+ void SetFaceCulling(bool enable, Face face);
+
+ void SetFrontFace(FrontFace frontFace);
+
+ void SetPrimitiveRestart(bool enable, int index);
+
+ void SetPrimitiveTopology(PrimitiveTopology topology);
+
+ void SetRenderTargetColorMasks(uint[] componentMask);
+
+ void SetRenderTargets(ITexture color3D, ITexture depthStencil);
+ void SetRenderTargets(ITexture[] colors, ITexture depthStencil);
+
+ void SetStencilTest(StencilTestDescriptor stencilTest);
+
+ void SetViewports(int first, Viewport[] viewports);
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/IProgram.cs b/Ryujinx.Graphics.GAL/IProgram.cs
new file mode 100644
index 000000000..ef44fc47e
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IProgram.cs
@@ -0,0 +1,6 @@
+using System;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface IProgram : IDisposable { }
+}
diff --git a/Ryujinx.Graphics.GAL/IRenderer.cs b/Ryujinx.Graphics.GAL/IRenderer.cs
new file mode 100644
index 000000000..609f05f58
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IRenderer.cs
@@ -0,0 +1,33 @@
+using Ryujinx.Graphics.GAL.Sampler;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.Shader;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface IRenderer
+ {
+ IComputePipeline ComputePipeline { get; }
+ IGraphicsPipeline GraphicsPipeline { get; }
+
+ IWindow Window { get; }
+
+ IShader CompileShader(ShaderProgram shader);
+
+ IBuffer CreateBuffer(int size);
+
+ IProgram CreateProgram(IShader[] shaders);
+
+ ISampler CreateSampler(SamplerCreateInfo info);
+ ITexture CreateTexture(TextureCreateInfo info);
+
+ void FlushPipelines();
+
+ Capabilities GetCapabilities();
+
+ ulong GetCounter(CounterType type);
+
+ void InitializeCounters();
+
+ void ResetCounter(CounterType type);
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/ISampler.cs b/Ryujinx.Graphics.GAL/ISampler.cs
new file mode 100644
index 000000000..3aefc6a78
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/ISampler.cs
@@ -0,0 +1,6 @@
+using System;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface ISampler : IDisposable { }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/IShader.cs b/Ryujinx.Graphics.GAL/IShader.cs
new file mode 100644
index 000000000..be24adcda
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IShader.cs
@@ -0,0 +1,6 @@
+using System;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface IShader : IDisposable { }
+}
diff --git a/Ryujinx.Graphics.GAL/ITexture.cs b/Ryujinx.Graphics.GAL/ITexture.cs
new file mode 100644
index 000000000..6b3f5c59e
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/ITexture.cs
@@ -0,0 +1,21 @@
+using Ryujinx.Graphics.GAL.Texture;
+using System;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface ITexture : IDisposable
+ {
+ int Handle { get; }
+
+ void CopyTo(ITexture destination);
+ void CopyTo(ITexture destination, Extents2D srcRegion, Extents2D dstRegion, bool linearFilter);
+
+ ITexture CreateView(TextureCreateInfo info, int firstLayer, int firstLevel);
+
+ int GetStorageDebugId();
+
+ byte[] GetData(int face);
+
+ void SetData(Span data);
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/IWindow.cs b/Ryujinx.Graphics.GAL/IWindow.cs
new file mode 100644
index 000000000..a0e5f196c
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IWindow.cs
@@ -0,0 +1,13 @@
+using System;
+
+namespace Ryujinx.Graphics.GAL
+{
+ public interface IWindow
+ {
+ void Present();
+
+ void QueueTexture(ITexture texture, ImageCrop crop, object context);
+
+ void RegisterTextureReleaseCallback(TextureReleaseCallback callback);
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/ImageCrop.cs b/Ryujinx.Graphics.GAL/ImageCrop.cs
new file mode 100644
index 000000000..4428eee97
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/ImageCrop.cs
@@ -0,0 +1,28 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public struct ImageCrop
+ {
+ public int Left { get; }
+ public int Right { get; }
+ public int Top { get; }
+ public int Bottom { get; }
+ public bool FlipX { get; }
+ public bool FlipY { get; }
+
+ public ImageCrop(
+ int left,
+ int right,
+ int top,
+ int bottom,
+ bool flipX,
+ bool flipY)
+ {
+ Left = left;
+ Right = right;
+ Top = top;
+ Bottom = bottom;
+ FlipX = flipX;
+ FlipY = flipY;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/IndexType.cs b/Ryujinx.Graphics.GAL/IndexType.cs
new file mode 100644
index 000000000..4abf28d9c
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/IndexType.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public enum IndexType
+ {
+ UByte,
+ UShort,
+ UInt
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/InputAssembler/VertexAttribDescriptor.cs b/Ryujinx.Graphics.GAL/InputAssembler/VertexAttribDescriptor.cs
new file mode 100644
index 000000000..cba3a9a41
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/InputAssembler/VertexAttribDescriptor.cs
@@ -0,0 +1,17 @@
+namespace Ryujinx.Graphics.GAL.InputAssembler
+{
+ public struct VertexAttribDescriptor
+ {
+ public int BufferIndex { get; }
+ public int Offset { get; }
+
+ public Format Format { get; }
+
+ public VertexAttribDescriptor(int bufferIndex, int offset, Format format)
+ {
+ BufferIndex = bufferIndex;
+ Offset = offset;
+ Format = format;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/InputAssembler/VertexBufferDescriptor.cs b/Ryujinx.Graphics.GAL/InputAssembler/VertexBufferDescriptor.cs
new file mode 100644
index 000000000..eb428f8ec
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/InputAssembler/VertexBufferDescriptor.cs
@@ -0,0 +1,17 @@
+namespace Ryujinx.Graphics.GAL.InputAssembler
+{
+ public struct VertexBufferDescriptor
+ {
+ public BufferRange Buffer { get; }
+
+ public int Stride { get; }
+ public int Divisor { get; }
+
+ public VertexBufferDescriptor(BufferRange buffer, int stride, int divisor)
+ {
+ Buffer = buffer;
+ Stride = stride;
+ Divisor = divisor;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/PolygonModeMask.cs b/Ryujinx.Graphics.GAL/PolygonModeMask.cs
new file mode 100644
index 000000000..514b42317
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/PolygonModeMask.cs
@@ -0,0 +1,12 @@
+using System;
+
+namespace Ryujinx.Graphics.GAL
+{
+ [Flags]
+ public enum PolygonModeMask
+ {
+ Point = 1 << 0,
+ Line = 1 << 1,
+ Fill = 1 << 2
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/PrimitiveTopology.cs b/Ryujinx.Graphics.GAL/PrimitiveTopology.cs
new file mode 100644
index 000000000..ed567a68a
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/PrimitiveTopology.cs
@@ -0,0 +1,21 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public enum PrimitiveTopology
+ {
+ Points,
+ Lines,
+ LineLoop,
+ LineStrip,
+ Triangles,
+ TriangleStrip,
+ TriangleFan,
+ Quads,
+ QuadStrip,
+ Polygon,
+ LinesAdjacency,
+ LineStripAdjacency,
+ TrianglesAdjacency,
+ TriangleStripAdjacency,
+ Patches
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/RectangleF.cs b/Ryujinx.Graphics.GAL/RectangleF.cs
new file mode 100644
index 000000000..c58aabf0e
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/RectangleF.cs
@@ -0,0 +1,18 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public struct RectangleF
+ {
+ public float X { get; }
+ public float Y { get; }
+ public float Width { get; }
+ public float Height { get; }
+
+ public RectangleF(float x, float y, float width, float height)
+ {
+ X = x;
+ Y = y;
+ Width = width;
+ Height = height;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/Ryujinx.Graphics.GAL.csproj b/Ryujinx.Graphics.GAL/Ryujinx.Graphics.GAL.csproj
new file mode 100644
index 000000000..584ebe975
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Ryujinx.Graphics.GAL.csproj
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+ netcoreapp3.0
+
+
+
diff --git a/Ryujinx.Graphics.GAL/Sampler/AddressMode.cs b/Ryujinx.Graphics.GAL/Sampler/AddressMode.cs
new file mode 100644
index 000000000..4f56d892f
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Sampler/AddressMode.cs
@@ -0,0 +1,14 @@
+namespace Ryujinx.Graphics.GAL.Sampler
+{
+ public enum AddressMode
+ {
+ Repeat,
+ MirroredRepeat,
+ ClampToEdge,
+ ClampToBorder,
+ Clamp,
+ MirrorClampToEdge,
+ MirrorClampToBorder,
+ MirrorClamp
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Sampler/CompareMode.cs b/Ryujinx.Graphics.GAL/Sampler/CompareMode.cs
new file mode 100644
index 000000000..ca4b09a06
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Sampler/CompareMode.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.GAL.Sampler
+{
+ public enum CompareMode
+ {
+ None,
+ CompareRToTexture
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Sampler/MagFilter.cs b/Ryujinx.Graphics.GAL/Sampler/MagFilter.cs
new file mode 100644
index 000000000..3c9c9de6d
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Sampler/MagFilter.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.GAL.Sampler
+{
+ public enum MagFilter
+ {
+ Nearest = 1,
+ Linear
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Sampler/MinFilter.cs b/Ryujinx.Graphics.GAL/Sampler/MinFilter.cs
new file mode 100644
index 000000000..d012f695b
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Sampler/MinFilter.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.GAL.Sampler
+{
+ public enum MinFilter
+ {
+ Nearest = 1,
+ Linear,
+ NearestMipmapNearest,
+ LinearMipmapNearest,
+ NearestMipmapLinear,
+ LinearMipmapLinear
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Sampler/SamplerCreateInfo.cs b/Ryujinx.Graphics.GAL/Sampler/SamplerCreateInfo.cs
new file mode 100644
index 000000000..3f42742b9
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Sampler/SamplerCreateInfo.cs
@@ -0,0 +1,52 @@
+using Ryujinx.Graphics.GAL.Color;
+
+namespace Ryujinx.Graphics.GAL.Sampler
+{
+ public struct SamplerCreateInfo
+ {
+ public MinFilter MinFilter { get; }
+ public MagFilter MagFilter { get; }
+
+ public AddressMode AddressU { get; }
+ public AddressMode AddressV { get; }
+ public AddressMode AddressP { get; }
+
+ public CompareMode CompareMode { get; }
+ public CompareOp CompareOp { get; }
+
+ public ColorF BorderColor { get; }
+
+ public float MinLod { get; }
+ public float MaxLod { get; }
+ public float MipLodBias { get; }
+ public float MaxAnisotropy { get; }
+
+ public SamplerCreateInfo(
+ MinFilter minFilter,
+ MagFilter magFilter,
+ AddressMode addressU,
+ AddressMode addressV,
+ AddressMode addressP,
+ CompareMode compareMode,
+ CompareOp compareOp,
+ ColorF borderColor,
+ float minLod,
+ float maxLod,
+ float mipLodBias,
+ float maxAnisotropy)
+ {
+ MinFilter = minFilter;
+ MagFilter = magFilter;
+ AddressU = addressU;
+ AddressV = addressV;
+ AddressP = addressP;
+ CompareMode = compareMode;
+ CompareOp = compareOp;
+ BorderColor = borderColor;
+ MinLod = minLod;
+ MaxLod = maxLod;
+ MipLodBias = mipLodBias;
+ MaxAnisotropy = maxAnisotropy;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Texture/DepthStencilMode.cs b/Ryujinx.Graphics.GAL/Texture/DepthStencilMode.cs
new file mode 100644
index 000000000..d7a379d81
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Texture/DepthStencilMode.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.GAL.Texture
+{
+ public enum DepthStencilMode
+ {
+ Depth,
+ Stencil
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Texture/SwizzleComponent.cs b/Ryujinx.Graphics.GAL/Texture/SwizzleComponent.cs
new file mode 100644
index 000000000..fd7d50e3b
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Texture/SwizzleComponent.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.GAL.Texture
+{
+ public enum SwizzleComponent
+ {
+ Zero,
+ One,
+ Red,
+ Green,
+ Blue,
+ Alpha
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Texture/Target.cs b/Ryujinx.Graphics.GAL/Texture/Target.cs
new file mode 100644
index 000000000..b9cc11054
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Texture/Target.cs
@@ -0,0 +1,17 @@
+namespace Ryujinx.Graphics.GAL.Texture
+{
+ public enum Target
+ {
+ Texture1D,
+ Texture2D,
+ Texture3D,
+ Texture1DArray,
+ Texture2DArray,
+ Texture2DMultisample,
+ Texture2DMultisampleArray,
+ Rectangle,
+ Cubemap,
+ CubemapArray,
+ TextureBuffer
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.GAL/Texture/TextureCreateInfo.cs b/Ryujinx.Graphics.GAL/Texture/TextureCreateInfo.cs
new file mode 100644
index 000000000..ad365f6b1
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Texture/TextureCreateInfo.cs
@@ -0,0 +1,115 @@
+using Ryujinx.Common;
+using System;
+
+namespace Ryujinx.Graphics.GAL.Texture
+{
+ public struct TextureCreateInfo
+ {
+ public int Width { get; }
+ public int Height { get; }
+ public int Depth { get; }
+ public int Levels { get; }
+ public int Samples { get; }
+ public int BlockWidth { get; }
+ public int BlockHeight { get; }
+ public int BytesPerPixel { get; }
+
+ public bool IsCompressed => (BlockWidth | BlockHeight) != 1;
+
+ public Format Format { get; }
+
+ public DepthStencilMode DepthStencilMode { get; }
+
+ public Target Target { get; }
+
+ public SwizzleComponent SwizzleR { get; }
+ public SwizzleComponent SwizzleG { get; }
+ public SwizzleComponent SwizzleB { get; }
+ public SwizzleComponent SwizzleA { get; }
+
+ public TextureCreateInfo(
+ int width,
+ int height,
+ int depth,
+ int levels,
+ int samples,
+ int blockWidth,
+ int blockHeight,
+ int bytesPerPixel,
+ Format format,
+ DepthStencilMode depthStencilMode,
+ Target target,
+ SwizzleComponent swizzleR,
+ SwizzleComponent swizzleG,
+ SwizzleComponent swizzleB,
+ SwizzleComponent swizzleA)
+ {
+ Width = width;
+ Height = height;
+ Depth = depth;
+ Levels = levels;
+ Samples = samples;
+ BlockWidth = blockWidth;
+ BlockHeight = blockHeight;
+ BytesPerPixel = bytesPerPixel;
+ Format = format;
+ DepthStencilMode = depthStencilMode;
+ Target = target;
+ SwizzleR = swizzleR;
+ SwizzleG = swizzleG;
+ SwizzleB = swizzleB;
+ SwizzleA = swizzleA;
+ }
+
+ public int GetMipSize(int level)
+ {
+ return GetMipStride(level) * GetLevelHeight(level) * GetLevelDepth(level);
+ }
+
+ public int GetMipStride(int level)
+ {
+ return BitUtils.AlignUp(GetLevelWidth(level) * BytesPerPixel, 4);
+ }
+
+ private int GetLevelWidth(int level)
+ {
+ return BitUtils.DivRoundUp(GetLevelSize(Width, level), BlockWidth);
+ }
+
+ private int GetLevelHeight(int level)
+ {
+ return BitUtils.DivRoundUp(GetLevelSize(Height, level), BlockHeight);
+ }
+
+ private int GetLevelDepth(int level)
+ {
+ return Target == Target.Texture3D ? GetLevelSize(Depth, level) : GetLayers();
+ }
+
+ public int GetDepthOrLayers()
+ {
+ return Target == Target.Texture3D ? Depth : GetLayers();
+ }
+
+ public int GetLayers()
+ {
+ if (Target == Target.Texture2DArray ||
+ Target == Target.Texture2DMultisampleArray ||
+ Target == Target.CubemapArray)
+ {
+ return Depth;
+ }
+ else if (Target == Target.Cubemap)
+ {
+ return 6;
+ }
+
+ return 1;
+ }
+
+ private static int GetLevelSize(int size, int level)
+ {
+ return Math.Max(1, size >> level);
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/TextureReleaseCallback.cs b/Ryujinx.Graphics.GAL/TextureReleaseCallback.cs
new file mode 100644
index 000000000..c058df2bb
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/TextureReleaseCallback.cs
@@ -0,0 +1,4 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public delegate void TextureReleaseCallback(object context);
+}
diff --git a/Ryujinx.Graphics.GAL/Viewport.cs b/Ryujinx.Graphics.GAL/Viewport.cs
new file mode 100644
index 000000000..d9d6e20a4
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/Viewport.cs
@@ -0,0 +1,33 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public struct Viewport
+ {
+ public RectangleF Region { get; }
+
+ public ViewportSwizzle SwizzleX { get; }
+ public ViewportSwizzle SwizzleY { get; }
+ public ViewportSwizzle SwizzleZ { get; }
+ public ViewportSwizzle SwizzleW { get; }
+
+ public float DepthNear { get; }
+ public float DepthFar { get; }
+
+ public Viewport(
+ RectangleF region,
+ ViewportSwizzle swizzleX,
+ ViewportSwizzle swizzleY,
+ ViewportSwizzle swizzleZ,
+ ViewportSwizzle swizzleW,
+ float depthNear,
+ float depthFar)
+ {
+ Region = region;
+ SwizzleX = swizzleX;
+ SwizzleY = swizzleY;
+ SwizzleZ = swizzleZ;
+ SwizzleW = swizzleW;
+ DepthNear = depthNear;
+ DepthFar = depthFar;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.GAL/ViewportSwizzle.cs b/Ryujinx.Graphics.GAL/ViewportSwizzle.cs
new file mode 100644
index 000000000..5f04bf87d
--- /dev/null
+++ b/Ryujinx.Graphics.GAL/ViewportSwizzle.cs
@@ -0,0 +1,14 @@
+namespace Ryujinx.Graphics.GAL
+{
+ public enum ViewportSwizzle
+ {
+ PositiveX,
+ NegativeX,
+ PositiveY,
+ NegativeY,
+ PositiveZ,
+ NegativeZ,
+ PositiveW,
+ NegativeW
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/ClassId.cs b/Ryujinx.Graphics.Gpu/ClassId.cs
new file mode 100644
index 000000000..3cde0ac06
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/ClassId.cs
@@ -0,0 +1,11 @@
+namespace Ryujinx.Graphics.Gpu
+{
+ enum ClassId
+ {
+ Engine2D = 0x902d,
+ Engine3D = 0xb197,
+ EngineCompute = 0xb1c0,
+ EngineInline2Memory = 0xa140,
+ EngineDma = 0xb0b5
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Constants.cs b/Ryujinx.Graphics.Gpu/Constants.cs
new file mode 100644
index 000000000..501933fbe
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Constants.cs
@@ -0,0 +1,14 @@
+namespace Ryujinx.Graphics.Gpu
+{
+ static class Constants
+ {
+ public const int TotalCpUniformBuffers = 8;
+ public const int TotalCpStorageBuffers = 16;
+ public const int TotalGpUniformBuffers = 18;
+ public const int TotalGpStorageBuffers = 16;
+ public const int TotalRenderTargets = 8;
+ public const int TotalShaderStages = 5;
+ public const int TotalVertexBuffers = 16;
+ public const int TotalViewports = 8;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Debugging.cs b/Ryujinx.Graphics.Gpu/Debugging.cs
new file mode 100644
index 000000000..cb99cee18
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Debugging.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Ryujinx.Graphics.Gpu
+{
+ static class Debugging
+ {
+ public static void PrintTexInfo(string prefix, Image.Texture tex)
+ {
+ if (tex == null)
+ {
+ Console.WriteLine(prefix + " null");
+
+ return;
+ }
+
+ string range = $"{tex.Address:X}..{(tex.Address + tex.Size):X}";
+
+ int debugId = tex.HostTexture.GetStorageDebugId();
+
+ string str = $"{prefix} p {debugId:X8} {tex.Info.Target} {tex.Info.FormatInfo.Format} {tex.Info.Width}x{tex.Info.Height}x{tex.Info.DepthOrLayers} mips {tex.Info.Levels} addr {range}";
+
+ Console.WriteLine(str);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/DmaPusher.cs b/Ryujinx.Graphics.Gpu/DmaPusher.cs
similarity index 81%
rename from Ryujinx.Graphics/DmaPusher.cs
rename to Ryujinx.Graphics.Gpu/DmaPusher.cs
index 74a32a4a2..ae9cc868c 100644
--- a/Ryujinx.Graphics/DmaPusher.cs
+++ b/Ryujinx.Graphics.Gpu/DmaPusher.cs
@@ -1,15 +1,14 @@
-using Ryujinx.Graphics.Memory;
using System.Collections.Concurrent;
using System.Threading;
-namespace Ryujinx.Graphics
+namespace Ryujinx.Graphics.Gpu
{
public class DmaPusher
{
- private ConcurrentQueue<(NvGpuVmm, long)> _ibBuffer;
+ private ConcurrentQueue _ibBuffer;
- private long _dmaPut;
- private long _dmaGet;
+ private ulong _dmaPut;
+ private ulong _dmaGet;
private struct DmaState
{
@@ -29,28 +28,26 @@ namespace Ryujinx.Graphics
private bool _ibEnable;
private bool _nonMain;
- private long _dmaMGet;
+ private ulong _dmaMGet;
- private NvGpuVmm _vmm;
-
- private NvGpu _gpu;
+ private GpuContext _context;
private AutoResetEvent _event;
- public DmaPusher(NvGpu gpu)
+ internal DmaPusher(GpuContext context)
{
- _gpu = gpu;
+ _context = context;
- _ibBuffer = new ConcurrentQueue<(NvGpuVmm, long)>();
+ _ibBuffer = new ConcurrentQueue();
_ibEnable = true;
_event = new AutoResetEvent(false);
}
- public void Push(NvGpuVmm vmm, long entry)
+ public void Push(ulong entry)
{
- _ibBuffer.Enqueue((vmm, entry));
+ _ibBuffer.Enqueue(entry);
_event.Set();
}
@@ -69,7 +66,7 @@ namespace Ryujinx.Graphics
{
if (_dmaGet != _dmaPut)
{
- int word = _vmm.ReadInt32(_dmaGet);
+ int word = _context.MemoryAccessor.ReadInt32(_dmaGet);
_dmaGet += 4;
@@ -148,20 +145,14 @@ namespace Ryujinx.Graphics
}
}
}
- else if (_ibEnable && _ibBuffer.TryDequeue(out (NvGpuVmm Vmm, long Entry) tuple))
+ else if (_ibEnable && _ibBuffer.TryDequeue(out ulong entry))
{
- _vmm = tuple.Vmm;
-
- long entry = tuple.Entry;
-
- int length = (int)(entry >> 42) & 0x1fffff;
+ ulong length = (entry >> 42) & 0x1fffff;
_dmaGet = entry & 0xfffffffffc;
_dmaPut = _dmaGet + length * 4;
- _nonMain = (entry & (1L << 41)) != 0;
-
- _gpu.ResourceManager.ClearPbCache();
+ _nonMain = (entry & (1UL << 41)) != 0;
}
else
{
@@ -180,7 +171,7 @@ namespace Ryujinx.Graphics
private void CallMethod(int argument)
{
- _gpu.Fifo.CallMethod(_vmm, new GpuMethodCall(
+ _context.Fifo.CallMethod(new MethodParams(
_state.Method,
argument,
_state.SubChannel,
diff --git a/Ryujinx.Graphics.Gpu/Engine/Compute.cs b/Ryujinx.Graphics.Gpu/Engine/Compute.cs
new file mode 100644
index 000000000..c8627435f
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/Compute.cs
@@ -0,0 +1,83 @@
+using Ryujinx.Graphics.Gpu.State;
+using Ryujinx.Graphics.Shader;
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ public void Dispatch(int argument)
+ {
+ uint dispatchParamsAddress = (uint)_context.State.Get(MethodOffset.DispatchParamsAddress);
+
+ var dispatchParams = _context.MemoryAccessor.Read((ulong)dispatchParamsAddress << 8);
+
+ GpuVa shaderBaseAddress = _context.State.Get(MethodOffset.ShaderBaseAddress);
+
+ ulong shaderGpuVa = shaderBaseAddress.Pack() + (uint)dispatchParams.ShaderOffset;
+
+ ComputeShader cs = _shaderCache.GetComputeShader(
+ shaderGpuVa,
+ dispatchParams.UnpackBlockSizeX(),
+ dispatchParams.UnpackBlockSizeY(),
+ dispatchParams.UnpackBlockSizeZ());
+
+ _context.Renderer.ComputePipeline.SetProgram(cs.Interface);
+
+ ShaderProgramInfo info = cs.Shader.Info;
+
+ uint sbEnableMask = 0;
+ uint ubEnableMask = dispatchParams.UnpackUniformBuffersEnableMask();
+
+ for (int index = 0; index < dispatchParams.UniformBuffers.Length; index++)
+ {
+ if ((ubEnableMask & (1 << index)) == 0)
+ {
+ continue;
+ }
+
+ ulong gpuVa = dispatchParams.UniformBuffers[index].PackAddress();
+ ulong size = dispatchParams.UniformBuffers[index].UnpackSize();
+
+ _bufferManager.SetComputeUniformBuffer(index, gpuVa, size);
+ }
+
+ for (int index = 0; index < info.SBuffers.Count; index++)
+ {
+ BufferDescriptor sb = info.SBuffers[index];
+
+ sbEnableMask |= 1u << sb.Slot;
+
+ ulong sbDescAddress = _bufferManager.GetComputeUniformBufferAddress(0);
+
+ int sbDescOffset = 0x310 + sb.Slot * 0x10;
+
+ sbDescAddress += (ulong)sbDescOffset;
+
+ Span sbDescriptorData = _context.PhysicalMemory.Read(sbDescAddress, 0x10);
+
+ SbDescriptor sbDescriptor = MemoryMarshal.Cast(sbDescriptorData)[0];
+
+ _bufferManager.SetComputeStorageBuffer(sb.Slot, sbDescriptor.PackAddress(), (uint)sbDescriptor.Size);
+ }
+
+ ubEnableMask = 0;
+
+ for (int index = 0; index < info.CBuffers.Count; index++)
+ {
+ ubEnableMask |= 1u << info.CBuffers[index].Slot;
+ }
+
+ _bufferManager.SetComputeStorageBufferEnableMask(sbEnableMask);
+ _bufferManager.SetComputeUniformBufferEnableMask(ubEnableMask);
+
+ _bufferManager.CommitComputeBindings();
+
+ _context.Renderer.ComputePipeline.Dispatch(
+ dispatchParams.UnpackGridSizeX(),
+ dispatchParams.UnpackGridSizeY(),
+ dispatchParams.UnpackGridSizeZ());
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/ComputeParams.cs b/Ryujinx.Graphics.Gpu/Engine/ComputeParams.cs
new file mode 100644
index 000000000..03582f050
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/ComputeParams.cs
@@ -0,0 +1,126 @@
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ struct UniformBufferParams
+ {
+ public int AddressLow;
+ public int AddressHighAndSize;
+
+ public ulong PackAddress()
+ {
+ return (uint)AddressLow | ((ulong)(AddressHighAndSize & 0xff) << 32);
+ }
+
+ public ulong UnpackSize()
+ {
+ return (ulong)((AddressHighAndSize >> 15) & 0x1ffff);
+ }
+ }
+
+ struct ComputeParams
+ {
+ public int Unknown0;
+ public int Unknown1;
+ public int Unknown2;
+ public int Unknown3;
+ public int Unknown4;
+ public int Unknown5;
+ public int Unknown6;
+ public int Unknown7;
+ public int ShaderOffset;
+ public int Unknown9;
+ public int Unknown10;
+ public int Unknown11;
+ public int GridSizeX;
+ public int GridSizeYZ;
+ public int Unknown14;
+ public int Unknown15;
+ public int Unknown16;
+ public int Unknown17;
+ public int BlockSizeX;
+ public int BlockSizeYZ;
+ public int UniformBuffersConfig;
+ public int Unknown21;
+ public int Unknown22;
+ public int Unknown23;
+ public int Unknown24;
+ public int Unknown25;
+ public int Unknown26;
+ public int Unknown27;
+ public int Unknown28;
+
+ private UniformBufferParams _uniformBuffer0;
+ private UniformBufferParams _uniformBuffer1;
+ private UniformBufferParams _uniformBuffer2;
+ private UniformBufferParams _uniformBuffer3;
+ private UniformBufferParams _uniformBuffer4;
+ private UniformBufferParams _uniformBuffer5;
+ private UniformBufferParams _uniformBuffer6;
+ private UniformBufferParams _uniformBuffer7;
+
+ public Span UniformBuffers
+ {
+ get
+ {
+ return MemoryMarshal.CreateSpan(ref _uniformBuffer0, 8);
+ }
+ }
+
+ public int Unknown45;
+ public int Unknown46;
+ public int Unknown47;
+ public int Unknown48;
+ public int Unknown49;
+ public int Unknown50;
+ public int Unknown51;
+ public int Unknown52;
+ public int Unknown53;
+ public int Unknown54;
+ public int Unknown55;
+ public int Unknown56;
+ public int Unknown57;
+ public int Unknown58;
+ public int Unknown59;
+ public int Unknown60;
+ public int Unknown61;
+ public int Unknown62;
+ public int Unknown63;
+
+ public int UnpackGridSizeX()
+ {
+ return GridSizeX & 0x7fffffff;
+ }
+
+ public int UnpackGridSizeY()
+ {
+ return GridSizeYZ & 0xffff;
+ }
+
+ public int UnpackGridSizeZ()
+ {
+ return (GridSizeYZ >> 16) & 0xffff;
+ }
+
+ public int UnpackBlockSizeX()
+ {
+ return (BlockSizeX >> 16) & 0xffff;
+ }
+
+ public int UnpackBlockSizeY()
+ {
+ return BlockSizeYZ & 0xffff;
+ }
+
+ public int UnpackBlockSizeZ()
+ {
+ return (BlockSizeYZ >> 16) & 0xffff;
+ }
+
+ public uint UnpackUniformBuffersEnableMask()
+ {
+ return (uint)UniformBuffersConfig & 0xff;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/ComputeShader.cs b/Ryujinx.Graphics.Gpu/Engine/ComputeShader.cs
new file mode 100644
index 000000000..cc7d4d996
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/ComputeShader.cs
@@ -0,0 +1,18 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Shader;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ class ComputeShader
+ {
+ public IProgram Interface { get; set; }
+
+ public ShaderProgram Shader { get; }
+
+ public ComputeShader(IProgram program, ShaderProgram shader)
+ {
+ Interface = program;
+ Shader = shader;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/GraphicsShader.cs b/Ryujinx.Graphics.Gpu/Engine/GraphicsShader.cs
new file mode 100644
index 000000000..a8ccc05ac
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/GraphicsShader.cs
@@ -0,0 +1,17 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Shader;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ class GraphicsShader
+ {
+ public IProgram Interface { get; set; }
+
+ public ShaderProgram[] Shader { get; }
+
+ public GraphicsShader()
+ {
+ Shader = new ShaderProgram[5];
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/Inline2Memory.cs b/Ryujinx.Graphics.Gpu/Engine/Inline2Memory.cs
new file mode 100644
index 000000000..d2816ac59
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/Inline2Memory.cs
@@ -0,0 +1,42 @@
+using Ryujinx.Graphics.Gpu.State;
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private Inline2MemoryParams _params;
+
+ private bool _isLinear;
+
+ private int _offset;
+ private int _size;
+
+ public void Execute(int argument)
+ {
+ _params = _context.State.Get(MethodOffset.Inline2MemoryParams);
+
+ _isLinear = (argument & 1) != 0;
+
+ _offset = 0;
+ _size = _params.LineLengthIn * _params.LineCount;
+ }
+
+ public void PushData(int argument)
+ {
+ if (_isLinear)
+ {
+ for (int shift = 0; shift < 32 && _offset < _size; shift += 8, _offset++)
+ {
+ ulong gpuVa = _params.DstAddress.Pack() + (ulong)_offset;
+
+ _context.MemoryAccessor.Write(gpuVa, new byte[] { (byte)(argument >> shift) });
+ }
+ }
+ else
+ {
+ throw new NotImplementedException();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodClear.cs b/Ryujinx.Graphics.Gpu/Engine/MethodClear.cs
new file mode 100644
index 000000000..b4680fa57
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodClear.cs
@@ -0,0 +1,55 @@
+using Ryujinx.Graphics.GAL.Color;
+using Ryujinx.Graphics.Gpu.State;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private void Clear(int argument)
+ {
+ UpdateState();
+
+ bool clearDepth = (argument & 1) != 0;
+ bool clearStencil = (argument & 2) != 0;
+
+ uint componentMask = (uint)((argument >> 2) & 0xf);
+
+ int index = (argument >> 6) & 0xf;
+
+ if (componentMask != 0)
+ {
+ ClearColors clearColor = _context.State.GetClearColors();
+
+ ColorF color = new ColorF(
+ clearColor.Red,
+ clearColor.Green,
+ clearColor.Blue,
+ clearColor.Alpha);
+
+ _context.Renderer.GraphicsPipeline.ClearRenderTargetColor(
+ index,
+ componentMask,
+ color);
+ }
+
+ if (clearDepth || clearStencil)
+ {
+ float depthValue = _context.State.GetClearDepthValue();
+ int stencilValue = _context.State.GetClearStencilValue();
+
+ int stencilMask = 0;
+
+ if (clearStencil)
+ {
+ stencilMask = _context.State.GetStencilTestState().FrontMask;
+ }
+
+ _context.Renderer.GraphicsPipeline.ClearRenderTargetDepthStencil(
+ depthValue,
+ clearDepth,
+ stencilValue,
+ stencilMask);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodCopyBuffer.cs b/Ryujinx.Graphics.Gpu/Engine/MethodCopyBuffer.cs
new file mode 100644
index 000000000..19ffb0e3c
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodCopyBuffer.cs
@@ -0,0 +1,79 @@
+using Ryujinx.Graphics.Gpu.State;
+using Ryujinx.Graphics.Texture;
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private void CopyBuffer(int argument)
+ {
+ var cbp = _context.State.Get(MethodOffset.CopyBufferParams);
+
+ var swizzle = _context.State.Get(MethodOffset.CopyBufferSwizzle);
+
+ bool srcLinear = (argument & (1 << 7)) != 0;
+ bool dstLinear = (argument & (1 << 8)) != 0;
+ bool copy2D = (argument & (1 << 9)) != 0;
+
+ int size = cbp.XCount;
+
+ if (size == 0)
+ {
+ return;
+ }
+
+ if (copy2D)
+ {
+ // Buffer to texture copy.
+ int srcBpp = swizzle.UnpackSrcComponentsCount() * swizzle.UnpackComponentSize();
+ int dstBpp = swizzle.UnpackDstComponentsCount() * swizzle.UnpackComponentSize();
+
+ var dst = _context.State.Get(MethodOffset.CopyBufferDstTexture);
+ var src = _context.State.Get(MethodOffset.CopyBufferSrcTexture);
+
+ var srcCalculator = new OffsetCalculator(
+ src.Width,
+ src.Height,
+ cbp.SrcStride,
+ srcLinear,
+ src.MemoryLayout.UnpackGobBlocksInY(),
+ srcBpp);
+
+ var dstCalculator = new OffsetCalculator(
+ dst.Width,
+ dst.Height,
+ cbp.DstStride,
+ dstLinear,
+ dst.MemoryLayout.UnpackGobBlocksInY(),
+ dstBpp);
+
+ ulong srcBaseAddress = _context.MemoryManager.Translate(cbp.SrcAddress.Pack());
+ ulong dstBaseAddress = _context.MemoryManager.Translate(cbp.DstAddress.Pack());
+
+ for (int y = 0; y < cbp.YCount; y++)
+ for (int x = 0; x < cbp.XCount; x++)
+ {
+ int srcOffset = srcCalculator.GetOffset(src.RegionX + x, src.RegionY + y);
+ int dstOffset = dstCalculator.GetOffset(dst.RegionX + x, dst.RegionY + y);
+
+ ulong srcAddress = srcBaseAddress + (ulong)srcOffset;
+ ulong dstAddress = dstBaseAddress + (ulong)dstOffset;
+
+ Span pixel = _context.PhysicalMemory.Read(srcAddress, (ulong)srcBpp);
+
+ _context.PhysicalMemory.Write(dstAddress, pixel);
+ }
+ }
+ else
+ {
+ // Buffer to buffer copy.
+ _bufferManager.CopyBuffer(cbp.SrcAddress, cbp.DstAddress, (uint)size);
+
+ Span data = _context.MemoryAccessor.Read(cbp.SrcAddress.Pack(), (uint)size);
+
+ _context.MemoryAccessor.Write(cbp.DstAddress.Pack(), data);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodCopyTexture.cs b/Ryujinx.Graphics.Gpu/Engine/MethodCopyTexture.cs
new file mode 100644
index 000000000..e2c40805b
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodCopyTexture.cs
@@ -0,0 +1,70 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Gpu.State;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private void CopyTexture(int argument)
+ {
+ CopyTexture dstCopyTexture = _context.State.GetCopyDstTexture();
+ CopyTexture srcCopyTexture = _context.State.GetCopySrcTexture();
+
+ Image.Texture srcTexture = _textureManager.FindOrCreateTexture(srcCopyTexture);
+
+ if (srcTexture == null)
+ {
+ return;
+ }
+
+ // When the source texture that was found has a depth format,
+ // we must enforce the target texture also has a depth format,
+ // as copies between depth and color formats are not allowed.
+ if (srcTexture.Format == Format.D32Float)
+ {
+ dstCopyTexture.Format = RtFormat.D32Float;
+ }
+
+ Image.Texture dstTexture = _textureManager.FindOrCreateTexture(dstCopyTexture);
+
+ if (dstTexture == null)
+ {
+ return;
+ }
+
+ CopyTextureControl control = _context.State.GetCopyTextureControl();
+
+ CopyRegion region = _context.State.GetCopyRegion();
+
+ int srcX1 = (int)(region.SrcXF >> 32);
+ int srcY1 = (int)(region.SrcYF >> 32);
+
+ int srcX2 = (int)((region.SrcXF + region.SrcWidthRF * region.DstWidth) >> 32);
+ int srcY2 = (int)((region.SrcYF + region.SrcHeightRF * region.DstHeight) >> 32);
+
+ int dstX1 = region.DstX;
+ int dstY1 = region.DstY;
+
+ int dstX2 = region.DstX + region.DstWidth;
+ int dstY2 = region.DstY + region.DstHeight;
+
+ Extents2D srcRegion = new Extents2D(
+ srcX1 / srcTexture.Info.SamplesInX,
+ srcY1 / srcTexture.Info.SamplesInY,
+ srcX2 / srcTexture.Info.SamplesInX,
+ srcY2 / srcTexture.Info.SamplesInY);
+
+ Extents2D dstRegion = new Extents2D(
+ dstX1 / dstTexture.Info.SamplesInX,
+ dstY1 / dstTexture.Info.SamplesInY,
+ dstX2 / dstTexture.Info.SamplesInX,
+ dstY2 / dstTexture.Info.SamplesInY);
+
+ bool linearFilter = control.UnpackLinearFilter();
+
+ srcTexture.HostTexture.CopyTo(dstTexture.HostTexture, srcRegion, dstRegion, linearFilter);
+
+ dstTexture.Modified = true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodDraw.cs b/Ryujinx.Graphics.Gpu/Engine/MethodDraw.cs
new file mode 100644
index 000000000..dd360113b
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodDraw.cs
@@ -0,0 +1,133 @@
+using Ryujinx.Graphics.Gpu.State;
+using Ryujinx.Graphics.Gpu.Image;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private bool _drawIndexed;
+
+ private int _firstIndex;
+ private int _indexCount;
+
+ private bool _instancedHasState;
+ private bool _instancedIndexed;
+
+ private int _instancedFirstIndex;
+ private int _instancedFirstVertex;
+ private int _instancedFirstInstance;
+ private int _instancedIndexCount;
+ private int _instancedDrawStateFirst;
+ private int _instancedDrawStateCount;
+
+ private int _instanceIndex;
+
+ public PrimitiveType PrimitiveType { get; private set; }
+
+ private void DrawEnd(int argument)
+ {
+ UpdateState();
+
+ bool instanced = _vsUsesInstanceId || _isAnyVbInstanced;
+
+ if (instanced)
+ {
+ if (!_instancedHasState)
+ {
+ _instancedHasState = true;
+
+ _instancedIndexed = _drawIndexed;
+
+ _instancedFirstIndex = _firstIndex;
+ _instancedFirstVertex = _context.State.GetBaseVertex();
+ _instancedFirstInstance = _context.State.GetBaseInstance();
+
+ _instancedIndexCount = _indexCount;
+
+ VertexBufferDrawState drawState = _context.State.GetVertexBufferDrawState();
+
+ _instancedDrawStateFirst = drawState.First;
+ _instancedDrawStateCount = drawState.Count;
+ }
+
+ return;
+ }
+
+ int firstInstance = _context.State.GetBaseInstance();
+
+ if (_drawIndexed)
+ {
+ _drawIndexed = false;
+
+ int firstVertex = _context.State.GetBaseVertex();
+
+ _context.Renderer.GraphicsPipeline.DrawIndexed(
+ _indexCount,
+ 1,
+ _firstIndex,
+ firstVertex,
+ firstInstance);
+ }
+ else
+ {
+ VertexBufferDrawState drawState = _context.State.GetVertexBufferDrawState();
+
+ _context.Renderer.GraphicsPipeline.Draw(
+ drawState.Count,
+ 1,
+ drawState.First,
+ firstInstance);
+ }
+ }
+
+ private void DrawBegin(int argument)
+ {
+ PrimitiveType type = (PrimitiveType)(argument & 0xffff);
+
+ _context.Renderer.GraphicsPipeline.SetPrimitiveTopology(type.Convert());
+
+ PrimitiveType = type;
+
+ if ((argument & (1 << 26)) != 0)
+ {
+ _instanceIndex++;
+ }
+ else if ((argument & (1 << 27)) == 0)
+ {
+ _instanceIndex = 0;
+ }
+ }
+
+ private void SetIndexCount(int argument)
+ {
+ _drawIndexed = true;
+ }
+
+ public void PerformDeferredDraws()
+ {
+ // Perform any pending instanced draw.
+ if (_instancedHasState)
+ {
+ _instancedHasState = false;
+
+ if (_instancedIndexed)
+ {
+ _context.Renderer.GraphicsPipeline.DrawIndexed(
+ _instancedIndexCount,
+ _instanceIndex + 1,
+ _instancedFirstIndex,
+ _instancedFirstVertex,
+ _instancedFirstInstance);
+ }
+ else
+ {
+ _context.Renderer.GraphicsPipeline.Draw(
+ _instancedDrawStateCount,
+ _instanceIndex + 1,
+ _instancedDrawStateFirst,
+ _instancedFirstInstance);
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodReport.cs b/Ryujinx.Graphics.Gpu/Engine/MethodReport.cs
new file mode 100644
index 000000000..fd0a31a16
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodReport.cs
@@ -0,0 +1,100 @@
+using Ryujinx.Common;
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Gpu.State;
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private ulong _runningCounter;
+
+ private void Report(int argument)
+ {
+ ReportMode mode = (ReportMode)(argument & 3);
+
+ ReportCounterType type = (ReportCounterType)((argument >> 23) & 0x1f);
+
+ switch (mode)
+ {
+ case ReportMode.Semaphore: ReportSemaphore(); break;
+ case ReportMode.Counter: ReportCounter(type); break;
+ }
+ }
+
+ private void ReportSemaphore()
+ {
+ ReportState state = _context.State.GetReportState();
+
+ _context.MemoryAccessor.Write(state.Address.Pack(), state.Payload);
+
+ _context.AdvanceSequence();
+ }
+
+ private struct CounterData
+ {
+ public ulong Counter;
+ public ulong Timestamp;
+ }
+
+ private void ReportCounter(ReportCounterType type)
+ {
+ CounterData counterData = new CounterData();
+
+ ulong counter = 0;
+
+ switch (type)
+ {
+ case ReportCounterType.Zero:
+ counter = 0;
+ break;
+ case ReportCounterType.SamplesPassed:
+ counter = _context.Renderer.GetCounter(CounterType.SamplesPassed);
+ break;
+ case ReportCounterType.PrimitivesGenerated:
+ counter = _context.Renderer.GetCounter(CounterType.PrimitivesGenerated);
+ break;
+ case ReportCounterType.TransformFeedbackPrimitivesWritten:
+ counter = _context.Renderer.GetCounter(CounterType.TransformFeedbackPrimitivesWritten);
+ break;
+ }
+
+ ulong ticks;
+
+ if (GraphicsConfig.FastGpuTime)
+ {
+ ticks = _runningCounter++;
+ }
+ else
+ {
+ ticks = ConvertNanosecondsToTicks((ulong)PerformanceCounter.ElapsedNanoseconds);
+ }
+
+ counterData.Counter = counter;
+ counterData.Timestamp = ticks;
+
+ Span counterDataSpan = MemoryMarshal.CreateSpan(ref counterData, 1);
+
+ Span data = MemoryMarshal.Cast(counterDataSpan);
+
+ ReportState state = _context.State.GetReportState();
+
+ _context.MemoryAccessor.Write(state.Address.Pack(), data);
+ }
+
+ private static ulong ConvertNanosecondsToTicks(ulong nanoseconds)
+ {
+ // We need to divide first to avoid overflows.
+ // We fix up the result later by calculating the difference and adding
+ // that to the result.
+ ulong divided = nanoseconds / 625;
+
+ ulong rounded = divided * 625;
+
+ ulong errorBias = ((nanoseconds - rounded) * 384) / 625;
+
+ return divided * 384 + errorBias;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodResetCounter.cs b/Ryujinx.Graphics.Gpu/Engine/MethodResetCounter.cs
new file mode 100644
index 000000000..12a878459
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodResetCounter.cs
@@ -0,0 +1,26 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Gpu.State;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private void ResetCounter(int argument)
+ {
+ ResetCounterType type = (ResetCounterType)argument;
+
+ switch (type)
+ {
+ case ResetCounterType.SamplesPassed:
+ _context.Renderer.ResetCounter(CounterType.SamplesPassed);
+ break;
+ case ResetCounterType.PrimitivesGenerated:
+ _context.Renderer.ResetCounter(CounterType.PrimitivesGenerated);
+ break;
+ case ResetCounterType.TransformFeedbackPrimitivesWritten:
+ _context.Renderer.ResetCounter(CounterType.TransformFeedbackPrimitivesWritten);
+ break;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodUniformBufferBind.cs b/Ryujinx.Graphics.Gpu/Engine/MethodUniformBufferBind.cs
new file mode 100644
index 000000000..a9ebce83c
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodUniformBufferBind.cs
@@ -0,0 +1,52 @@
+using Ryujinx.Graphics.Gpu.State;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private void UniformBufferBind0(int argument)
+ {
+ UniformBufferBind(argument, ShaderType.Vertex);
+ }
+
+ private void UniformBufferBind1(int argument)
+ {
+ UniformBufferBind(argument, ShaderType.TessellationControl);
+ }
+
+ private void UniformBufferBind2(int argument)
+ {
+ UniformBufferBind(argument, ShaderType.TessellationEvaluation);
+ }
+
+ private void UniformBufferBind3(int argument)
+ {
+ UniformBufferBind(argument, ShaderType.Geometry);
+ }
+
+ private void UniformBufferBind4(int argument)
+ {
+ UniformBufferBind(argument, ShaderType.Fragment);
+ }
+
+ private void UniformBufferBind(int argument, ShaderType type)
+ {
+ bool enable = (argument & 1) != 0;
+
+ int index = (argument >> 4) & 0x1f;
+
+ if (enable)
+ {
+ UniformBufferState uniformBuffer = _context.State.GetUniformBufferState();
+
+ ulong address = uniformBuffer.Address.Pack();
+
+ _bufferManager.SetGraphicsUniformBuffer((int)type, index, address, (uint)uniformBuffer.Size);
+ }
+ else
+ {
+ _bufferManager.SetGraphicsUniformBuffer((int)type, index, 0, 0);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/MethodUniformBufferUpdate.cs b/Ryujinx.Graphics.Gpu/Engine/MethodUniformBufferUpdate.cs
new file mode 100644
index 000000000..f0b8e2d77
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/MethodUniformBufferUpdate.cs
@@ -0,0 +1,18 @@
+using Ryujinx.Graphics.Gpu.State;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private void UniformBufferUpdate(int argument)
+ {
+ UniformBufferState uniformBuffer = _context.State.GetUniformBufferState();
+
+ _context.MemoryAccessor.Write(uniformBuffer.Address.Pack() + (uint)uniformBuffer.Offset, argument);
+
+ _context.State.SetUniformBufferOffset(uniformBuffer.Offset + 4);
+
+ _context.AdvanceSequence();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/Methods.cs b/Ryujinx.Graphics.Gpu/Engine/Methods.cs
new file mode 100644
index 000000000..db72a861a
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/Methods.cs
@@ -0,0 +1,784 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Blend;
+using Ryujinx.Graphics.GAL.DepthStencil;
+using Ryujinx.Graphics.GAL.InputAssembler;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.Gpu.Image;
+using Ryujinx.Graphics.Gpu.Memory;
+using Ryujinx.Graphics.Gpu.State;
+using Ryujinx.Graphics.Shader;
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ partial class Methods
+ {
+ private GpuContext _context;
+
+ private ShaderCache _shaderCache;
+
+ private BufferManager _bufferManager;
+ private TextureManager _textureManager;
+
+ public TextureManager TextureManager => _textureManager;
+
+ private bool _isAnyVbInstanced;
+ private bool _vsUsesInstanceId;
+
+ public Methods(GpuContext context)
+ {
+ _context = context;
+
+ _shaderCache = new ShaderCache(_context);
+
+ _bufferManager = new BufferManager(context);
+ _textureManager = new TextureManager(context, _bufferManager);
+
+ RegisterCallbacks();
+ }
+
+ private void RegisterCallbacks()
+ {
+ _context.State.RegisterCopyBufferCallback(CopyBuffer);
+ _context.State.RegisterCopyTextureCallback(CopyTexture);
+
+ _context.State.RegisterDrawEndCallback(DrawEnd);
+
+ _context.State.RegisterDrawBeginCallback(DrawBegin);
+
+ _context.State.RegisterSetIndexCountCallback(SetIndexCount);
+
+ _context.State.RegisterClearCallback(Clear);
+
+ _context.State.RegisterReportCallback(Report);
+
+ _context.State.RegisterUniformBufferUpdateCallback(UniformBufferUpdate);
+
+ _context.State.RegisterUniformBufferBind0Callback(UniformBufferBind0);
+ _context.State.RegisterUniformBufferBind1Callback(UniformBufferBind1);
+ _context.State.RegisterUniformBufferBind2Callback(UniformBufferBind2);
+ _context.State.RegisterUniformBufferBind3Callback(UniformBufferBind3);
+ _context.State.RegisterUniformBufferBind4Callback(UniformBufferBind4);
+
+ _context.State.RegisterCallback(MethodOffset.InvalidateTextures, InvalidateTextures);
+
+ _context.State.RegisterCallback(MethodOffset.ResetCounter, ResetCounter);
+
+ _context.State.RegisterCallback(MethodOffset.Inline2MemoryExecute, Execute);
+ _context.State.RegisterCallback(MethodOffset.Inline2MemoryPushData, PushData);
+
+ _context.State.RegisterCallback(MethodOffset.Dispatch, Dispatch);
+ }
+
+ public Image.Texture GetTexture(ulong address) => _textureManager.Find2(address);
+
+ private void UpdateState()
+ {
+ if ((_context.State.StateWriteFlags & StateWriteFlags.Any) == 0)
+ {
+ CommitBindings();
+
+ return;
+ }
+
+ // Shaders must be the first one to be updated if modified, because
+ // some of the other state depends on information from the currently
+ // bound shaders.
+ if ((_context.State.StateWriteFlags & StateWriteFlags.ShaderState) != 0)
+ {
+ UpdateShaderState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.RenderTargetGroup) != 0)
+ {
+ UpdateRenderTargetGroupState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.DepthTestState) != 0)
+ {
+ UpdateDepthTestState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.ViewportTransform) != 0)
+ {
+ UpdateViewportTransform();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.DepthBiasState) != 0)
+ {
+ UpdateDepthBiasState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.StencilTestState) != 0)
+ {
+ UpdateStencilTestState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.SamplerPoolState) != 0)
+ {
+ UpdateSamplerPoolState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.TexturePoolState) != 0)
+ {
+ UpdateTexturePoolState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.InputAssemblerGroup) != 0)
+ {
+ UpdateInputAssemblerGroupState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.FaceState) != 0)
+ {
+ UpdateFaceState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.RtColorMask) != 0)
+ {
+ UpdateRtColorMask();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.BlendState) != 0)
+ {
+ UpdateBlendState();
+ }
+
+ _context.State.StateWriteFlags &= ~StateWriteFlags.Any;
+
+ CommitBindings();
+ }
+
+ private void CommitBindings()
+ {
+ _bufferManager.CommitBindings();
+ _textureManager.CommitBindings();
+ }
+
+ public void InvalidateRange(ulong address, ulong size)
+ {
+ _bufferManager.InvalidateRange(address, size);
+ _textureManager.InvalidateRange(address, size);
+ }
+
+ public void InvalidateTextureRange(ulong address, ulong size)
+ {
+ _textureManager.InvalidateRange(address, size);
+ }
+
+ private void UpdateRenderTargetGroupState()
+ {
+ TextureMsaaMode msaaMode = _context.State.GetRtMsaaMode();
+
+ int samplesInX = msaaMode.SamplesInX();
+ int samplesInY = msaaMode.SamplesInY();
+
+ Image.Texture color3D = Get3DRenderTarget(samplesInX, samplesInY);
+
+ if (color3D == null)
+ {
+ for (int index = 0; index < Constants.TotalRenderTargets; index++)
+ {
+ RtColorState colorState = _context.State.GetRtColorState(index);
+
+ if (!IsRtEnabled(colorState))
+ {
+ _textureManager.SetRenderTargetColor(index, null);
+
+ continue;
+ }
+
+ Image.Texture color = _textureManager.FindOrCreateTexture(
+ colorState,
+ samplesInX,
+ samplesInY);
+
+ _textureManager.SetRenderTargetColor(index, color);
+
+ color.Modified = true;
+ }
+ }
+ else
+ {
+ _textureManager.SetRenderTargetColor3D(color3D);
+
+ color3D.Modified = true;
+ }
+
+ bool dsEnable = _context.State.Get(MethodOffset.RtDepthStencilEnable);
+
+ Image.Texture depthStencil = null;
+
+ if (dsEnable)
+ {
+ var dsState = _context.State.GetRtDepthStencilState();
+ var dsSize = _context.State.GetRtDepthStencilSize();
+
+ depthStencil = _textureManager.FindOrCreateTexture(
+ dsState,
+ dsSize,
+ samplesInX,
+ samplesInY);
+ }
+
+ _textureManager.SetRenderTargetDepthStencil(depthStencil);
+ }
+
+ private Image.Texture Get3DRenderTarget(int samplesInX, int samplesInY)
+ {
+ RtColorState colorState0 = _context.State.GetRtColorState(0);
+
+ if (!IsRtEnabled(colorState0) || !colorState0.MemoryLayout.UnpackIsTarget3D() || colorState0.Depth != 1)
+ {
+ return null;
+ }
+
+ int slices = 1;
+ int unused = 0;
+
+ for (int index = 1; index < Constants.TotalRenderTargets; index++)
+ {
+ RtColorState colorState = _context.State.GetRtColorState(index);
+
+ if (!IsRtEnabled(colorState))
+ {
+ unused++;
+
+ continue;
+ }
+
+ if (colorState.MemoryLayout.UnpackIsTarget3D() && colorState.Depth == 1)
+ {
+ slices++;
+ }
+ }
+
+ if (slices + unused == Constants.TotalRenderTargets)
+ {
+ colorState0.Depth = slices;
+
+ return _textureManager.FindOrCreateTexture(colorState0, samplesInX, samplesInY);
+ }
+
+ return null;
+ }
+
+ private static bool IsRtEnabled(RtColorState colorState)
+ {
+ // Colors are disabled by writing 0 to the format.
+ return colorState.Format != 0 && colorState.WidthOrStride != 0;
+ }
+
+ private void UpdateDepthTestState()
+ {
+ _context.Renderer.GraphicsPipeline.SetDepthTest(new DepthTestDescriptor(
+ _context.State.GetDepthTestEnable().IsTrue(),
+ _context.State.GetDepthWriteEnable().IsTrue(),
+ _context.State.GetDepthTestFunc()));
+ }
+
+ private void UpdateViewportTransform()
+ {
+ Viewport[] viewports = new Viewport[Constants.TotalViewports];
+
+ for (int index = 0; index < Constants.TotalViewports; index++)
+ {
+ var transform = _context.State.Get(MethodOffset.ViewportTransform + index * 8);
+ var extents = _context.State.Get (MethodOffset.ViewportExtents + index * 4);
+
+ float x = transform.TranslateX - MathF.Abs(transform.ScaleX);
+ float y = transform.TranslateY - MathF.Abs(transform.ScaleY);
+
+ float width = transform.ScaleX * 2;
+ float height = transform.ScaleY * 2;
+
+ RectangleF region = new RectangleF(x, y, width, height);
+
+ viewports[index] = new Viewport(
+ region,
+ transform.UnpackSwizzleX(),
+ transform.UnpackSwizzleY(),
+ transform.UnpackSwizzleZ(),
+ transform.UnpackSwizzleW(),
+ extents.DepthNear,
+ extents.DepthFar);
+ }
+
+ _context.Renderer.GraphicsPipeline.SetViewports(0, viewports);
+ }
+
+ private void UpdateDepthBiasState()
+ {
+ var polygonOffset = _context.State.Get(MethodOffset.DepthBiasState);
+
+ float factor = _context.State.Get(MethodOffset.DepthBiasFactor);
+ float units = _context.State.Get(MethodOffset.DepthBiasUnits);
+ float clamp = _context.State.Get(MethodOffset.DepthBiasClamp);
+
+ PolygonModeMask enables = 0;
+
+ enables = (polygonOffset.PointEnable.IsTrue() ? PolygonModeMask.Point : 0);
+ enables |= (polygonOffset.LineEnable.IsTrue() ? PolygonModeMask.Line : 0);
+ enables |= (polygonOffset.FillEnable.IsTrue() ? PolygonModeMask.Fill : 0);
+
+ _context.Renderer.GraphicsPipeline.SetDepthBias(enables, factor, units, clamp);
+ }
+
+ private void UpdateStencilTestState()
+ {
+ StencilBackMasks backMasks = _context.State.GetStencilBackMasks();
+ StencilTestState test = _context.State.GetStencilTestState();
+ StencilBackTestState backTest = _context.State.GetStencilBackTestState();
+
+ CompareOp backFunc;
+ StencilOp backSFail;
+ StencilOp backDpPass;
+ StencilOp backDpFail;
+ int backFuncRef;
+ int backFuncMask;
+ int backMask;
+
+ if (backTest.TwoSided.IsTrue())
+ {
+ backFunc = backTest.BackFunc;
+ backSFail = backTest.BackSFail;
+ backDpPass = backTest.BackDpPass;
+ backDpFail = backTest.BackDpFail;
+ backFuncRef = backMasks.FuncRef;
+ backFuncMask = backMasks.FuncMask;
+ backMask = backMasks.Mask;
+ }
+ else
+ {
+ backFunc = test.FrontFunc;
+ backSFail = test.FrontSFail;
+ backDpPass = test.FrontDpPass;
+ backDpFail = test.FrontDpFail;
+ backFuncRef = test.FrontFuncRef;
+ backFuncMask = test.FrontFuncMask;
+ backMask = test.FrontMask;
+ }
+
+ _context.Renderer.GraphicsPipeline.SetStencilTest(new StencilTestDescriptor(
+ test.Enable.IsTrue(),
+ test.FrontFunc,
+ test.FrontSFail,
+ test.FrontDpPass,
+ test.FrontDpFail,
+ test.FrontFuncRef,
+ test.FrontFuncMask,
+ test.FrontMask,
+ backFunc,
+ backSFail,
+ backDpPass,
+ backDpFail,
+ backFuncRef,
+ backFuncMask,
+ backMask));
+ }
+
+ private void UpdateSamplerPoolState()
+ {
+ PoolState samplerPool = _context.State.GetSamplerPoolState();
+
+ _textureManager.SetSamplerPool(samplerPool.Address.Pack(), samplerPool.MaximumId);
+ }
+
+ private void UpdateTexturePoolState()
+ {
+ PoolState texturePool = _context.State.GetTexturePoolState();
+
+ _textureManager.SetTexturePool(texturePool.Address.Pack(), texturePool.MaximumId);
+
+ _textureManager.SetTextureBufferIndex(_context.State.GetTextureBufferIndex());
+ }
+
+ private void UpdateInputAssemblerGroupState()
+ {
+ // Must be updated before the vertex buffer.
+ if ((_context.State.StateWriteFlags & StateWriteFlags.VertexAttribState) != 0)
+ {
+ UpdateVertexAttribState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.PrimitiveRestartState) != 0)
+ {
+ UpdatePrimitiveRestartState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.IndexBufferState) != 0)
+ {
+ UpdateIndexBufferState();
+ }
+
+ if ((_context.State.StateWriteFlags & StateWriteFlags.VertexBufferState) != 0)
+ {
+ UpdateVertexBufferState();
+ }
+ }
+
+ private void UpdateVertexAttribState()
+ {
+ VertexAttribDescriptor[] vertexAttribs = new VertexAttribDescriptor[16];
+
+ for (int index = 0; index < 16; index++)
+ {
+ VertexAttribState vertexAttrib = _context.State.GetVertexAttribState(index);
+
+ if (!FormatTable.TryGetAttribFormat(vertexAttrib.UnpackFormat(), out Format format))
+ {
+ // TODO: warning.
+
+ format = Format.R32G32B32A32Float;
+ }
+
+ vertexAttribs[index] = new VertexAttribDescriptor(
+ vertexAttrib.UnpackBufferIndex(),
+ vertexAttrib.UnpackOffset(),
+ format);
+ }
+
+ _context.Renderer.GraphicsPipeline.BindVertexAttribs(vertexAttribs);
+ }
+
+ private void UpdatePrimitiveRestartState()
+ {
+ PrimitiveRestartState primitiveRestart = _context.State.Get(MethodOffset.PrimitiveRestartState);
+
+ _context.Renderer.GraphicsPipeline.SetPrimitiveRestart(
+ primitiveRestart.Enable,
+ primitiveRestart.Index);
+ }
+
+ private void UpdateIndexBufferState()
+ {
+ IndexBufferState indexBuffer = _context.State.GetIndexBufferState();
+
+ _firstIndex = indexBuffer.First;
+ _indexCount = indexBuffer.Count;
+
+ if (_indexCount == 0)
+ {
+ return;
+ }
+
+ ulong gpuVa = indexBuffer.Address.Pack();
+
+ // Do not use the end address to calculate the size, because
+ // the result may be much larger than the real size of the index buffer.
+ ulong size = (ulong)(_firstIndex + _indexCount);
+
+ switch (indexBuffer.Type)
+ {
+ case IndexType.UShort: size *= 2; break;
+ case IndexType.UInt: size *= 4; break;
+ }
+
+ _bufferManager.SetIndexBuffer(gpuVa, size, indexBuffer.Type);
+
+ // The index buffer affects the vertex buffer size calculation, we
+ // need to ensure that they are updated.
+ UpdateVertexBufferState();
+ }
+
+ private uint GetIndexBufferMaxIndex(ulong gpuVa, ulong size, IndexType type)
+ {
+ ulong address = _context.MemoryManager.Translate(gpuVa);
+
+ Span data = _context.PhysicalMemory.Read(address, size);
+
+ uint maxIndex = 0;
+
+ switch (type)
+ {
+ case IndexType.UByte:
+ {
+ for (int index = 0; index < data.Length; index++)
+ {
+ if (maxIndex < data[index])
+ {
+ maxIndex = data[index];
+ }
+ }
+
+ break;
+ }
+
+ case IndexType.UShort:
+ {
+ Span indices = MemoryMarshal.Cast(data);
+
+ for (int index = 0; index < indices.Length; index++)
+ {
+ if (maxIndex < indices[index])
+ {
+ maxIndex = indices[index];
+ }
+ }
+
+ break;
+ }
+
+ case IndexType.UInt:
+ {
+ Span indices = MemoryMarshal.Cast(data);
+
+ for (int index = 0; index < indices.Length; index++)
+ {
+ if (maxIndex < indices[index])
+ {
+ maxIndex = indices[index];
+ }
+ }
+
+ break;
+ }
+ }
+
+ return maxIndex;
+ }
+
+ private void UpdateVertexBufferState()
+ {
+ _isAnyVbInstanced = false;
+
+ for (int index = 0; index < 16; index++)
+ {
+ VertexBufferState vertexBuffer = _context.State.GetVertexBufferState(index);
+
+ if (!vertexBuffer.UnpackEnable())
+ {
+ _bufferManager.SetVertexBuffer(index, 0, 0, 0, 0);
+
+ continue;
+ }
+
+ GpuVa endAddress = _context.State.GetVertexBufferEndAddress(index);
+
+ ulong address = vertexBuffer.Address.Pack();
+
+ int stride = vertexBuffer.UnpackStride();
+
+ bool instanced = _context.State.Get(MethodOffset.VertexBufferInstanced + index);
+
+ int divisor = instanced ? vertexBuffer.Divisor : 0;
+
+ _isAnyVbInstanced |= divisor != 0;
+
+ ulong size;
+
+ if (_drawIndexed || stride == 0 || instanced)
+ {
+ // This size may be (much) larger than the real vertex buffer size.
+ // Avoid calculating it this way, unless we don't have any other option.
+ size = endAddress.Pack() - address + 1;
+ }
+ else
+ {
+ // For non-indexed draws, we can guess the size from the vertex count
+ // and stride.
+ int firstInstance = _context.State.GetBaseInstance();
+
+ VertexBufferDrawState drawState = _context.State.GetVertexBufferDrawState();
+
+ size = (ulong)((firstInstance + drawState.First + drawState.Count) * stride);
+ }
+
+ _bufferManager.SetVertexBuffer(index, address, size, stride, divisor);
+ }
+ }
+
+ private void UpdateFaceState()
+ {
+ FaceState face = _context.State.GetFaceState();
+
+ _context.Renderer.GraphicsPipeline.SetFaceCulling(face.CullEnable.IsTrue(), face.CullFace);
+
+ _context.Renderer.GraphicsPipeline.SetFrontFace(face.FrontFace);
+ }
+
+ private void UpdateRtColorMask()
+ {
+ uint[] componentMasks = new uint[Constants.TotalRenderTargets];
+
+ for (int index = 0; index < Constants.TotalRenderTargets; index++)
+ {
+ RtColorMask colorMask = _context.State.Get(MethodOffset.RtColorMask + index);
+
+ uint componentMask = 0;
+
+ componentMask = (colorMask.UnpackRed() ? 1u : 0u);
+ componentMask |= (colorMask.UnpackGreen() ? 2u : 0u);
+ componentMask |= (colorMask.UnpackBlue() ? 4u : 0u);
+ componentMask |= (colorMask.UnpackAlpha() ? 8u : 0u);
+
+ componentMasks[index] = componentMask;
+ }
+
+ _context.Renderer.GraphicsPipeline.SetRenderTargetColorMasks(componentMasks);
+ }
+
+ private void UpdateBlendState()
+ {
+ BlendState[] blends = new BlendState[8];
+
+ for (int index = 0; index < 8; index++)
+ {
+ bool blendEnable = _context.State.GetBlendEnable(index).IsTrue();
+
+ BlendState blend = _context.State.GetBlendState(index);
+
+ BlendDescriptor descriptor = new BlendDescriptor(
+ blendEnable,
+ blend.ColorOp,
+ blend.ColorSrcFactor,
+ blend.ColorDstFactor,
+ blend.AlphaOp,
+ blend.AlphaSrcFactor,
+ blend.AlphaDstFactor);
+
+ _context.Renderer.GraphicsPipeline.BindBlendState(index, descriptor);
+ }
+ }
+
+ private struct SbDescriptor
+ {
+ public uint AddressLow;
+ public uint AddressHigh;
+ public int Size;
+ public int Padding;
+
+ public ulong PackAddress()
+ {
+ return AddressLow | ((ulong)AddressHigh << 32);
+ }
+ }
+
+ private void UpdateShaderState()
+ {
+ ShaderAddresses addresses = new ShaderAddresses();
+
+ Span addressesSpan = MemoryMarshal.CreateSpan(ref addresses, 1);
+
+ Span addressesArray = MemoryMarshal.Cast(addressesSpan);
+
+ ulong baseAddress = _context.State.GetShaderBaseAddress().Pack();
+
+ for (int index = 0; index < 6; index++)
+ {
+ ShaderState shader = _context.State.GetShaderState(index);
+
+ if (!shader.UnpackEnable() && index != 1)
+ {
+ continue;
+ }
+
+ addressesArray[index] = baseAddress + shader.Offset;
+ }
+
+ GraphicsShader gs = _shaderCache.GetGraphicsShader(addresses);
+
+ _vsUsesInstanceId = gs.Shader[0].Info.UsesInstanceId;
+
+ for (int stage = 0; stage < Constants.TotalShaderStages; stage++)
+ {
+ ShaderProgramInfo info = gs.Shader[stage]?.Info;
+
+ if (info == null)
+ {
+ continue;
+ }
+
+ var textureBindings = new TextureBindingInfo[info.Textures.Count];
+
+ for (int index = 0; index < info.Textures.Count; index++)
+ {
+ var descriptor = info.Textures[index];
+
+ Target target = GetTarget(descriptor.Target);
+
+ textureBindings[index] = new TextureBindingInfo(target, descriptor.HandleIndex);
+ }
+
+ _textureManager.BindTextures(stage, textureBindings);
+
+ uint sbEnableMask = 0;
+ uint ubEnableMask = 0;
+
+ for (int index = 0; index < info.SBuffers.Count; index++)
+ {
+ BufferDescriptor sb = info.SBuffers[index];
+
+ sbEnableMask |= 1u << sb.Slot;
+
+ ulong sbDescAddress = _bufferManager.GetGraphicsUniformBufferAddress(stage, 0);
+
+ int sbDescOffset = 0x110 + stage * 0x100 + sb.Slot * 0x10;
+
+ sbDescAddress += (ulong)sbDescOffset;
+
+ Span sbDescriptorData = _context.PhysicalMemory.Read(sbDescAddress, 0x10);
+
+ SbDescriptor sbDescriptor = MemoryMarshal.Cast(sbDescriptorData)[0];
+
+ _bufferManager.SetGraphicsStorageBuffer(stage, sb.Slot, sbDescriptor.PackAddress(), (uint)sbDescriptor.Size);
+ }
+
+ for (int index = 0; index < info.CBuffers.Count; index++)
+ {
+ ubEnableMask |= 1u << info.CBuffers[index].Slot;
+ }
+
+ _bufferManager.SetGraphicsStorageBufferEnableMask(stage, sbEnableMask);
+ _bufferManager.SetGraphicsUniformBufferEnableMask(stage, ubEnableMask);
+ }
+
+ _context.Renderer.GraphicsPipeline.BindProgram(gs.Interface);
+ }
+
+ private static Target GetTarget(Shader.TextureTarget target)
+ {
+ target &= ~Shader.TextureTarget.Shadow;
+
+ switch (target)
+ {
+ case Shader.TextureTarget.Texture1D:
+ return Target.Texture1D;
+
+ case Shader.TextureTarget.Texture1D | Shader.TextureTarget.Array:
+ return Target.Texture1DArray;
+
+ case Shader.TextureTarget.Texture2D:
+ return Target.Texture2D;
+
+ case Shader.TextureTarget.Texture2D | Shader.TextureTarget.Array:
+ return Target.Texture2DArray;
+
+ case Shader.TextureTarget.Texture2D | Shader.TextureTarget.Multisample:
+ return Target.Texture2DMultisample;
+
+ case Shader.TextureTarget.Texture2D | Shader.TextureTarget.Multisample | Shader.TextureTarget.Array:
+ return Target.Texture2DMultisampleArray;
+
+ case Shader.TextureTarget.Texture3D:
+ return Target.Texture3D;
+
+ case Shader.TextureTarget.TextureCube:
+ return Target.Cubemap;
+
+ case Shader.TextureTarget.TextureCube | Shader.TextureTarget.Array:
+ return Target.CubemapArray;
+ }
+
+ // TODO: Warning.
+
+ return Target.Texture2D;
+ }
+
+ private void InvalidateTextures(int argument)
+ {
+ _textureManager.Flush();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/ShaderAddresses.cs b/Ryujinx.Graphics.Gpu/Engine/ShaderAddresses.cs
new file mode 100644
index 000000000..368b5a177
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/ShaderAddresses.cs
@@ -0,0 +1,34 @@
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ struct ShaderAddresses : IEquatable
+ {
+ public ulong VertexA;
+ public ulong Vertex;
+ public ulong TessControl;
+ public ulong TessEvaluation;
+ public ulong Geometry;
+ public ulong Fragment;
+
+ public override bool Equals(object other)
+ {
+ return other is ShaderAddresses addresses && Equals(addresses);
+ }
+
+ public bool Equals(ShaderAddresses other)
+ {
+ return VertexA == other.VertexA &&
+ Vertex == other.Vertex &&
+ TessControl == other.TessControl &&
+ TessEvaluation == other.TessEvaluation &&
+ Geometry == other.Geometry &&
+ Fragment == other.Fragment;
+ }
+
+ public override int GetHashCode()
+ {
+ return HashCode.Combine(VertexA, Vertex, TessControl, TessEvaluation, Geometry, Fragment);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/ShaderCache.cs b/Ryujinx.Graphics.Gpu/Engine/ShaderCache.cs
new file mode 100644
index 000000000..79a84a6d1
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/ShaderCache.cs
@@ -0,0 +1,228 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Gpu.State;
+using Ryujinx.Graphics.Shader;
+using Ryujinx.Graphics.Shader.Translation;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ class ShaderCache
+ {
+ private const int MaxProgramSize = 0x100000;
+
+ private GpuContext _context;
+
+ private ShaderDumper _dumper;
+
+ private Dictionary _cpPrograms;
+
+ private Dictionary _gpPrograms;
+
+ public ShaderCache(GpuContext context)
+ {
+ _context = context;
+
+ _dumper = new ShaderDumper(context);
+
+ _cpPrograms = new Dictionary();
+
+ _gpPrograms = new Dictionary();
+ }
+
+ public ComputeShader GetComputeShader(ulong gpuVa, int localSizeX, int localSizeY, int localSizeZ)
+ {
+ if (!_cpPrograms.TryGetValue(gpuVa, out ComputeShader cpShader))
+ {
+ ShaderProgram shader = TranslateComputeShader(gpuVa);
+
+ shader.Replace(DefineNames.LocalSizeX, localSizeX.ToString(CultureInfo.InvariantCulture));
+ shader.Replace(DefineNames.LocalSizeY, localSizeY.ToString(CultureInfo.InvariantCulture));
+ shader.Replace(DefineNames.LocalSizeZ, localSizeZ.ToString(CultureInfo.InvariantCulture));
+
+ IShader hostShader = _context.Renderer.CompileShader(shader);
+
+ IProgram program = _context.Renderer.CreateProgram(new IShader[] { hostShader });
+
+ cpShader = new ComputeShader(program, shader);
+
+ _cpPrograms.Add(gpuVa, cpShader);
+ }
+
+ return cpShader;
+ }
+
+ public GraphicsShader GetGraphicsShader(ShaderAddresses addresses)
+ {
+ if (!_gpPrograms.TryGetValue(addresses, out GraphicsShader gpShader))
+ {
+ gpShader = new GraphicsShader();
+
+ if (addresses.VertexA != 0)
+ {
+ gpShader.Shader[0] = TranslateGraphicsShader(addresses.Vertex, addresses.VertexA);
+ }
+ else
+ {
+ gpShader.Shader[0] = TranslateGraphicsShader(addresses.Vertex);
+ }
+
+ gpShader.Shader[1] = TranslateGraphicsShader(addresses.TessControl);
+ gpShader.Shader[2] = TranslateGraphicsShader(addresses.TessEvaluation);
+ gpShader.Shader[3] = TranslateGraphicsShader(addresses.Geometry);
+ gpShader.Shader[4] = TranslateGraphicsShader(addresses.Fragment);
+
+ BackpropQualifiers(gpShader);
+
+ List shaders = new List();
+
+ for (int stage = 0; stage < gpShader.Shader.Length; stage++)
+ {
+ if (gpShader.Shader[stage] == null)
+ {
+ continue;
+ }
+
+ IShader shader = _context.Renderer.CompileShader(gpShader.Shader[stage]);
+
+ shaders.Add(shader);
+ }
+
+ gpShader.Interface = _context.Renderer.CreateProgram(shaders.ToArray());
+
+ _gpPrograms.Add(addresses, gpShader);
+ }
+
+ return gpShader;
+ }
+
+ private ShaderProgram TranslateComputeShader(ulong gpuVa)
+ {
+ if (gpuVa == 0)
+ {
+ return null;
+ }
+
+ ShaderProgram program;
+
+ const TranslationFlags flags =
+ TranslationFlags.Compute |
+ TranslationFlags.Unspecialized;
+
+ TranslationConfig translationConfig = new TranslationConfig(0x10000, _dumper.CurrentDumpIndex, flags);
+
+ Span code = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
+
+ program = Translator.Translate(code, translationConfig);
+
+ _dumper.Dump(gpuVa, compute : true);
+
+ return program;
+ }
+
+ private ShaderProgram TranslateGraphicsShader(ulong gpuVa, ulong gpuVaA = 0)
+ {
+ if (gpuVa == 0)
+ {
+ return null;
+ }
+
+ ShaderProgram program;
+
+ const TranslationFlags flags =
+ TranslationFlags.DebugMode |
+ TranslationFlags.Unspecialized;
+
+ TranslationConfig translationConfig = new TranslationConfig(0x10000, _dumper.CurrentDumpIndex, flags);
+
+ if (gpuVaA != 0)
+ {
+ Span codeA = _context.MemoryAccessor.Read(gpuVaA, MaxProgramSize);
+ Span codeB = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
+
+ program = Translator.Translate(codeA, codeB, translationConfig);
+
+ _dumper.Dump(gpuVaA, compute: false);
+ _dumper.Dump(gpuVa, compute: false);
+ }
+ else
+ {
+ Span code = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
+
+ program = Translator.Translate(code, translationConfig);
+
+ _dumper.Dump(gpuVa, compute: false);
+ }
+
+ if (program.Stage == ShaderStage.Geometry)
+ {
+ PrimitiveType primitiveType = _context.Methods.PrimitiveType;
+
+ string inPrimitive = "points";
+
+ switch (primitiveType)
+ {
+ case PrimitiveType.Points:
+ inPrimitive = "points";
+ break;
+ case PrimitiveType.Lines:
+ case PrimitiveType.LineLoop:
+ case PrimitiveType.LineStrip:
+ inPrimitive = "lines";
+ break;
+ case PrimitiveType.LinesAdjacency:
+ case PrimitiveType.LineStripAdjacency:
+ inPrimitive = "lines_adjacency";
+ break;
+ case PrimitiveType.Triangles:
+ case PrimitiveType.TriangleStrip:
+ case PrimitiveType.TriangleFan:
+ inPrimitive = "triangles";
+ break;
+ case PrimitiveType.TrianglesAdjacency:
+ case PrimitiveType.TriangleStripAdjacency:
+ inPrimitive = "triangles_adjacency";
+ break;
+ }
+
+ program.Replace(DefineNames.InputTopologyName, inPrimitive);
+ }
+
+ return program;
+ }
+
+ private void BackpropQualifiers(GraphicsShader program)
+ {
+ ShaderProgram fragmentShader = program.Shader[4];
+
+ bool isFirst = true;
+
+ for (int stage = 3; stage >= 0; stage--)
+ {
+ if (program.Shader[stage] == null)
+ {
+ continue;
+ }
+
+ // We need to iterate backwards, since we do name replacement,
+ // and it would otherwise replace a subset of the longer names.
+ for (int attr = 31; attr >= 0; attr--)
+ {
+ string iq = fragmentShader?.Info.InterpolationQualifiers[attr].ToGlslQualifier() ?? string.Empty;
+
+ if (isFirst && iq != string.Empty)
+ {
+ program.Shader[stage].Replace($"{DefineNames.OutQualifierPrefixName}{attr}", iq);
+ }
+ else
+ {
+ program.Shader[stage].Replace($"{DefineNames.OutQualifierPrefixName}{attr} ", string.Empty);
+ }
+ }
+
+ isFirst = false;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Engine/ShaderDumper.cs b/Ryujinx.Graphics.Gpu/Engine/ShaderDumper.cs
new file mode 100644
index 000000000..fdcf06121
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Engine/ShaderDumper.cs
@@ -0,0 +1,126 @@
+using System.IO;
+
+namespace Ryujinx.Graphics.Gpu.Engine
+{
+ class ShaderDumper
+ {
+ private const int ShaderHeaderSize = 0x50;
+
+ private GpuContext _context;
+
+ private string _runtimeDir;
+ private string _dumpPath;
+ private int _dumpIndex;
+
+ public int CurrentDumpIndex => _dumpIndex;
+
+ public ShaderDumper(GpuContext context)
+ {
+ _context = context;
+
+ _dumpIndex = 1;
+ }
+
+ public void Dump(ulong gpuVa, bool compute)
+ {
+ _dumpPath = GraphicsConfig.ShadersDumpPath;
+
+ if (string.IsNullOrWhiteSpace(_dumpPath))
+ {
+ return;
+ }
+
+ string fileName = "Shader" + _dumpIndex.ToString("d4") + ".bin";
+
+ string fullPath = Path.Combine(FullDir(), fileName);
+ string codePath = Path.Combine(CodeDir(), fileName);
+
+ _dumpIndex++;
+
+ ulong headerSize = compute ? 0UL : ShaderHeaderSize;
+
+ using (FileStream fullFile = File.Create(fullPath))
+ using (FileStream codeFile = File.Create(codePath))
+ {
+ BinaryWriter fullWriter = new BinaryWriter(fullFile);
+ BinaryWriter codeWriter = new BinaryWriter(codeFile);
+
+ for (ulong i = 0; i < headerSize; i += 4)
+ {
+ fullWriter.Write(_context.MemoryAccessor.ReadInt32(gpuVa + i));
+ }
+
+ ulong offset = 0;
+
+ ulong instruction = 0;
+
+ // Dump until a NOP instruction is found.
+ while ((instruction >> 48 & 0xfff8) != 0x50b0)
+ {
+ uint word0 = (uint)_context.MemoryAccessor.ReadInt32(gpuVa + headerSize + offset + 0);
+ uint word1 = (uint)_context.MemoryAccessor.ReadInt32(gpuVa + headerSize + offset + 4);
+
+ instruction = word0 | (ulong)word1 << 32;
+
+ // Zero instructions (other kind of NOP) stop immediately,
+ // this is to avoid two rows of zeroes.
+ if (instruction == 0)
+ {
+ break;
+ }
+
+ fullWriter.Write(instruction);
+ codeWriter.Write(instruction);
+
+ offset += 8;
+ }
+
+ // Align to meet nvdisasm requirements.
+ while (offset % 0x20 != 0)
+ {
+ fullWriter.Write(0);
+ codeWriter.Write(0);
+
+ offset += 4;
+ }
+ }
+ }
+
+ private string FullDir()
+ {
+ return CreateAndReturn(Path.Combine(DumpDir(), "Full"));
+ }
+
+ private string CodeDir()
+ {
+ return CreateAndReturn(Path.Combine(DumpDir(), "Code"));
+ }
+
+ private string DumpDir()
+ {
+ if (string.IsNullOrEmpty(_runtimeDir))
+ {
+ int index = 1;
+
+ do
+ {
+ _runtimeDir = Path.Combine(_dumpPath, "Dumps" + index.ToString("d2"));
+
+ index++;
+ }
+ while (Directory.Exists(_runtimeDir));
+
+ Directory.CreateDirectory(_runtimeDir);
+ }
+
+ return _runtimeDir;
+ }
+
+ private static string CreateAndReturn(string dir)
+ {
+ Directory.CreateDirectory(dir);
+
+ return dir;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/GpuContext.cs b/Ryujinx.Graphics.Gpu/GpuContext.cs
new file mode 100644
index 000000000..1e865e6a7
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/GpuContext.cs
@@ -0,0 +1,100 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.Gpu.Engine;
+using Ryujinx.Graphics.Gpu.Image;
+using Ryujinx.Graphics.Gpu.Memory;
+using Ryujinx.Graphics.Gpu.State;
+using System;
+
+namespace Ryujinx.Graphics.Gpu
+{
+ public class GpuContext
+ {
+ public IRenderer Renderer { get; }
+
+ internal GpuState State { get; }
+
+ internal IPhysicalMemory PhysicalMemory { get; private set; }
+
+ public MemoryManager MemoryManager { get; }
+
+ internal MemoryAccessor MemoryAccessor { get; }
+
+ internal Methods Methods { get; }
+
+ internal NvGpuFifo Fifo { get; }
+
+ public DmaPusher DmaPusher { get; }
+
+ internal int SequenceNumber { get; private set; }
+
+ private Lazy _caps;
+
+ internal Capabilities Capabilities => _caps.Value;
+
+ public GpuContext(IRenderer renderer)
+ {
+ Renderer = renderer;
+
+ State = new GpuState();
+
+ MemoryManager = new MemoryManager();
+
+ MemoryAccessor = new MemoryAccessor(this);
+
+ Methods = new Methods(this);
+
+ Fifo = new NvGpuFifo(this);
+
+ DmaPusher = new DmaPusher(this);
+
+ _caps = new Lazy(GetCapabilities);
+ }
+
+ internal void AdvanceSequence()
+ {
+ SequenceNumber++;
+ }
+
+ public ITexture GetTexture(
+ ulong address,
+ int width,
+ int height,
+ int stride,
+ bool isLinear,
+ int gobBlocksInY,
+ Format format,
+ int bytesPerPixel)
+ {
+ FormatInfo formatInfo = new FormatInfo(format, 1, 1, bytesPerPixel);
+
+ TextureInfo info = new TextureInfo(
+ address,
+ width,
+ height,
+ 1,
+ 1,
+ 1,
+ 1,
+ stride,
+ isLinear,
+ gobBlocksInY,
+ 1,
+ 1,
+ Target.Texture2D,
+ formatInfo);
+
+ return Methods.GetTexture(address)?.HostTexture;
+ }
+
+ private Capabilities GetCapabilities()
+ {
+ return Renderer.GetCapabilities();
+ }
+
+ public void SetVmm(IPhysicalMemory mm)
+ {
+ PhysicalMemory = mm;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/GraphicsConfig.cs b/Ryujinx.Graphics.Gpu/GraphicsConfig.cs
new file mode 100644
index 000000000..c5eaa0b35
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/GraphicsConfig.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Gpu
+{
+ public static class GraphicsConfig
+ {
+ public static string ShadersDumpPath;
+
+ public static bool FastGpuTime = true;
+
+ public static bool DisableTUpdate;
+ public static bool DisableBUpdate;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs b/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs
new file mode 100644
index 000000000..33ed78818
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs
@@ -0,0 +1,62 @@
+using System.Collections;
+using System.Collections.Generic;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ class AutoDeleteCache : IEnumerable
+ {
+ private const int MaxCapacity = 2048;
+
+ private LinkedList _textures;
+
+ public AutoDeleteCache()
+ {
+ _textures = new LinkedList();
+ }
+
+ public void Add(Texture texture)
+ {
+ texture.IncrementReferenceCount();
+
+ texture.CacheNode = _textures.AddLast(texture);
+
+ if (_textures.Count > MaxCapacity)
+ {
+ Texture oldestTexture = _textures.First.Value;
+
+ _textures.RemoveFirst();
+
+ oldestTexture.DecrementReferenceCount();
+
+ oldestTexture.CacheNode = null;
+ }
+ }
+
+ public void Lift(Texture texture)
+ {
+ if (texture.CacheNode != null)
+ {
+ if (texture.CacheNode != _textures.Last)
+ {
+ _textures.Remove(texture.CacheNode);
+
+ texture.CacheNode = _textures.AddLast(texture);
+ }
+ }
+ else
+ {
+ Add(texture);
+ }
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ return _textures.GetEnumerator();
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return _textures.GetEnumerator();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/FormatInfo.cs b/Ryujinx.Graphics.Gpu/Image/FormatInfo.cs
new file mode 100644
index 000000000..a728c66e1
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/FormatInfo.cs
@@ -0,0 +1,31 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ struct FormatInfo
+ {
+ private static FormatInfo _rgba8 = new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4);
+
+ public static FormatInfo Default => _rgba8;
+
+ public Format Format { get; }
+
+ public int BlockWidth { get; }
+ public int BlockHeight { get; }
+ public int BytesPerPixel { get; }
+
+ public bool IsCompressed => (BlockWidth | BlockHeight) != 1;
+
+ public FormatInfo(
+ Format format,
+ int blockWidth,
+ int blockHeight,
+ int bytesPerPixel)
+ {
+ Format = format;
+ BlockWidth = blockWidth;
+ BlockHeight = blockHeight;
+ BytesPerPixel = bytesPerPixel;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/FormatTable.cs b/Ryujinx.Graphics.Gpu/Image/FormatTable.cs
new file mode 100644
index 000000000..9f5b26d4b
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/FormatTable.cs
@@ -0,0 +1,201 @@
+using Ryujinx.Graphics.GAL;
+using System.Collections.Generic;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ static class FormatTable
+ {
+ private static Dictionary _textureFormats = new Dictionary()
+ {
+ { 0x2491d, new FormatInfo(Format.R8Unorm, 1, 1, 1) },
+ { 0x1249d, new FormatInfo(Format.R8Snorm, 1, 1, 1) },
+ { 0x4921d, new FormatInfo(Format.R8Uint, 1, 1, 1) },
+ { 0x36d9d, new FormatInfo(Format.R8Sint, 1, 1, 1) },
+ { 0x7ff9b, new FormatInfo(Format.R16Float, 1, 1, 2) },
+ { 0x2491b, new FormatInfo(Format.R16Unorm, 1, 1, 2) },
+ { 0x1249b, new FormatInfo(Format.R16Snorm, 1, 1, 2) },
+ { 0x4921b, new FormatInfo(Format.R16Uint, 1, 1, 2) },
+ { 0x36d9b, new FormatInfo(Format.R16Sint, 1, 1, 2) },
+ { 0x7ff8f, new FormatInfo(Format.R32Float, 1, 1, 4) },
+ { 0x4920f, new FormatInfo(Format.R32Uint, 1, 1, 4) },
+ { 0x36d8f, new FormatInfo(Format.R32Sint, 1, 1, 4) },
+ { 0x24918, new FormatInfo(Format.R8G8Unorm, 1, 1, 2) },
+ { 0x12498, new FormatInfo(Format.R8G8Snorm, 1, 1, 2) },
+ { 0x49218, new FormatInfo(Format.R8G8Uint, 1, 1, 2) },
+ { 0x36d98, new FormatInfo(Format.R8G8Sint, 1, 1, 2) },
+ { 0x7ff8c, new FormatInfo(Format.R16G16Float, 1, 1, 4) },
+ { 0x2490c, new FormatInfo(Format.R16G16Unorm, 1, 1, 4) },
+ { 0x1248c, new FormatInfo(Format.R16G16Snorm, 1, 1, 4) },
+ { 0x4920c, new FormatInfo(Format.R16G16Uint, 1, 1, 4) },
+ { 0x36d8c, new FormatInfo(Format.R16G16Sint, 1, 1, 4) },
+ { 0x7ff84, new FormatInfo(Format.R32G32Float, 1, 1, 8) },
+ { 0x49204, new FormatInfo(Format.R32G32Uint, 1, 1, 8) },
+ { 0x36d84, new FormatInfo(Format.R32G32Sint, 1, 1, 8) },
+ { 0x7ff82, new FormatInfo(Format.R32G32B32Float, 1, 1, 12) },
+ { 0x49202, new FormatInfo(Format.R32G32B32Uint, 1, 1, 12) },
+ { 0x36d82, new FormatInfo(Format.R32G32B32Sint, 1, 1, 12) },
+ { 0x24908, new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4) },
+ { 0x12488, new FormatInfo(Format.R8G8B8A8Snorm, 1, 1, 4) },
+ { 0x49208, new FormatInfo(Format.R8G8B8A8Uint, 1, 1, 4) },
+ { 0x36d88, new FormatInfo(Format.R8G8B8A8Sint, 1, 1, 4) },
+ { 0x7ff83, new FormatInfo(Format.R16G16B16A16Float, 1, 1, 8) },
+ { 0x24903, new FormatInfo(Format.R16G16B16A16Unorm, 1, 1, 8) },
+ { 0x12483, new FormatInfo(Format.R16G16B16A16Snorm, 1, 1, 8) },
+ { 0x49203, new FormatInfo(Format.R16G16B16A16Uint, 1, 1, 8) },
+ { 0x36d83, new FormatInfo(Format.R16G16B16A16Sint, 1, 1, 8) },
+ { 0x7ff81, new FormatInfo(Format.R32G32B32A32Float, 1, 1, 16) },
+ { 0x49201, new FormatInfo(Format.R32G32B32A32Uint, 1, 1, 16) },
+ { 0x36d81, new FormatInfo(Format.R32G32B32A32Sint, 1, 1, 16) },
+ { 0x2493a, new FormatInfo(Format.D16Unorm, 1, 1, 2) },
+ { 0x7ffaf, new FormatInfo(Format.D32Float, 1, 1, 4) },
+ { 0x24a29, new FormatInfo(Format.D24UnormS8Uint, 1, 1, 4) },
+ { 0x253b0, new FormatInfo(Format.D32FloatS8Uint, 1, 1, 8) },
+ { 0xa4908, new FormatInfo(Format.R8G8B8A8Srgb, 1, 1, 4) },
+ { 0x24912, new FormatInfo(Format.R4G4B4A4Unorm, 1, 1, 2) },
+ { 0x24914, new FormatInfo(Format.R5G5B5A1Unorm, 1, 1, 2) },
+ { 0x24915, new FormatInfo(Format.R5G6B5Unorm, 1, 1, 2) },
+ { 0x24909, new FormatInfo(Format.R10G10B10A2Unorm, 1, 1, 4) },
+ { 0x49209, new FormatInfo(Format.R10G10B10A2Uint, 1, 1, 4) },
+ { 0x7ffa1, new FormatInfo(Format.R11G11B10Float, 1, 1, 4) },
+ { 0x7ffa0, new FormatInfo(Format.R9G9B9E5Float, 1, 1, 4) },
+ { 0x24924, new FormatInfo(Format.Bc1RgbaUnorm, 4, 4, 8) },
+ { 0x24925, new FormatInfo(Format.Bc2Unorm, 4, 4, 16) },
+ { 0x24926, new FormatInfo(Format.Bc3Unorm, 4, 4, 16) },
+ { 0xa4924, new FormatInfo(Format.Bc1RgbaSrgb, 4, 4, 8) },
+ { 0xa4925, new FormatInfo(Format.Bc2Srgb, 4, 4, 16) },
+ { 0xa4926, new FormatInfo(Format.Bc3Srgb, 4, 4, 16) },
+ { 0x24927, new FormatInfo(Format.Bc4Unorm, 4, 4, 8) },
+ { 0x124a7, new FormatInfo(Format.Bc4Snorm, 4, 4, 8) },
+ { 0x24928, new FormatInfo(Format.Bc5Unorm, 4, 4, 16) },
+ { 0x124a8, new FormatInfo(Format.Bc5Snorm, 4, 4, 16) },
+ { 0x24917, new FormatInfo(Format.Bc7Unorm, 4, 4, 16) },
+ { 0xa4917, new FormatInfo(Format.Bc7Srgb, 4, 4, 16) },
+ { 0x7ff90, new FormatInfo(Format.Bc6HUfloat, 4, 4, 16) },
+ { 0x7ff91, new FormatInfo(Format.Bc6HSfloat, 4, 4, 16) },
+ { 0x24940, new FormatInfo(Format.Astc4x4Unorm, 4, 4, 16) },
+ { 0x24950, new FormatInfo(Format.Astc5x4Unorm, 5, 4, 16) },
+ { 0x24941, new FormatInfo(Format.Astc5x5Unorm, 5, 5, 16) },
+ { 0x24951, new FormatInfo(Format.Astc6x5Unorm, 6, 5, 16) },
+ { 0x24942, new FormatInfo(Format.Astc6x6Unorm, 6, 6, 16) },
+ { 0x24955, new FormatInfo(Format.Astc8x5Unorm, 8, 5, 16) },
+ { 0x24952, new FormatInfo(Format.Astc8x6Unorm, 8, 6, 16) },
+ { 0x24944, new FormatInfo(Format.Astc8x8Unorm, 8, 8, 16) },
+ { 0x24956, new FormatInfo(Format.Astc10x5Unorm, 10, 5, 16) },
+ { 0x24957, new FormatInfo(Format.Astc10x6Unorm, 10, 6, 16) },
+ { 0x24953, new FormatInfo(Format.Astc10x8Unorm, 10, 8, 16) },
+ { 0x24945, new FormatInfo(Format.Astc10x10Unorm, 10, 10, 16) },
+ { 0x24954, new FormatInfo(Format.Astc12x10Unorm, 12, 10, 16) },
+ { 0x24946, new FormatInfo(Format.Astc12x12Unorm, 12, 12, 16) },
+ { 0xa4940, new FormatInfo(Format.Astc4x4Srgb, 4, 4, 16) },
+ { 0xa4950, new FormatInfo(Format.Astc5x4Srgb, 5, 4, 16) },
+ { 0xa4941, new FormatInfo(Format.Astc5x5Srgb, 5, 5, 16) },
+ { 0xa4951, new FormatInfo(Format.Astc6x5Srgb, 6, 5, 16) },
+ { 0xa4942, new FormatInfo(Format.Astc6x6Srgb, 6, 6, 16) },
+ { 0xa4955, new FormatInfo(Format.Astc8x5Srgb, 8, 5, 16) },
+ { 0xa4952, new FormatInfo(Format.Astc8x6Srgb, 8, 6, 16) },
+ { 0xa4944, new FormatInfo(Format.Astc8x8Srgb, 8, 8, 16) },
+ { 0xa4956, new FormatInfo(Format.Astc10x5Srgb, 10, 5, 16) },
+ { 0xa4957, new FormatInfo(Format.Astc10x6Srgb, 10, 6, 16) },
+ { 0xa4953, new FormatInfo(Format.Astc10x8Srgb, 10, 8, 16) },
+ { 0xa4945, new FormatInfo(Format.Astc10x10Srgb, 10, 10, 16) },
+ { 0xa4954, new FormatInfo(Format.Astc12x10Srgb, 12, 10, 16) },
+ { 0xa4946, new FormatInfo(Format.Astc12x12Srgb, 12, 12, 16) },
+ { 0x24913, new FormatInfo(Format.A1B5G5R5Unorm, 1, 1, 2) }
+ };
+
+ private static Dictionary _attribFormats = new Dictionary()
+ {
+ { 0x13a00000, Format.R8Unorm },
+ { 0x0ba00000, Format.R8Snorm },
+ { 0x23a00000, Format.R8Uint },
+ { 0x1ba00000, Format.R8Sint },
+ { 0x3b600000, Format.R16Float },
+ { 0x13600000, Format.R16Unorm },
+ { 0x0b600000, Format.R16Snorm },
+ { 0x23600000, Format.R16Uint },
+ { 0x1b600000, Format.R16Sint },
+ { 0x3a400000, Format.R32Float },
+ { 0x22400000, Format.R32Uint },
+ { 0x1a400000, Format.R32Sint },
+ { 0x13000000, Format.R8G8Unorm },
+ { 0x0b000000, Format.R8G8Snorm },
+ { 0x23000000, Format.R8G8Uint },
+ { 0x1b000000, Format.R8G8Sint },
+ { 0x39e00000, Format.R16G16Float },
+ { 0x11e00000, Format.R16G16Unorm },
+ { 0x09e00000, Format.R16G16Snorm },
+ { 0x21e00000, Format.R16G16Uint },
+ { 0x19e00000, Format.R16G16Sint },
+ { 0x38800000, Format.R32G32Float },
+ { 0x20800000, Format.R32G32Uint },
+ { 0x18800000, Format.R32G32Sint },
+ { 0x12600000, Format.R8G8B8Unorm },
+ { 0x0a600000, Format.R8G8B8Snorm },
+ { 0x22600000, Format.R8G8B8Uint },
+ { 0x1a600000, Format.R8G8B8Sint },
+ { 0x38a00000, Format.R16G16B16Float },
+ { 0x10a00000, Format.R16G16B16Unorm },
+ { 0x08a00000, Format.R16G16B16Snorm },
+ { 0x20a00000, Format.R16G16B16Uint },
+ { 0x18a00000, Format.R16G16B16Sint },
+ { 0x38400000, Format.R32G32B32Float },
+ { 0x20400000, Format.R32G32B32Uint },
+ { 0x18400000, Format.R32G32B32Sint },
+ { 0x11400000, Format.R8G8B8A8Unorm },
+ { 0x09400000, Format.R8G8B8A8Snorm },
+ { 0x21400000, Format.R8G8B8A8Uint },
+ { 0x19400000, Format.R8G8B8A8Sint },
+ { 0x38600000, Format.R16G16B16A16Float },
+ { 0x10600000, Format.R16G16B16A16Unorm },
+ { 0x08600000, Format.R16G16B16A16Snorm },
+ { 0x20600000, Format.R16G16B16A16Uint },
+ { 0x18600000, Format.R16G16B16A16Sint },
+ { 0x38200000, Format.R32G32B32A32Float },
+ { 0x20200000, Format.R32G32B32A32Uint },
+ { 0x18200000, Format.R32G32B32A32Sint },
+ { 0x16000000, Format.R10G10B10A2Unorm },
+ { 0x26000000, Format.R10G10B10A2Uint },
+ { 0x3e200000, Format.R11G11B10Float },
+ { 0x2ba00000, Format.R8Uscaled },
+ { 0x33a00000, Format.R8Sscaled },
+ { 0x2b600000, Format.R16Uscaled },
+ { 0x33600000, Format.R16Sscaled },
+ { 0x2a400000, Format.R32Uscaled },
+ { 0x32400000, Format.R32Sscaled },
+ { 0x2b000000, Format.R8G8Uscaled },
+ { 0x33000000, Format.R8G8Sscaled },
+ { 0x29e00000, Format.R16G16Uscaled },
+ { 0x31e00000, Format.R16G16Sscaled },
+ { 0x28800000, Format.R32G32Uscaled },
+ { 0x30800000, Format.R32G32Sscaled },
+ { 0x2a600000, Format.R8G8B8Uscaled },
+ { 0x32600000, Format.R8G8B8Sscaled },
+ { 0x28a00000, Format.R16G16B16Uscaled },
+ { 0x30a00000, Format.R16G16B16Sscaled },
+ { 0x28400000, Format.R32G32B32Uscaled },
+ { 0x30400000, Format.R32G32B32Sscaled },
+ { 0x29400000, Format.R8G8B8A8Uscaled },
+ { 0x31400000, Format.R8G8B8A8Sscaled },
+ { 0x28600000, Format.R16G16B16A16Uscaled },
+ { 0x30600000, Format.R16G16B16A16Sscaled },
+ { 0x28200000, Format.R32G32B32A32Uscaled },
+ { 0x30200000, Format.R32G32B32A32Sscaled },
+ { 0x0e000000, Format.R10G10B10A2Snorm },
+ { 0x1e000000, Format.R10G10B10A2Sint },
+ { 0x2e000000, Format.R10G10B10A2Uscaled },
+ { 0x36000000, Format.R10G10B10A2Sscaled }
+ };
+
+ public static bool TryGetTextureFormat(uint encoded, bool isSrgb, out FormatInfo format)
+ {
+ encoded |= (isSrgb ? 1u << 19 : 0u);
+
+ return _textureFormats.TryGetValue(encoded, out format);
+ }
+
+ public static bool TryGetAttribFormat(uint encoded, out Format format)
+ {
+ return _attribFormats.TryGetValue(encoded, out format);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/Pool.cs b/Ryujinx.Graphics.Gpu/Image/Pool.cs
new file mode 100644
index 000000000..196fc137e
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/Pool.cs
@@ -0,0 +1,99 @@
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ abstract class Pool : IDisposable
+ {
+ protected const int DescriptorSize = 0x20;
+
+ protected GpuContext Context;
+
+ protected T[] Items;
+
+ public ulong Address { get; }
+ public ulong Size { get; }
+
+ public Pool(GpuContext context, ulong address, int maximumId)
+ {
+ Context = context;
+
+ int count = maximumId + 1;
+
+ ulong size = (ulong)(uint)count * DescriptorSize;;
+
+ Items = new T[count];
+
+ Address = address;
+ Size = size;
+ }
+
+ public abstract T Get(int id);
+
+ public void SynchronizeMemory()
+ {
+ (ulong, ulong)[] modifiedRanges = Context.PhysicalMemory.GetModifiedRanges(Address, Size);
+
+ for (int index = 0; index < modifiedRanges.Length; index++)
+ {
+ (ulong mAddress, ulong mSize) = modifiedRanges[index];
+
+ if (mAddress < Address)
+ {
+ mAddress = Address;
+ }
+
+ ulong maxSize = Address + Size - mAddress;
+
+ if (mSize > maxSize)
+ {
+ mSize = maxSize;
+ }
+
+ InvalidateRangeImpl(mAddress, mSize);
+ }
+ }
+
+ public void InvalidateRange(ulong address, ulong size)
+ {
+ ulong endAddress = address + size;
+
+ ulong texturePoolEndAddress = Address + Size;
+
+ // If the range being invalidated is not overlapping the texture pool range,
+ // then we don't have anything to do, exit early.
+ if (address >= texturePoolEndAddress || endAddress <= Address)
+ {
+ return;
+ }
+
+ if (address < Address)
+ {
+ address = Address;
+ }
+
+ if (endAddress > texturePoolEndAddress)
+ {
+ endAddress = texturePoolEndAddress;
+ }
+
+ InvalidateRangeImpl(address, size);
+ }
+
+ protected abstract void InvalidateRangeImpl(ulong address, ulong size);
+
+ protected abstract void Delete(T item);
+
+ public void Dispose()
+ {
+ if (Items != null)
+ {
+ for (int index = 0; index < Items.Length; index++)
+ {
+ Delete(Items[index]);
+ }
+
+ Items = null;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/ReductionFilter.cs b/Ryujinx.Graphics.Gpu/Image/ReductionFilter.cs
new file mode 100644
index 000000000..f14a17f2e
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/ReductionFilter.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ enum ReductionFilter
+ {
+ Average,
+ Minimum,
+ Maximum
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/Image/Sampler.cs b/Ryujinx.Graphics.Gpu/Image/Sampler.cs
new file mode 100644
index 000000000..06fedd8a0
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/Sampler.cs
@@ -0,0 +1,52 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Color;
+using Ryujinx.Graphics.GAL.Sampler;
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ class Sampler : IDisposable
+ {
+ public ISampler HostSampler { get; }
+
+ public Sampler(GpuContext context, SamplerDescriptor descriptor)
+ {
+ MinFilter minFilter = descriptor.UnpackMinFilter();
+ MagFilter magFilter = descriptor.UnpackMagFilter();
+
+ AddressMode addressU = descriptor.UnpackAddressU();
+ AddressMode addressV = descriptor.UnpackAddressV();
+ AddressMode addressP = descriptor.UnpackAddressP();
+
+ CompareMode compareMode = descriptor.UnpackCompareMode();
+ CompareOp compareOp = descriptor.UnpackCompareOp();
+
+ ColorF color = new ColorF(0, 0, 0, 0);
+
+ float minLod = descriptor.UnpackMinLod();
+ float maxLod = descriptor.UnpackMaxLod();
+ float mipLodBias = descriptor.UnpackMipLodBias();
+
+ float maxAnisotropy = descriptor.UnpackMaxAnisotropy();
+
+ HostSampler = context.Renderer.CreateSampler(new SamplerCreateInfo(
+ minFilter,
+ magFilter,
+ addressU,
+ addressV,
+ addressP,
+ compareMode,
+ compareOp,
+ color,
+ minLod,
+ maxLod,
+ mipLodBias,
+ maxAnisotropy));
+ }
+
+ public void Dispose()
+ {
+ HostSampler.Dispose();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/SamplerDescriptor.cs b/Ryujinx.Graphics.Gpu/Image/SamplerDescriptor.cs
new file mode 100644
index 000000000..0a43dd1b9
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/SamplerDescriptor.cs
@@ -0,0 +1,132 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Sampler;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ struct SamplerDescriptor
+ {
+ private static readonly float[] _f5ToF32ConversionLut = new float[]
+ {
+ 0.0f,
+ 0.055555556f,
+ 0.1f,
+ 0.13636364f,
+ 0.16666667f,
+ 0.1923077f,
+ 0.21428572f,
+ 0.23333333f,
+ 0.25f,
+ 0.2777778f,
+ 0.3f,
+ 0.3181818f,
+ 0.33333334f,
+ 0.34615386f,
+ 0.35714287f,
+ 0.36666667f,
+ 0.375f,
+ 0.3888889f,
+ 0.4f,
+ 0.4090909f,
+ 0.41666666f,
+ 0.42307693f,
+ 0.42857143f,
+ 0.43333334f,
+ 0.4375f,
+ 0.44444445f,
+ 0.45f,
+ 0.45454547f,
+ 0.45833334f,
+ 0.46153846f,
+ 0.4642857f,
+ 0.46666667f
+ };
+
+ private static readonly float[] _maxAnisotropyLut = new float[]
+ {
+ 1, 2, 4, 6, 8, 10, 12, 16
+ };
+
+ private const float Frac8ToF32 = 1.0f / 256.0f;
+
+ public uint Word0;
+ public uint Word1;
+ public uint Word2;
+ public uint Word3;
+ public uint BorderColorR;
+ public uint BorderColorG;
+ public uint BorderColorB;
+ public uint BorderColorA;
+
+ public AddressMode UnpackAddressU()
+ {
+ return (AddressMode)(Word0 & 7);
+ }
+
+ public AddressMode UnpackAddressV()
+ {
+ return (AddressMode)((Word0 >> 3) & 7);
+ }
+
+ public AddressMode UnpackAddressP()
+ {
+ return (AddressMode)((Word0 >> 6) & 7);
+ }
+
+ public CompareMode UnpackCompareMode()
+ {
+ return (CompareMode)((Word0 >> 9) & 1);
+ }
+
+ public CompareOp UnpackCompareOp()
+ {
+ return (CompareOp)(((Word0 >> 10) & 7) + 1);
+ }
+
+ public float UnpackMaxAnisotropy()
+ {
+ return _maxAnisotropyLut[(Word0 >> 20) & 7];
+ }
+
+ public MagFilter UnpackMagFilter()
+ {
+ return (MagFilter)(Word1 & 3);
+ }
+
+ public MinFilter UnpackMinFilter()
+ {
+ int minFilter = (int)(Word1 >> 4) & 3;
+ int mipFilter = (int)(Word1 >> 6) & 3;
+
+ return (MinFilter)(minFilter + (mipFilter - 1) * 2);
+ }
+
+ public ReductionFilter UnpackReductionFilter()
+ {
+ return (ReductionFilter)((Word1 >> 10) & 3);
+ }
+
+ public float UnpackMipLodBias()
+ {
+ int fixedValue = (int)(Word1 >> 12) & 0x1fff;
+
+ fixedValue = (fixedValue << 19) >> 19;
+
+ return fixedValue * Frac8ToF32;
+ }
+
+ public float UnpackLodSnap()
+ {
+ return _f5ToF32ConversionLut[(Word1 >> 26) & 0x1f];
+ }
+
+ public float UnpackMinLod()
+ {
+ return (Word2 & 0xfff) * Frac8ToF32;
+ }
+
+ public float UnpackMaxLod()
+ {
+ return ((Word2 >> 12) & 0xfff) * Frac8ToF32;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/Image/SamplerPool.cs b/Ryujinx.Graphics.Gpu/Image/SamplerPool.cs
new file mode 100644
index 000000000..970a09832
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/SamplerPool.cs
@@ -0,0 +1,61 @@
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ class SamplerPool : Pool
+ {
+ public SamplerPool(GpuContext context, ulong address, int maximumId) : base(context, address, maximumId) { }
+
+ public override Sampler Get(int id)
+ {
+ if ((uint)id >= Items.Length)
+ {
+ return null;
+ }
+
+ SynchronizeMemory();
+
+ Sampler sampler = Items[id];
+
+ if (sampler == null)
+ {
+ ulong address = Address + (ulong)(uint)id * DescriptorSize;
+
+ Span data = Context.PhysicalMemory.Read(address, DescriptorSize);
+
+ SamplerDescriptor descriptor = MemoryMarshal.Cast(data)[0];
+
+ sampler = new Sampler(Context, descriptor);
+
+ Items[id] = sampler;
+ }
+
+ return sampler;
+ }
+
+ protected override void InvalidateRangeImpl(ulong address, ulong size)
+ {
+ ulong endAddress = address + size;
+
+ for (; address < endAddress; address += DescriptorSize)
+ {
+ int id = (int)((address - Address) / DescriptorSize);
+
+ Sampler sampler = Items[id];
+
+ if (sampler != null)
+ {
+ sampler.Dispose();
+
+ Items[id] = null;
+ }
+ }
+ }
+
+ protected override void Delete(Sampler item)
+ {
+ item?.Dispose();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/Texture.cs b/Ryujinx.Graphics.Gpu/Image/Texture.cs
new file mode 100644
index 000000000..32db86882
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/Texture.cs
@@ -0,0 +1,719 @@
+using Ryujinx.Common;
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.Gpu.Memory;
+using Ryujinx.Graphics.Texture;
+using Ryujinx.Graphics.Texture.Astc;
+using System;
+using System.Collections.Generic;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ class Texture : IRange
+ {
+ private GpuContext _context;
+
+ private TextureInfo _info;
+
+ private SizeInfo _sizeInfo;
+
+ public Format Format => _info.FormatInfo.Format;
+
+ public TextureInfo Info => _info;
+
+ private int _depth;
+ private int _layers;
+ private int _firstLayer;
+ private int _firstLevel;
+
+ private bool _hasData;
+
+ private ITexture _arrayViewTexture;
+ private Target _arrayViewTarget;
+
+ private Texture _viewStorage;
+
+ private List _views;
+
+ public ITexture HostTexture { get; private set; }
+
+ public LinkedListNode CacheNode { get; set; }
+
+ public bool Modified { get; set; }
+
+ public ulong Address => _info.Address;
+ public ulong EndAddress => _info.Address + Size;
+
+ public ulong Size => (ulong)_sizeInfo.TotalSize;
+
+ private int _referenceCount;
+
+ private int _sequenceNumber;
+
+ private Texture(
+ GpuContext context,
+ TextureInfo info,
+ SizeInfo sizeInfo,
+ int firstLayer,
+ int firstLevel)
+ {
+ InitializeTexture(context, info, sizeInfo);
+
+ _firstLayer = firstLayer;
+ _firstLevel = firstLevel;
+
+ _hasData = true;
+ }
+
+ public Texture(GpuContext context, TextureInfo info, SizeInfo sizeInfo)
+ {
+ InitializeTexture(context, info, sizeInfo);
+
+ TextureCreateInfo createInfo = TextureManager.GetCreateInfo(info, context.Capabilities);
+
+ HostTexture = _context.Renderer.CreateTexture(createInfo);
+ }
+
+ private void InitializeTexture(GpuContext context, TextureInfo info, SizeInfo sizeInfo)
+ {
+ _context = context;
+ _sizeInfo = sizeInfo;
+
+ SetInfo(info);
+
+ _viewStorage = this;
+
+ _views = new List();
+ }
+
+ public Texture CreateView(TextureInfo info, SizeInfo sizeInfo, int firstLayer, int firstLevel)
+ {
+ Texture texture = new Texture(
+ _context,
+ info,
+ sizeInfo,
+ _firstLayer + firstLayer,
+ _firstLevel + firstLevel);
+
+ TextureCreateInfo createInfo = TextureManager.GetCreateInfo(info, _context.Capabilities);
+
+ texture.HostTexture = HostTexture.CreateView(createInfo, firstLayer, firstLevel);
+
+ _viewStorage.AddView(texture);
+
+ return texture;
+ }
+
+ private void AddView(Texture texture)
+ {
+ _views.Add(texture);
+
+ texture._viewStorage = this;
+ }
+
+ private void RemoveView(Texture texture)
+ {
+ _views.Remove(texture);
+
+ texture._viewStorage = null;
+ }
+
+ public void ChangeSize(int width, int height, int depthOrLayers)
+ {
+ width <<= _firstLevel;
+ height <<= _firstLevel;
+
+ if (_info.Target == Target.Texture3D)
+ {
+ depthOrLayers <<= _firstLevel;
+ }
+ else
+ {
+ depthOrLayers = _viewStorage._info.DepthOrLayers;
+ }
+
+ _viewStorage.RecreateStorageOrView(width, height, depthOrLayers);
+
+ foreach (Texture view in _viewStorage._views)
+ {
+ int viewWidth = Math.Max(1, width >> view._firstLevel);
+ int viewHeight = Math.Max(1, height >> view._firstLevel);
+
+ int viewDepthOrLayers;
+
+ if (view._info.Target == Target.Texture3D)
+ {
+ viewDepthOrLayers = Math.Max(1, depthOrLayers >> view._firstLevel);
+ }
+ else
+ {
+ viewDepthOrLayers = view._info.DepthOrLayers;
+ }
+
+ view.RecreateStorageOrView(viewWidth, viewHeight, viewDepthOrLayers);
+ }
+ }
+
+ private void RecreateStorageOrView(int width, int height, int depthOrLayers)
+ {
+ SetInfo(new TextureInfo(
+ _info.Address,
+ width,
+ height,
+ depthOrLayers,
+ _info.Levels,
+ _info.SamplesInX,
+ _info.SamplesInY,
+ _info.Stride,
+ _info.IsLinear,
+ _info.GobBlocksInY,
+ _info.GobBlocksInZ,
+ _info.GobBlocksInTileX,
+ _info.Target,
+ _info.FormatInfo,
+ _info.DepthStencilMode,
+ _info.SwizzleR,
+ _info.SwizzleG,
+ _info.SwizzleB,
+ _info.SwizzleA));
+
+ TextureCreateInfo createInfo = TextureManager.GetCreateInfo(_info, _context.Capabilities);
+
+ if (_viewStorage != this)
+ {
+ ReplaceStorage(_viewStorage.HostTexture.CreateView(createInfo, _firstLayer, _firstLevel));
+ }
+ else
+ {
+ ITexture newStorage = _context.Renderer.CreateTexture(createInfo);
+
+ HostTexture.CopyTo(newStorage);
+
+ ReplaceStorage(newStorage);
+ }
+ }
+
+ public void SynchronizeMemory()
+ {
+ if (_sequenceNumber == _context.SequenceNumber && _hasData)
+ {
+ return;
+ }
+
+ _sequenceNumber = _context.SequenceNumber;
+
+ bool modified = _context.PhysicalMemory.GetModifiedRanges(Address, Size).Length != 0;
+
+ if (!modified && _hasData)
+ {
+ return;
+ }
+
+ ulong pageSize = (uint)_context.PhysicalMemory.GetPageSize();
+
+ ulong pageMask = pageSize - 1;
+
+ ulong rangeAddress = Address & ~pageMask;
+
+ ulong rangeSize = (EndAddress - Address + pageMask) & ~pageMask;
+
+ _context.Methods.InvalidateRange(rangeAddress, rangeSize);
+
+ Span data = _context.PhysicalMemory.Read(Address, Size);
+
+ if (_info.IsLinear)
+ {
+ data = LayoutConverter.ConvertLinearStridedToLinear(
+ _info.Width,
+ _info.Height,
+ _info.FormatInfo.BlockWidth,
+ _info.FormatInfo.BlockHeight,
+ _info.Stride,
+ _info.FormatInfo.BytesPerPixel,
+ data);
+ }
+ else
+ {
+ data = LayoutConverter.ConvertBlockLinearToLinear(
+ _info.Width,
+ _info.Height,
+ _depth,
+ _info.Levels,
+ _layers,
+ _info.FormatInfo.BlockWidth,
+ _info.FormatInfo.BlockHeight,
+ _info.FormatInfo.BytesPerPixel,
+ _info.GobBlocksInY,
+ _info.GobBlocksInZ,
+ _info.GobBlocksInTileX,
+ _sizeInfo,
+ data);
+ }
+
+ if (!_context.Capabilities.SupportsAstcCompression && _info.FormatInfo.Format.IsAstc())
+ {
+ int blockWidth = _info.FormatInfo.BlockWidth;
+ int blockHeight = _info.FormatInfo.BlockHeight;
+
+ data = AstcDecoder.DecodeToRgba8(
+ data,
+ blockWidth,
+ blockHeight,
+ 1,
+ _info.Width,
+ _info.Height,
+ _depth);
+ }
+
+ HostTexture.SetData(data);
+
+ _hasData = true;
+ }
+
+ public void Flush()
+ {
+ byte[] data = HostTexture.GetData(0);
+
+ _context.PhysicalMemory.Write(Address, data);
+ }
+
+ public bool IsPerfectMatch(TextureInfo info, TextureSearchFlags flags)
+ {
+ if (!FormatMatches(info, (flags & TextureSearchFlags.Strict) != 0))
+ {
+ return false;
+ }
+
+ if (!LayoutMatches(info))
+ {
+ return false;
+ }
+
+ if (!SizeMatches(info, (flags & TextureSearchFlags.Strict) == 0))
+ {
+ return false;
+ }
+
+ if ((flags & TextureSearchFlags.Sampler) != 0)
+ {
+ if (!SamplerParamsMatches(info))
+ {
+ return false;
+ }
+ }
+
+ if ((flags & TextureSearchFlags.IgnoreMs) != 0)
+ {
+ bool msTargetCompatible = _info.Target == Target.Texture2DMultisample &&
+ info.Target == Target.Texture2D;
+
+ if (!msTargetCompatible && !TargetAndSamplesCompatible(info))
+ {
+ return false;
+ }
+ }
+ else if (!TargetAndSamplesCompatible(info))
+ {
+ return false;
+ }
+
+ return _info.Address == info.Address && _info.Levels == info.Levels;
+ }
+
+ private bool FormatMatches(TextureInfo info, bool strict)
+ {
+ // D32F and R32F texture have the same representation internally,
+ // however the R32F format is used to sample from depth textures.
+ if (_info.FormatInfo.Format == Format.D32Float &&
+ info.FormatInfo.Format == Format.R32Float && !strict)
+ {
+ return true;
+ }
+
+ if (_info.FormatInfo.Format == Format.R8G8B8A8Srgb &&
+ info.FormatInfo.Format == Format.R8G8B8A8Unorm && !strict)
+ {
+ return true;
+ }
+
+ if (_info.FormatInfo.Format == Format.R8G8B8A8Unorm &&
+ info.FormatInfo.Format == Format.R8G8B8A8Srgb && !strict)
+ {
+ return true;
+ }
+
+ return _info.FormatInfo.Format == info.FormatInfo.Format;
+ }
+
+ private bool LayoutMatches(TextureInfo info)
+ {
+ if (_info.IsLinear != info.IsLinear)
+ {
+ return false;
+ }
+
+ // For linear textures, gob block sizes are ignored.
+ // For block linear textures, the stride is ignored.
+ if (info.IsLinear)
+ {
+ return _info.Stride == info.Stride;
+ }
+ else
+ {
+ return _info.GobBlocksInY == info.GobBlocksInY &&
+ _info.GobBlocksInZ == info.GobBlocksInZ;
+ }
+ }
+
+ public bool SizeMatches(TextureInfo info)
+ {
+ return SizeMatches(info, alignSizes: false);
+ }
+
+ public bool SizeMatches(TextureInfo info, int level)
+ {
+ return Math.Max(1, _info.Width >> level) == info.Width &&
+ Math.Max(1, _info.Height >> level) == info.Height &&
+ Math.Max(1, _info.GetDepth() >> level) == info.GetDepth();
+ }
+
+ private bool SizeMatches(TextureInfo info, bool alignSizes)
+ {
+ if (_info.GetLayers() != info.GetLayers())
+ {
+ return false;
+ }
+
+ if (alignSizes)
+ {
+ Size size0 = GetAlignedSize(_info);
+ Size size1 = GetAlignedSize(info);
+
+ return size0.Width == size1.Width &&
+ size0.Height == size1.Height &&
+ size0.Depth == size1.Depth;
+ }
+ else
+ {
+ return _info.Width == info.Width &&
+ _info.Height == info.Height &&
+ _info.GetDepth() == info.GetDepth();
+ }
+ }
+
+ private bool SamplerParamsMatches(TextureInfo info)
+ {
+ return _info.DepthStencilMode == info.DepthStencilMode &&
+ _info.SwizzleR == info.SwizzleR &&
+ _info.SwizzleG == info.SwizzleG &&
+ _info.SwizzleB == info.SwizzleB &&
+ _info.SwizzleA == info.SwizzleA;
+ }
+
+ private bool TargetAndSamplesCompatible(TextureInfo info)
+ {
+ return _info.Target == info.Target &&
+ _info.SamplesInX == info.SamplesInX &&
+ _info.SamplesInY == info.SamplesInY;
+ }
+
+ public bool IsViewCompatible(TextureInfo info, ulong size, out int firstLayer, out int firstLevel)
+ {
+ // Out of range.
+ if (info.Address < Address || info.Address + size > EndAddress)
+ {
+ firstLayer = 0;
+ firstLevel = 0;
+
+ return false;
+ }
+
+ int offset = (int)(info.Address - Address);
+
+ if (!_sizeInfo.FindView(offset, (int)size, out firstLayer, out firstLevel))
+ {
+ return false;
+ }
+
+ if (!ViewLayoutCompatible(info, firstLevel))
+ {
+ return false;
+ }
+
+ if (!ViewFormatCompatible(info))
+ {
+ return false;
+ }
+
+ if (!ViewSizeMatches(info, firstLevel))
+ {
+ return false;
+ }
+
+ if (!ViewTargetCompatible(info))
+ {
+ return false;
+ }
+
+ return _info.SamplesInX == info.SamplesInX &&
+ _info.SamplesInY == info.SamplesInY;
+ }
+
+ private bool ViewLayoutCompatible(TextureInfo info, int level)
+ {
+ if (_info.IsLinear != info.IsLinear)
+ {
+ return false;
+ }
+
+ // For linear textures, gob block sizes are ignored.
+ // For block linear textures, the stride is ignored.
+ if (info.IsLinear)
+ {
+ int width = Math.Max(1, _info.Width >> level);
+
+ int stride = width * _info.FormatInfo.BytesPerPixel;
+
+ stride = BitUtils.AlignUp(stride, 32);
+
+ return stride == info.Stride;
+ }
+ else
+ {
+ int height = Math.Max(1, _info.Height >> level);
+ int depth = Math.Max(1, _info.GetDepth() >> level);
+
+ (int gobBlocksInY, int gobBlocksInZ) = SizeCalculator.GetMipGobBlockSizes(
+ height,
+ depth,
+ _info.FormatInfo.BlockHeight,
+ _info.GobBlocksInY,
+ _info.GobBlocksInZ);
+
+ return gobBlocksInY == info.GobBlocksInY &&
+ gobBlocksInZ == info.GobBlocksInZ;
+ }
+ }
+
+ private bool ViewFormatCompatible(TextureInfo info)
+ {
+ return TextureCompatibility.FormatCompatible(_info.FormatInfo, info.FormatInfo);
+ }
+
+ private bool ViewSizeMatches(TextureInfo info, int level)
+ {
+ Size size = GetAlignedSize(_info, level);
+
+ Size otherSize = GetAlignedSize(info);
+
+ return size.Width == otherSize.Width &&
+ size.Height == otherSize.Height &&
+ size.Depth == otherSize.Depth;
+ }
+
+ private bool ViewTargetCompatible(TextureInfo info)
+ {
+ switch (_info.Target)
+ {
+ case Target.Texture1D:
+ case Target.Texture1DArray:
+ return info.Target == Target.Texture1D ||
+ info.Target == Target.Texture1DArray;
+
+ case Target.Texture2D:
+ return info.Target == Target.Texture2D ||
+ info.Target == Target.Texture2DArray;
+
+ case Target.Texture2DArray:
+ case Target.Cubemap:
+ case Target.CubemapArray:
+ return info.Target == Target.Texture2D ||
+ info.Target == Target.Texture2DArray ||
+ info.Target == Target.Cubemap ||
+ info.Target == Target.CubemapArray;
+
+ case Target.Texture2DMultisample:
+ case Target.Texture2DMultisampleArray:
+ return info.Target == Target.Texture2DMultisample ||
+ info.Target == Target.Texture2DMultisampleArray;
+
+ case Target.Texture3D:
+ return info.Target == Target.Texture3D;
+ }
+
+ return false;
+ }
+
+ private static Size GetAlignedSize(TextureInfo info, int level = 0)
+ {
+ int width = Math.Max(1, info.Width >> level);
+ int height = Math.Max(1, info.Height >> level);
+
+ if (info.IsLinear)
+ {
+ return SizeCalculator.GetLinearAlignedSize(
+ width,
+ height,
+ info.FormatInfo.BlockWidth,
+ info.FormatInfo.BlockHeight,
+ info.FormatInfo.BytesPerPixel);
+ }
+ else
+ {
+ int depth = Math.Max(1, info.GetDepth() >> level);
+
+ (int gobBlocksInY, int gobBlocksInZ) = SizeCalculator.GetMipGobBlockSizes(
+ height,
+ depth,
+ info.FormatInfo.BlockHeight,
+ info.GobBlocksInY,
+ info.GobBlocksInZ);
+
+ return SizeCalculator.GetBlockLinearAlignedSize(
+ width,
+ height,
+ depth,
+ info.FormatInfo.BlockWidth,
+ info.FormatInfo.BlockHeight,
+ info.FormatInfo.BytesPerPixel,
+ gobBlocksInY,
+ gobBlocksInZ,
+ info.GobBlocksInTileX);
+ }
+ }
+
+ public ITexture GetTargetTexture(Target target)
+ {
+ if (target == _info.Target)
+ {
+ return HostTexture;
+ }
+
+ if (_arrayViewTexture == null && IsSameDimensionsTarget(target))
+ {
+ TextureCreateInfo createInfo = new TextureCreateInfo(
+ _info.Width,
+ _info.Height,
+ target == Target.CubemapArray ? 6 : 1,
+ _info.Levels,
+ _info.Samples,
+ _info.FormatInfo.BlockWidth,
+ _info.FormatInfo.BlockHeight,
+ _info.FormatInfo.BytesPerPixel,
+ _info.FormatInfo.Format,
+ _info.DepthStencilMode,
+ target,
+ _info.SwizzleR,
+ _info.SwizzleG,
+ _info.SwizzleB,
+ _info.SwizzleA);
+
+ ITexture viewTexture = HostTexture.CreateView(createInfo, 0, 0);
+
+ _arrayViewTexture = viewTexture;
+ _arrayViewTarget = target;
+
+ return viewTexture;
+ }
+ else if (_arrayViewTarget == target)
+ {
+ return _arrayViewTexture;
+ }
+
+ return null;
+ }
+
+ private bool IsSameDimensionsTarget(Target target)
+ {
+ switch (_info.Target)
+ {
+ case Target.Texture1D:
+ case Target.Texture1DArray:
+ return target == Target.Texture1D ||
+ target == Target.Texture1DArray;
+
+ case Target.Texture2D:
+ case Target.Texture2DArray:
+ return target == Target.Texture2D ||
+ target == Target.Texture2DArray;
+
+ case Target.Cubemap:
+ case Target.CubemapArray:
+ return target == Target.Cubemap ||
+ target == Target.CubemapArray;
+
+ case Target.Texture2DMultisample:
+ case Target.Texture2DMultisampleArray:
+ return target == Target.Texture2DMultisample ||
+ target == Target.Texture2DMultisampleArray;
+
+ case Target.Texture3D:
+ return target == Target.Texture3D;
+ }
+
+ return false;
+ }
+
+ public void ReplaceView(Texture parent, TextureInfo info, ITexture hostTexture)
+ {
+ ReplaceStorage(hostTexture);
+
+ parent._viewStorage.AddView(this);
+
+ SetInfo(info);
+ }
+
+ private void SetInfo(TextureInfo info)
+ {
+ _info = info;
+
+ _depth = info.GetDepth();
+ _layers = info.GetLayers();
+ }
+
+ private void ReplaceStorage(ITexture hostTexture)
+ {
+ DisposeTextures();
+
+ HostTexture = hostTexture;
+ }
+
+ public bool OverlapsWith(ulong address, ulong size)
+ {
+ return Address < address + size && address < EndAddress;
+ }
+
+ public void Invalidate()
+ {
+ // _hasData = false;
+ }
+
+ public void IncrementReferenceCount()
+ {
+ _referenceCount++;
+ }
+
+ public void DecrementReferenceCount()
+ {
+ if (--_referenceCount == 0)
+ {
+ if (_viewStorage != this)
+ {
+ _viewStorage.RemoveView(this);
+ }
+
+ _context.Methods.TextureManager.RemoveTextureFromCache(this);
+
+ DisposeTextures();
+ }
+ }
+
+ private void DisposeTextures()
+ {
+ HostTexture.Dispose();
+
+ _arrayViewTexture?.Dispose();
+ _arrayViewTexture = null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureBindingInfo.cs b/Ryujinx.Graphics.Gpu/Image/TextureBindingInfo.cs
new file mode 100644
index 000000000..19090ab33
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureBindingInfo.cs
@@ -0,0 +1,17 @@
+using Ryujinx.Graphics.GAL.Texture;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ struct TextureBindingInfo
+ {
+ public Target Target { get; }
+
+ public int Handle { get; }
+
+ public TextureBindingInfo(Target target, int handle)
+ {
+ Target = target;
+ Handle = handle;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureCompatibility.cs b/Ryujinx.Graphics.Gpu/Image/TextureCompatibility.cs
new file mode 100644
index 000000000..524721647
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureCompatibility.cs
@@ -0,0 +1,95 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ static class TextureCompatibility
+ {
+ private enum FormatClass
+ {
+ Unclassified,
+ BCn64,
+ BCn128,
+ Bc1Rgb,
+ Bc1Rgba,
+ Bc2,
+ Bc3,
+ Bc4,
+ Bc5,
+ Bc6,
+ Bc7
+ }
+
+ public static bool FormatCompatible(FormatInfo lhs, FormatInfo rhs)
+ {
+ if (IsDsFormat(lhs.Format) || IsDsFormat(rhs.Format))
+ {
+ return lhs.Format == rhs.Format;
+ }
+
+ if (lhs.Format.IsAstc() || rhs.Format.IsAstc())
+ {
+ return lhs.Format == rhs.Format;
+ }
+
+ if (lhs.IsCompressed && rhs.IsCompressed)
+ {
+ FormatClass lhsClass = GetFormatClass(lhs.Format);
+ FormatClass rhsClass = GetFormatClass(rhs.Format);
+
+ return lhsClass == rhsClass;
+ }
+ else
+ {
+ return lhs.BytesPerPixel == rhs.BytesPerPixel;
+ }
+ }
+
+ private static FormatClass GetFormatClass(Format format)
+ {
+ switch (format)
+ {
+ case Format.Bc1RgbSrgb:
+ case Format.Bc1RgbUnorm:
+ return FormatClass.Bc1Rgb;
+ case Format.Bc1RgbaSrgb:
+ case Format.Bc1RgbaUnorm:
+ return FormatClass.Bc1Rgba;
+ case Format.Bc2Srgb:
+ case Format.Bc2Unorm:
+ return FormatClass.Bc2;
+ case Format.Bc3Srgb:
+ case Format.Bc3Unorm:
+ return FormatClass.Bc3;
+ case Format.Bc4Snorm:
+ case Format.Bc4Unorm:
+ return FormatClass.Bc4;
+ case Format.Bc5Snorm:
+ case Format.Bc5Unorm:
+ return FormatClass.Bc5;
+ case Format.Bc6HSfloat:
+ case Format.Bc6HUfloat:
+ return FormatClass.Bc6;
+ case Format.Bc7Srgb:
+ case Format.Bc7Unorm:
+ return FormatClass.Bc7;
+ }
+
+ return FormatClass.Unclassified;
+ }
+
+ private static bool IsDsFormat(Format format)
+ {
+ switch (format)
+ {
+ case Format.D16Unorm:
+ case Format.D24X8Unorm:
+ case Format.D24UnormS8Uint:
+ case Format.D32Float:
+ case Format.D32FloatS8Uint:
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureComponent.cs b/Ryujinx.Graphics.Gpu/Image/TextureComponent.cs
new file mode 100644
index 000000000..37b3f65e2
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureComponent.cs
@@ -0,0 +1,35 @@
+using Ryujinx.Graphics.GAL.Texture;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ enum TextureComponent
+ {
+ Zero = 0,
+ Red = 2,
+ Green = 3,
+ Blue = 4,
+ Alpha = 5,
+ OneSI = 6,
+ OneF = 7
+ }
+
+ static class TextureComponentConverter
+ {
+ public static SwizzleComponent Convert(this TextureComponent component)
+ {
+ switch (component)
+ {
+ case TextureComponent.Zero: return SwizzleComponent.Zero;
+ case TextureComponent.Red: return SwizzleComponent.Red;
+ case TextureComponent.Green: return SwizzleComponent.Green;
+ case TextureComponent.Blue: return SwizzleComponent.Blue;
+ case TextureComponent.Alpha: return SwizzleComponent.Alpha;
+ case TextureComponent.OneSI:
+ case TextureComponent.OneF:
+ return SwizzleComponent.One;
+ }
+
+ return SwizzleComponent.Zero;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureDescriptor.cs b/Ryujinx.Graphics.Gpu/Image/TextureDescriptor.cs
new file mode 100644
index 000000000..79e4f55ea
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureDescriptor.cs
@@ -0,0 +1,119 @@
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ struct TextureDescriptor
+ {
+ public uint Word0;
+ public uint Word1;
+ public uint Word2;
+ public uint Word3;
+ public uint Word4;
+ public uint Word5;
+ public uint Word6;
+ public uint Word7;
+
+ public uint UnpackFormat()
+ {
+ return Word0 & 0x8007ffff;
+ }
+
+ public TextureComponent UnpackSwizzleR()
+ {
+ return(TextureComponent)((Word0 >> 19) & 7);
+ }
+
+ public TextureComponent UnpackSwizzleG()
+ {
+ return(TextureComponent)((Word0 >> 22) & 7);
+ }
+
+ public TextureComponent UnpackSwizzleB()
+ {
+ return(TextureComponent)((Word0 >> 25) & 7);
+ }
+
+ public TextureComponent UnpackSwizzleA()
+ {
+ return(TextureComponent)((Word0 >> 28) & 7);
+ }
+
+ public ulong UnpackAddress()
+ {
+ return Word1 | ((ulong)(Word2 & 0xffff) << 32);
+ }
+
+ public TextureDescriptorType UnpackTextureDescriptorType()
+ {
+ return (TextureDescriptorType)((Word2 >> 21) & 7);
+ }
+
+ public int UnpackStride()
+ {
+ return (int)(Word3 & 0xffff) << 5;
+ }
+
+ public int UnpackGobBlocksInX()
+ {
+ return 1 << (int)(Word3 & 7);
+ }
+
+ public int UnpackGobBlocksInY()
+ {
+ return 1 << (int)((Word3 >> 3) & 7);
+ }
+
+ public int UnpackGobBlocksInZ()
+ {
+ return 1 << (int)((Word3 >> 6) & 7);
+ }
+
+ public int UnpackGobBlocksInTileX()
+ {
+ return 1 << (int)((Word3 >> 10) & 7);
+ }
+
+ public int UnpackLevels()
+ {
+ return (int)(Word3 >> 28) + 1;
+ }
+
+ public int UnpackWidth()
+ {
+ return (int)(Word4 & 0xffff) + 1;
+ }
+
+ public bool UnpackSrgb()
+ {
+ return (Word4 & (1 << 22)) != 0;
+ }
+
+ public TextureTarget UnpackTextureTarget()
+ {
+ return (TextureTarget)((Word4 >> 23) & 0xf);
+ }
+
+ public int UnpackHeight()
+ {
+ return (int)(Word5 & 0xffff) + 1;
+ }
+
+ public int UnpackDepth()
+ {
+ return (int)((Word5 >> 16) & 0x3fff) + 1;
+ }
+
+ public int UnpackBaseLevel()
+ {
+ return (int)(Word7 & 0xf);
+ }
+
+ public int UnpackMaxLevelInclusive()
+ {
+ return (int)((Word7 >> 4) & 0xf);
+ }
+
+ public TextureMsaaMode UnpackTextureMsaaMode()
+ {
+ return (TextureMsaaMode)((Word7 >> 8) & 0xf);
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureDescriptorType.cs b/Ryujinx.Graphics.Gpu/Image/TextureDescriptorType.cs
new file mode 100644
index 000000000..6f6048a61
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureDescriptorType.cs
@@ -0,0 +1,11 @@
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ enum TextureDescriptorType
+ {
+ Buffer,
+ LinearColorKey,
+ Linear,
+ BlockLinear,
+ BlockLinearColorKey
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureInfo.cs b/Ryujinx.Graphics.Gpu/Image/TextureInfo.cs
new file mode 100644
index 000000000..639abdd84
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureInfo.cs
@@ -0,0 +1,101 @@
+using Ryujinx.Graphics.GAL.Texture;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ struct TextureInfo
+ {
+ public ulong Address { get; }
+
+ public int Width { get; }
+ public int Height { get; }
+ public int DepthOrLayers { get; }
+ public int Levels { get; }
+ public int SamplesInX { get; }
+ public int SamplesInY { get; }
+ public int Stride { get; }
+ public bool IsLinear { get; }
+ public int GobBlocksInY { get; }
+ public int GobBlocksInZ { get; }
+ public int GobBlocksInTileX { get; }
+
+ public int Samples => SamplesInX * SamplesInY;
+
+ public Target Target { get; }
+
+ public FormatInfo FormatInfo { get; }
+
+ public DepthStencilMode DepthStencilMode { get; }
+
+ public SwizzleComponent SwizzleR { get; }
+ public SwizzleComponent SwizzleG { get; }
+ public SwizzleComponent SwizzleB { get; }
+ public SwizzleComponent SwizzleA { get; }
+
+ public TextureInfo(
+ ulong address,
+ int width,
+ int height,
+ int depthOrLayers,
+ int levels,
+ int samplesInX,
+ int samplesInY,
+ int stride,
+ bool isLinear,
+ int gobBlocksInY,
+ int gobBlocksInZ,
+ int gobBlocksInTileX,
+ Target target,
+ FormatInfo formatInfo,
+ DepthStencilMode depthStencilMode = DepthStencilMode.Depth,
+ SwizzleComponent swizzleR = SwizzleComponent.Red,
+ SwizzleComponent swizzleG = SwizzleComponent.Green,
+ SwizzleComponent swizzleB = SwizzleComponent.Blue,
+ SwizzleComponent swizzleA = SwizzleComponent.Alpha)
+ {
+ Address = address;
+ Width = width;
+ Height = height;
+ DepthOrLayers = depthOrLayers;
+ Levels = levels;
+ SamplesInX = samplesInX;
+ SamplesInY = samplesInY;
+ Stride = stride;
+ IsLinear = isLinear;
+ GobBlocksInY = gobBlocksInY;
+ GobBlocksInZ = gobBlocksInZ;
+ GobBlocksInTileX = gobBlocksInTileX;
+ Target = target;
+ FormatInfo = formatInfo;
+ DepthStencilMode = depthStencilMode;
+ SwizzleR = swizzleR;
+ SwizzleG = swizzleG;
+ SwizzleB = swizzleB;
+ SwizzleA = swizzleA;
+ }
+
+ public int GetDepth()
+ {
+ return Target == Target.Texture3D ? DepthOrLayers : 1;
+ }
+
+ public int GetLayers()
+ {
+ if (Target == Target.Texture2DArray || Target == Target.Texture2DMultisampleArray)
+ {
+ return DepthOrLayers;
+ }
+ else if (Target == Target.CubemapArray)
+ {
+ return DepthOrLayers * 6;
+ }
+ else if (Target == Target.Cubemap)
+ {
+ return 6;
+ }
+ else
+ {
+ return 1;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureManager.cs b/Ryujinx.Graphics.Gpu/Image/TextureManager.cs
new file mode 100644
index 000000000..56dff9ad6
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureManager.cs
@@ -0,0 +1,669 @@
+using Ryujinx.Common;
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.Gpu.Image;
+using Ryujinx.Graphics.Gpu.Memory;
+using Ryujinx.Graphics.Gpu.State;
+using Ryujinx.Graphics.Shader;
+using Ryujinx.Graphics.Texture;
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ class TextureManager
+ {
+ private GpuContext _context;
+ private BufferManager _bufferManager;
+
+ private SamplerPool _samplerPool;
+
+ private ulong _texturePoolAddress;
+ private int _texturePoolMaximumId;
+
+ private TexturePoolCache _texturePoolCache;
+
+ private Texture[] _rtColors;
+ private Texture _rtColor3D;
+
+ private Texture _rtDepthStencil;
+
+ private ITexture[] _rtHostColors;
+
+ private ITexture _rtHostDs;
+
+ private RangeList _textures;
+
+ private AutoDeleteCache _cache;
+
+ private TextureBindingInfo[][] _bindings;
+
+ private struct TextureStatePerStage
+ {
+ public ITexture Texture;
+ public ISampler Sampler;
+ }
+
+ private TextureStatePerStage[][] _textureState;
+
+ private int _textureBufferIndex;
+
+ public TextureManager(GpuContext context, BufferManager bufferManager)
+ {
+ _context = context;
+ _bufferManager = bufferManager;
+
+ _texturePoolCache = new TexturePoolCache(context, this);
+
+ _rtColors = new Texture[Constants.TotalRenderTargets];
+
+ _rtHostColors = new ITexture[Constants.TotalRenderTargets];
+
+ _textures = new RangeList();
+
+ _cache = new AutoDeleteCache();
+
+ _bindings = new TextureBindingInfo[Constants.TotalShaderStages][];
+
+ _textureState = new TextureStatePerStage[Constants.TotalShaderStages][];
+ }
+
+ public void BindTextures(int stage, TextureBindingInfo[] bindings)
+ {
+ _bindings[stage] = bindings;
+
+ _textureState[stage] = new TextureStatePerStage[bindings.Length];
+ }
+
+ public void SetTextureBufferIndex(int index)
+ {
+ _textureBufferIndex = index;
+ }
+
+ public void SetSamplerPool(ulong gpuVa, int maximumId)
+ {
+ ulong address = _context.MemoryManager.Translate(gpuVa);
+
+ if (_samplerPool != null)
+ {
+ if (_samplerPool.Address == address)
+ {
+ return;
+ }
+
+ _samplerPool.Dispose();
+ }
+
+ _samplerPool = new SamplerPool(_context, address, maximumId);
+ }
+
+ public void SetTexturePool(ulong gpuVa, int maximumId)
+ {
+ ulong address = _context.MemoryManager.Translate(gpuVa);
+
+ _texturePoolAddress = address;
+ _texturePoolMaximumId = maximumId;
+ }
+
+ public void SetRenderTargetColor(int index, Texture color)
+ {
+ _rtColors[index] = color;
+
+ _rtColor3D = null;
+ }
+
+ public void SetRenderTargetColor3D(Texture color)
+ {
+ _rtColor3D = color;
+ }
+
+ public void SetRenderTargetDepthStencil(Texture depthStencil)
+ {
+ _rtDepthStencil = depthStencil;
+ }
+
+ public void CommitBindings()
+ {
+ UpdateTextures();
+ UpdateRenderTargets();
+ }
+
+ private void UpdateTextures()
+ {
+ TexturePool texturePool = _texturePoolCache.FindOrCreate(
+ _texturePoolAddress,
+ _texturePoolMaximumId);
+
+ for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
+ {
+ int stageIndex = (int)stage - 1;
+
+ if (_bindings[stageIndex] == null)
+ {
+ continue;
+ }
+
+ for (int index = 0; index < _bindings[stageIndex].Length; index++)
+ {
+ TextureBindingInfo binding = _bindings[stageIndex][index];
+
+ int packedId = ReadPackedId(stageIndex, binding.Handle);
+
+ int textureId = (packedId >> 0) & 0xfffff;
+ int samplerId = (packedId >> 20) & 0xfff;
+
+ Texture texture = texturePool.Get(textureId);
+
+ ITexture hostTexture = texture?.GetTargetTexture(binding.Target);
+
+ if (_textureState[stageIndex][index].Texture != hostTexture)
+ {
+ _textureState[stageIndex][index].Texture = hostTexture;
+
+ _context.Renderer.GraphicsPipeline.BindTexture(index, stage, hostTexture);
+ }
+
+ Sampler sampler = _samplerPool.Get(samplerId);
+
+ ISampler hostSampler = sampler?.HostSampler;
+
+ if (_textureState[stageIndex][index].Sampler != hostSampler)
+ {
+ _textureState[stageIndex][index].Sampler = hostSampler;
+
+ _context.Renderer.GraphicsPipeline.BindSampler(index, stage, hostSampler);
+ }
+ }
+ }
+ }
+
+ private void UpdateRenderTargets()
+ {
+ bool anyChanged = false;
+
+ if (_rtHostDs != _rtDepthStencil?.HostTexture)
+ {
+ _rtHostDs = _rtDepthStencil?.HostTexture;
+
+ anyChanged = true;
+ }
+
+ if (_rtColor3D == null)
+ {
+ for (int index = 0; index < _rtColors.Length; index++)
+ {
+ ITexture hostTexture = _rtColors[index]?.HostTexture;
+
+ if (_rtHostColors[index] != hostTexture)
+ {
+ _rtHostColors[index] = hostTexture;
+
+ anyChanged = true;
+ }
+ }
+
+ if (anyChanged)
+ {
+ _context.Renderer.GraphicsPipeline.SetRenderTargets(_rtHostColors, _rtHostDs);
+ }
+ }
+ else
+ {
+ if (_rtHostColors[0] != _rtColor3D.HostTexture)
+ {
+ _rtHostColors[0] = _rtColor3D.HostTexture;
+
+ anyChanged = true;
+ }
+
+ if (anyChanged)
+ {
+ _context.Renderer.GraphicsPipeline.SetRenderTargets(_rtColor3D.HostTexture, _rtHostDs);
+ }
+ }
+ }
+
+ private int ReadPackedId(int stage, int wordOffset)
+ {
+ ulong address = _bufferManager.GetGraphicsUniformBufferAddress(stage, _textureBufferIndex);
+
+ address += (uint)wordOffset * 4;
+
+ return BitConverter.ToInt32(_context.PhysicalMemory.Read(address, 4));
+ }
+
+ public Texture FindOrCreateTexture(CopyTexture copyTexture)
+ {
+ ulong address = _context.MemoryManager.Translate(copyTexture.Address.Pack());
+
+ if (address == MemoryManager.BadAddress)
+ {
+ return null;
+ }
+
+ int gobBlocksInY = copyTexture.MemoryLayout.UnpackGobBlocksInY();
+ int gobBlocksInZ = copyTexture.MemoryLayout.UnpackGobBlocksInZ();
+
+ FormatInfo formatInfo = copyTexture.Format.Convert();
+
+ TextureInfo info = new TextureInfo(
+ address,
+ copyTexture.Width,
+ copyTexture.Height,
+ copyTexture.Depth,
+ 1,
+ 1,
+ 1,
+ copyTexture.Stride,
+ copyTexture.LinearLayout,
+ gobBlocksInY,
+ gobBlocksInZ,
+ 1,
+ Target.Texture2D,
+ formatInfo);
+
+ Texture texture = FindOrCreateTexture(info, TextureSearchFlags.IgnoreMs);
+
+ texture.SynchronizeMemory();
+
+ return texture;
+ }
+
+ public Texture FindOrCreateTexture(RtColorState colorState, int samplesInX, int samplesInY)
+ {
+ ulong address = _context.MemoryManager.Translate(colorState.Address.Pack());
+
+ if (address == MemoryManager.BadAddress)
+ {
+ return null;
+ }
+
+ bool isLinear = colorState.MemoryLayout.UnpackIsLinear();
+
+ int gobBlocksInY = colorState.MemoryLayout.UnpackGobBlocksInY();
+ int gobBlocksInZ = colorState.MemoryLayout.UnpackGobBlocksInZ();
+
+ Target target;
+
+ if (colorState.MemoryLayout.UnpackIsTarget3D())
+ {
+ target = Target.Texture3D;
+ }
+ else if ((samplesInX | samplesInY) != 1)
+ {
+ target = colorState.Depth > 1
+ ? Target.Texture2DMultisampleArray
+ : Target.Texture2DMultisample;
+ }
+ else
+ {
+ target = colorState.Depth > 1
+ ? Target.Texture2DArray
+ : Target.Texture2D;
+ }
+
+ FormatInfo formatInfo = colorState.Format.Convert();
+
+ int width, stride;
+
+ // For linear textures, the width value is actually the stride.
+ // We can easily get the width by dividing the stride by the bpp,
+ // since the stride is the total number of bytes occupied by a
+ // line. The stride should also meet alignment constraints however,
+ // so the width we get here is the aligned width.
+ if (isLinear)
+ {
+ width = colorState.WidthOrStride / formatInfo.BytesPerPixel;
+ stride = colorState.WidthOrStride;
+ }
+ else
+ {
+ width = colorState.WidthOrStride;
+ stride = 0;
+ }
+
+ TextureInfo info = new TextureInfo(
+ address,
+ width,
+ colorState.Height,
+ colorState.Depth,
+ 1,
+ samplesInX,
+ samplesInY,
+ stride,
+ isLinear,
+ gobBlocksInY,
+ gobBlocksInZ,
+ 1,
+ target,
+ formatInfo);
+
+ Texture texture = FindOrCreateTexture(info);
+
+ texture.SynchronizeMemory();
+
+ return texture;
+ }
+
+ public Texture FindOrCreateTexture(RtDepthStencilState dsState, Size3D size, int samplesInX, int samplesInY)
+ {
+ ulong address = _context.MemoryManager.Translate(dsState.Address.Pack());
+
+ if (address == MemoryManager.BadAddress)
+ {
+ return null;
+ }
+
+ int gobBlocksInY = dsState.MemoryLayout.UnpackGobBlocksInY();
+ int gobBlocksInZ = dsState.MemoryLayout.UnpackGobBlocksInZ();
+
+ Target target = (samplesInX | samplesInY) != 1
+ ? Target.Texture2DMultisample
+ : Target.Texture2D;
+
+ FormatInfo formatInfo = dsState.Format.Convert();
+
+ TextureInfo info = new TextureInfo(
+ address,
+ size.Width,
+ size.Height,
+ size.Depth,
+ 1,
+ samplesInX,
+ samplesInY,
+ 0,
+ false,
+ gobBlocksInY,
+ gobBlocksInZ,
+ 1,
+ target,
+ formatInfo);
+
+ Texture texture = FindOrCreateTexture(info);
+
+ texture.SynchronizeMemory();
+
+ return texture;
+ }
+
+ public Texture FindOrCreateTexture(TextureInfo info, TextureSearchFlags flags = TextureSearchFlags.None)
+ {
+ bool isSamplerTexture = (flags & TextureSearchFlags.Sampler) != 0;
+
+ // Try to find a perfect texture match, with the same address and parameters.
+ Texture[] sameAddressOverlaps = _textures.FindOverlaps(info.Address);
+
+ foreach (Texture overlap in sameAddressOverlaps)
+ {
+ if (overlap.IsPerfectMatch(info, flags))
+ {
+ if (!isSamplerTexture)
+ {
+ // If not a sampler texture, it is managed by the auto delete
+ // cache, ensure that it is on the "top" of the list to avoid
+ // deletion.
+ _cache.Lift(overlap);
+ }
+ else if (!overlap.SizeMatches(info))
+ {
+ // If this is used for sampling, the size must match,
+ // otherwise the shader would sample garbage data.
+ // To fix that, we create a new texture with the correct
+ // size, and copy the data from the old one to the new one.
+ overlap.ChangeSize(info.Width, info.Height, info.DepthOrLayers);
+ }
+
+ return overlap;
+ }
+ }
+
+ // Calculate texture sizes, used to find all overlapping textures.
+ SizeInfo sizeInfo;
+
+ if (info.IsLinear)
+ {
+ sizeInfo = SizeCalculator.GetLinearTextureSize(
+ info.Stride,
+ info.Height,
+ info.FormatInfo.BlockHeight);
+ }
+ else
+ {
+ sizeInfo = SizeCalculator.GetBlockLinearTextureSize(
+ info.Width,
+ info.Height,
+ info.GetDepth(),
+ info.Levels,
+ info.GetLayers(),
+ info.FormatInfo.BlockWidth,
+ info.FormatInfo.BlockHeight,
+ info.FormatInfo.BytesPerPixel,
+ info.GobBlocksInY,
+ info.GobBlocksInZ,
+ info.GobBlocksInTileX);
+ }
+
+ // Find view compatible matches.
+ ulong size = (ulong)sizeInfo.TotalSize;
+
+ Texture[] overlaps = _textures.FindOverlaps(info.Address, size);
+
+ Texture texture = null;
+
+ foreach (Texture overlap in overlaps)
+ {
+ if (overlap.IsViewCompatible(info, size, out int firstLayer, out int firstLevel))
+ {
+ if (!isSamplerTexture)
+ {
+ info = AdjustSizes(overlap, info, firstLevel);
+ }
+
+ texture = overlap.CreateView(info, sizeInfo, firstLayer, firstLevel);
+
+ // The size only matters (and is only really reliable) when the
+ // texture is used on a sampler, because otherwise the size will be
+ // aligned.
+ if (!overlap.SizeMatches(info, firstLevel) && isSamplerTexture)
+ {
+ texture.ChangeSize(info.Width, info.Height, info.DepthOrLayers);
+ }
+
+ break;
+ }
+ }
+
+ // No match, create a new texture.
+ if (texture == null)
+ {
+ texture = new Texture(_context, info, sizeInfo);
+
+ // We need to synchronize before copying the old view data to the texture,
+ // otherwise the copied data would be overwritten by a future synchronization.
+ texture.SynchronizeMemory();
+
+ foreach (Texture overlap in overlaps)
+ {
+ if (texture.IsViewCompatible(overlap.Info, overlap.Size, out int firstLayer, out int firstLevel))
+ {
+ TextureInfo overlapInfo = AdjustSizes(texture, overlap.Info, firstLevel);
+
+ TextureCreateInfo createInfo = GetCreateInfo(overlapInfo, _context.Capabilities);
+
+ ITexture newView = texture.HostTexture.CreateView(createInfo, firstLayer, firstLevel);
+
+ overlap.HostTexture.CopyTo(newView);
+
+ overlap.ReplaceView(texture, overlapInfo, newView);
+ }
+ }
+ }
+
+ // Sampler textures are managed by the texture pool, all other textures
+ // are managed by the auto delete cache.
+ if (!isSamplerTexture)
+ {
+ _cache.Add(texture);
+ }
+
+ _textures.Add(texture);
+
+ return texture;
+ }
+
+ private static TextureInfo AdjustSizes(Texture parent, TextureInfo info, int firstLevel)
+ {
+ // When the texture is used as view of another texture, we must
+ // ensure that the sizes are valid, otherwise data uploads would fail
+ // (and the size wouldn't match the real size used on the host API).
+ // Given a parent texture from where the view is created, we have the
+ // following rules:
+ // - The view size must be equal to the parent size, divided by (2 ^ l),
+ // where l is the first mipmap level of the view. The division result must
+ // be rounded down, and the result must be clamped to 1.
+ // - If the parent format is compressed, and the view format isn't, the
+ // view size is calculated as above, but the width and height of the
+ // view must be also divided by the compressed format block width and height.
+ // - If the parent format is not compressed, and the view is, the view
+ // size is calculated as described on the first point, but the width and height
+ // of the view must be also multiplied by the block width and height.
+ int width = Math.Max(1, parent.Info.Width >> firstLevel);
+ int height = Math.Max(1, parent.Info.Height >> firstLevel);
+
+ if (parent.Info.FormatInfo.IsCompressed && !info.FormatInfo.IsCompressed)
+ {
+ width = BitUtils.DivRoundUp(width, parent.Info.FormatInfo.BlockWidth);
+ height = BitUtils.DivRoundUp(height, parent.Info.FormatInfo.BlockHeight);
+ }
+ else if (!parent.Info.FormatInfo.IsCompressed && info.FormatInfo.IsCompressed)
+ {
+ width *= info.FormatInfo.BlockWidth;
+ height *= info.FormatInfo.BlockHeight;
+ }
+
+ int depthOrLayers;
+
+ if (info.Target == Target.Texture3D)
+ {
+ depthOrLayers = Math.Max(1, parent.Info.DepthOrLayers >> firstLevel);
+ }
+ else
+ {
+ depthOrLayers = info.DepthOrLayers;
+ }
+
+ return new TextureInfo(
+ info.Address,
+ width,
+ height,
+ depthOrLayers,
+ info.Levels,
+ info.SamplesInX,
+ info.SamplesInY,
+ info.Stride,
+ info.IsLinear,
+ info.GobBlocksInY,
+ info.GobBlocksInZ,
+ info.GobBlocksInTileX,
+ info.Target,
+ info.FormatInfo,
+ info.DepthStencilMode,
+ info.SwizzleR,
+ info.SwizzleG,
+ info.SwizzleB,
+ info.SwizzleA);
+ }
+
+ public static TextureCreateInfo GetCreateInfo(TextureInfo info, Capabilities caps)
+ {
+ FormatInfo formatInfo = info.FormatInfo;
+
+ if (!caps.SupportsAstcCompression)
+ {
+ if (formatInfo.Format.IsAstcUnorm())
+ {
+ formatInfo = new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4);
+ }
+ else if (formatInfo.Format.IsAstcSrgb())
+ {
+ formatInfo = new FormatInfo(Format.R8G8B8A8Srgb, 1, 1, 4);
+ }
+ }
+
+ int width = info.Width / info.SamplesInX;
+ int height = info.Height / info.SamplesInY;
+
+ int depth = info.GetDepth() * info.GetLayers();
+
+ return new TextureCreateInfo(
+ width,
+ height,
+ depth,
+ info.Levels,
+ info.Samples,
+ formatInfo.BlockWidth,
+ formatInfo.BlockHeight,
+ formatInfo.BytesPerPixel,
+ formatInfo.Format,
+ info.DepthStencilMode,
+ info.Target,
+ info.SwizzleR,
+ info.SwizzleG,
+ info.SwizzleB,
+ info.SwizzleA);
+ }
+
+ public Texture Find2(ulong address)
+ {
+ Texture[] ts = _textures.FindOverlaps(address, 1);
+
+ if (ts.Length == 2)
+ {
+ return ts[1];
+ }
+
+ if (ts.Length == 0)
+ {
+ ts = _textures.FindOverlaps(address - 1, 2);
+ }
+
+ if (ts.Length == 0)
+ {
+ return null;
+ }
+
+ return ts[0];
+ }
+
+ public void InvalidateRange(ulong address, ulong size)
+ {
+ Texture[] overlaps = _textures.FindOverlaps(address, size);
+
+ foreach (Texture overlap in overlaps)
+ {
+ overlap.Invalidate();
+ }
+
+ _samplerPool?.InvalidateRange(address, size);
+
+ _texturePoolCache.InvalidateRange(address, size);
+ }
+
+ public void Flush()
+ {
+ foreach (Texture texture in _cache)
+ {
+ if (texture.Info.IsLinear && texture.Modified)
+ {
+ texture.Flush();
+
+ texture.Modified = false;
+ }
+ }
+ }
+
+ public void RemoveTextureFromCache(Texture texture)
+ {
+ _textures.Remove(texture);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureMsaaMode.cs b/Ryujinx.Graphics.Gpu/Image/TextureMsaaMode.cs
new file mode 100644
index 000000000..134210671
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureMsaaMode.cs
@@ -0,0 +1,53 @@
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ enum TextureMsaaMode
+ {
+ Ms1x1 = 0,
+ Ms2x2 = 2,
+ Ms4x2 = 4,
+ Ms2x1 = 5,
+ Ms4x4 = 6
+ }
+
+ static class TextureMsaaModeConverter
+ {
+ public static int SamplesCount(this TextureMsaaMode msaaMode)
+ {
+ switch (msaaMode)
+ {
+ case TextureMsaaMode.Ms2x1: return 2;
+ case TextureMsaaMode.Ms2x2: return 4;
+ case TextureMsaaMode.Ms4x2: return 8;
+ case TextureMsaaMode.Ms4x4: return 16;
+ }
+
+ return 1;
+ }
+
+ public static int SamplesInX(this TextureMsaaMode msaaMode)
+ {
+ switch (msaaMode)
+ {
+ case TextureMsaaMode.Ms2x1: return 2;
+ case TextureMsaaMode.Ms2x2: return 2;
+ case TextureMsaaMode.Ms4x2: return 4;
+ case TextureMsaaMode.Ms4x4: return 4;
+ }
+
+ return 1;
+ }
+
+ public static int SamplesInY(this TextureMsaaMode msaaMode)
+ {
+ switch (msaaMode)
+ {
+ case TextureMsaaMode.Ms2x1: return 1;
+ case TextureMsaaMode.Ms2x2: return 2;
+ case TextureMsaaMode.Ms4x2: return 2;
+ case TextureMsaaMode.Ms4x4: return 4;
+ }
+
+ return 1;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TexturePool.cs b/Ryujinx.Graphics.Gpu/Image/TexturePool.cs
new file mode 100644
index 000000000..558f4def4
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TexturePool.cs
@@ -0,0 +1,219 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.Gpu.Memory;
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ class TexturePool : Pool
+ {
+ private TextureManager _textureManager;
+
+ public LinkedListNode CacheNode { get; set; }
+
+ private struct TextureContainer
+ {
+ public Texture Texture0 { get; set; }
+ public Texture Texture1 { get; set; }
+ }
+
+ public TexturePool(
+ GpuContext context,
+ TextureManager textureManager,
+ ulong address,
+ int maximumId) : base(context, address, maximumId)
+ {
+ _textureManager = textureManager;
+ }
+
+ public override Texture Get(int id)
+ {
+ if ((uint)id >= Items.Length)
+ {
+ return null;
+ }
+
+ SynchronizeMemory();
+
+ Texture texture = Items[id];
+
+ if (texture == null)
+ {
+ ulong address = Address + (ulong)(uint)id * DescriptorSize;
+
+ Span data = Context.PhysicalMemory.Read(address, DescriptorSize);
+
+ TextureDescriptor descriptor = MemoryMarshal.Cast(data)[0];
+
+ TextureInfo info = GetInfo(descriptor);
+
+ // Bad address. We can't add a texture with a invalid address
+ // to the cache.
+ if (info.Address == MemoryManager.BadAddress)
+ {
+ return null;
+ }
+
+ texture = _textureManager.FindOrCreateTexture(info, TextureSearchFlags.Sampler);
+
+ texture.IncrementReferenceCount();
+
+ Items[id] = texture;
+ }
+ else
+ {
+ // Memory is automatically synchronized on texture creation.
+ texture.SynchronizeMemory();
+ }
+
+ return texture;
+ }
+
+ protected override void InvalidateRangeImpl(ulong address, ulong size)
+ {
+ ulong endAddress = address + size;
+
+ for (; address < endAddress; address += DescriptorSize)
+ {
+ int id = (int)((address - Address) / DescriptorSize);
+
+ Texture texture = Items[id];
+
+ if (texture != null)
+ {
+ Span data = Context.PhysicalMemory.Read(address, DescriptorSize);
+
+ TextureDescriptor descriptor = MemoryMarshal.Cast(data)[0];
+
+ // If the descriptors are the same, the texture is the same,
+ // we don't need to remove as it was not modified. Just continue.
+ if (texture.IsPerfectMatch(GetInfo(descriptor), TextureSearchFlags.Strict))
+ {
+ continue;
+ }
+
+ texture.DecrementReferenceCount();
+
+ Items[id] = null;
+ }
+ }
+ }
+
+ private TextureInfo GetInfo(TextureDescriptor descriptor)
+ {
+ ulong address = Context.MemoryManager.Translate(descriptor.UnpackAddress());
+
+ int width = descriptor.UnpackWidth();
+ int height = descriptor.UnpackHeight();
+ int depthOrLayers = descriptor.UnpackDepth();
+ int levels = descriptor.UnpackLevels();
+
+ TextureMsaaMode msaaMode = descriptor.UnpackTextureMsaaMode();
+
+ int samplesInX = msaaMode.SamplesInX();
+ int samplesInY = msaaMode.SamplesInY();
+
+ int stride = descriptor.UnpackStride();
+
+ TextureDescriptorType descriptorType = descriptor.UnpackTextureDescriptorType();
+
+ bool isLinear = descriptorType == TextureDescriptorType.Linear;
+
+ Target target = descriptor.UnpackTextureTarget().Convert((samplesInX | samplesInY) != 1);
+
+ uint format = descriptor.UnpackFormat();
+ bool srgb = descriptor.UnpackSrgb();
+
+ if (!FormatTable.TryGetTextureFormat(format, srgb, out FormatInfo formatInfo))
+ {
+ // TODO: Warning.
+
+ formatInfo = FormatInfo.Default;
+ }
+
+ int gobBlocksInY = descriptor.UnpackGobBlocksInY();
+ int gobBlocksInZ = descriptor.UnpackGobBlocksInZ();
+
+ int gobBlocksInTileX = descriptor.UnpackGobBlocksInTileX();
+
+ SwizzleComponent swizzleR = descriptor.UnpackSwizzleR().Convert();
+ SwizzleComponent swizzleG = descriptor.UnpackSwizzleG().Convert();
+ SwizzleComponent swizzleB = descriptor.UnpackSwizzleB().Convert();
+ SwizzleComponent swizzleA = descriptor.UnpackSwizzleA().Convert();
+
+ DepthStencilMode depthStencilMode = GetDepthStencilMode(
+ formatInfo.Format,
+ swizzleR,
+ swizzleG,
+ swizzleB,
+ swizzleA);
+
+ return new TextureInfo(
+ address,
+ width,
+ height,
+ depthOrLayers,
+ levels,
+ samplesInX,
+ samplesInY,
+ stride,
+ isLinear,
+ gobBlocksInY,
+ gobBlocksInZ,
+ gobBlocksInTileX,
+ target,
+ formatInfo,
+ depthStencilMode,
+ swizzleR,
+ swizzleG,
+ swizzleB,
+ swizzleA);
+ }
+
+ private static DepthStencilMode GetDepthStencilMode(Format format, params SwizzleComponent[] components)
+ {
+ // R = Depth, G = Stencil.
+ // On 24-bits depth formats, this is inverted (Stencil is R etc).
+ // NVN setup:
+ // For depth, A is set to 1.0f, the other components are set to Depth.
+ // For stencil, all components are set to Stencil.
+ SwizzleComponent component = components[0];
+
+ for (int index = 1; index < 4 && !IsRG(component); index++)
+ {
+ component = components[index];
+ }
+
+ if (!IsRG(component))
+ {
+ return DepthStencilMode.Depth;
+ }
+
+ if (format == Format.D24X8Unorm || format == Format.D24UnormS8Uint)
+ {
+ return component == SwizzleComponent.Red
+ ? DepthStencilMode.Stencil
+ : DepthStencilMode.Depth;
+ }
+ else
+ {
+ return component == SwizzleComponent.Red
+ ? DepthStencilMode.Depth
+ : DepthStencilMode.Stencil;
+ }
+ }
+
+ private static bool IsRG(SwizzleComponent component)
+ {
+ return component == SwizzleComponent.Red ||
+ component == SwizzleComponent.Green;
+ }
+
+ protected override void Delete(Texture item)
+ {
+ item?.DecrementReferenceCount();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TexturePoolCache.cs b/Ryujinx.Graphics.Gpu/Image/TexturePoolCache.cs
new file mode 100644
index 000000000..8e8313ae3
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TexturePoolCache.cs
@@ -0,0 +1,73 @@
+using System.Collections.Generic;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ class TexturePoolCache
+ {
+ private const int MaxCapacity = 4;
+
+ private GpuContext _context;
+ private TextureManager _textureManager;
+
+ private LinkedList _pools;
+
+ public TexturePoolCache(GpuContext context, TextureManager textureManager)
+ {
+ _context = context;
+ _textureManager = textureManager;
+
+ _pools = new LinkedList();
+ }
+
+ public TexturePool FindOrCreate(ulong address, int maximumId)
+ {
+ TexturePool pool;
+
+ // First we try to find the pool.
+ for (LinkedListNode node = _pools.First; node != null; node = node.Next)
+ {
+ pool = node.Value;
+
+ if (pool.Address == address)
+ {
+ if (pool.CacheNode != _pools.Last)
+ {
+ _pools.Remove(pool.CacheNode);
+
+ pool.CacheNode = _pools.AddLast(pool);
+ }
+
+ return pool;
+ }
+ }
+
+ // If not found, create a new one.
+ pool = new TexturePool(_context, _textureManager, address, maximumId);
+
+ pool.CacheNode = _pools.AddLast(pool);
+
+ if (_pools.Count > MaxCapacity)
+ {
+ TexturePool oldestPool = _pools.First.Value;
+
+ _pools.RemoveFirst();
+
+ oldestPool.Dispose();
+
+ oldestPool.CacheNode = null;
+ }
+
+ return pool;
+ }
+
+ public void InvalidateRange(ulong address, ulong size)
+ {
+ for (LinkedListNode node = _pools.First; node != null; node = node.Next)
+ {
+ TexturePool pool = node.Value;
+
+ pool.InvalidateRange(address, size);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureSearchFlags.cs b/Ryujinx.Graphics.Gpu/Image/TextureSearchFlags.cs
new file mode 100644
index 000000000..a5c951b53
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureSearchFlags.cs
@@ -0,0 +1,13 @@
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ [Flags]
+ enum TextureSearchFlags
+ {
+ None = 0,
+ IgnoreMs = 1 << 0,
+ Strict = 1 << 1 | Sampler,
+ Sampler = 1 << 2
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Image/TextureTarget.cs b/Ryujinx.Graphics.Gpu/Image/TextureTarget.cs
new file mode 100644
index 000000000..8f5139034
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Image/TextureTarget.cs
@@ -0,0 +1,49 @@
+using Ryujinx.Graphics.GAL.Texture;
+
+namespace Ryujinx.Graphics.Gpu.Image
+{
+ enum TextureTarget
+ {
+ Texture1D,
+ Texture2D,
+ Texture3D,
+ Cubemap,
+ Texture1DArray,
+ Texture2DArray,
+ TextureBuffer,
+ Texture2DLinear,
+ CubemapArray
+ }
+
+ static class TextureTargetConverter
+ {
+ public static Target Convert(this TextureTarget target, bool isMultisample)
+ {
+ if (isMultisample)
+ {
+ switch (target)
+ {
+ case TextureTarget.Texture2D: return Target.Texture2DMultisample;
+ case TextureTarget.Texture2DArray: return Target.Texture2DMultisampleArray;
+ }
+ }
+ else
+ {
+ switch (target)
+ {
+ case TextureTarget.Texture1D: return Target.Texture1D;
+ case TextureTarget.Texture2D: return Target.Texture2D;
+ case TextureTarget.Texture2DLinear: return Target.Texture2D;
+ case TextureTarget.Texture3D: return Target.Texture3D;
+ case TextureTarget.Texture1DArray: return Target.Texture1DArray;
+ case TextureTarget.Texture2DArray: return Target.Texture2DArray;
+ case TextureTarget.Cubemap: return Target.Cubemap;
+ case TextureTarget.CubemapArray: return Target.CubemapArray;
+ case TextureTarget.TextureBuffer: return Target.TextureBuffer;
+ }
+ }
+
+ return Target.Texture1D;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs b/Ryujinx.Graphics.Gpu/MacroInterpreter.cs
similarity index 92%
rename from Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs
rename to Ryujinx.Graphics.Gpu/MacroInterpreter.cs
index 9a6206fa4..93d5c2ca2 100644
--- a/Ryujinx.Graphics/Graphics3d/MacroInterpreter.cs
+++ b/Ryujinx.Graphics.Gpu/MacroInterpreter.cs
@@ -1,9 +1,8 @@
using Ryujinx.Common.Logging;
-using Ryujinx.Graphics.Memory;
using System;
using System.Collections.Generic;
-namespace Ryujinx.Graphics.Graphics3d
+namespace Ryujinx.Graphics.Gpu
{
class MacroInterpreter
{
@@ -42,8 +41,9 @@ namespace Ryujinx.Graphics.Graphics3d
BitwiseNotAnd = 12
}
- private NvGpuFifo _pFifo;
- private INvGpuEngine _engine;
+ private GpuContext _context;
+
+ private NvGpuFifo _pFifo;
public Queue Fifo { get; private set; }
@@ -60,17 +60,17 @@ namespace Ryujinx.Graphics.Graphics3d
private int _pc;
- public MacroInterpreter(NvGpuFifo pFifo, INvGpuEngine engine)
+ public MacroInterpreter(GpuContext context, NvGpuFifo pFifo)
{
- _pFifo = pFifo;
- _engine = engine;
+ _context = context;
+ _pFifo = pFifo;
Fifo = new Queue();
_gprs = new int[8];
}
- public void Execute(NvGpuVmm vmm, int[] mme, int position, int param)
+ public void Execute(int[] mme, int position, int param)
{
Reset();
@@ -80,11 +80,11 @@ namespace Ryujinx.Graphics.Graphics3d
FetchOpCode(mme);
- while (Step(vmm, mme));
+ while (Step(mme));
// Due to the delay slot, we still need to execute
// one more instruction before we actually exit.
- Step(vmm, mme);
+ Step(mme);
}
private void Reset()
@@ -100,7 +100,7 @@ namespace Ryujinx.Graphics.Graphics3d
_carry = false;
}
- private bool Step(NvGpuVmm vmm, int[] mme)
+ private bool Step(int[] mme)
{
int baseAddr = _pc - 1;
@@ -146,7 +146,7 @@ namespace Ryujinx.Graphics.Graphics3d
{
SetDstGpr(FetchParam());
- Send(vmm, result);
+ Send(result);
break;
}
@@ -156,7 +156,7 @@ namespace Ryujinx.Graphics.Graphics3d
{
SetDstGpr(result);
- Send(vmm, result);
+ Send(result);
break;
}
@@ -178,7 +178,7 @@ namespace Ryujinx.Graphics.Graphics3d
SetMethAddr(result);
- Send(vmm, FetchParam());
+ Send(FetchParam());
break;
}
@@ -190,7 +190,7 @@ namespace Ryujinx.Graphics.Graphics3d
SetMethAddr(result);
- Send(vmm, (result >> 12) & 0x3f);
+ Send((result >> 12) & 0x3f);
break;
}
@@ -228,7 +228,6 @@ namespace Ryujinx.Graphics.Graphics3d
private void FetchOpCode(int[] mme)
{
_opCode = _pipeOp;
-
_pipeOp = mme[_pc++];
}
@@ -401,14 +400,14 @@ namespace Ryujinx.Graphics.Graphics3d
private int Read(int reg)
{
- return _engine.Registers[reg];
+ return _context.State.Read(reg);
}
- private void Send(NvGpuVmm vmm, int value)
+ private void Send(int value)
{
- GpuMethodCall methCall = new GpuMethodCall(_methAddr, value);
+ MethodParams meth = new MethodParams(_methAddr, value);
- _engine.CallMethod(vmm, methCall);
+ _context.State.CallMethod(meth);
_methAddr += _methIncr;
}
diff --git a/Ryujinx.Graphics.Gpu/Memory/Buffer.cs b/Ryujinx.Graphics.Gpu/Memory/Buffer.cs
new file mode 100644
index 000000000..30bd1ac07
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/Buffer.cs
@@ -0,0 +1,99 @@
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ class Buffer : IRange, IDisposable
+ {
+ private GpuContext _context;
+
+ private IBuffer _buffer;
+
+ public ulong Address { get; }
+ public ulong Size { get; }
+
+ public ulong EndAddress => Address + Size;
+
+ private int[] _sequenceNumbers;
+
+ public Buffer(GpuContext context, ulong address, ulong size)
+ {
+ _context = context;
+ Address = address;
+ Size = size;
+
+ _buffer = context.Renderer.CreateBuffer((int)size);
+
+ _sequenceNumbers = new int[size / MemoryManager.PageSize];
+
+ Invalidate();
+ }
+
+ public BufferRange GetRange(ulong address, ulong size)
+ {
+ int offset = (int)(address - Address);
+
+ return new BufferRange(_buffer, offset, (int)size);
+ }
+
+ public bool OverlapsWith(ulong address, ulong size)
+ {
+ return Address < address + size && address < EndAddress;
+ }
+
+ public void SynchronizeMemory(ulong address, ulong size)
+ {
+ int currentSequenceNumber = _context.SequenceNumber;
+
+ bool needsSync = false;
+
+ ulong buffOffset = address - Address;
+
+ ulong buffEndOffset = (buffOffset + size + MemoryManager.PageMask) & ~MemoryManager.PageMask;
+
+ int startIndex = (int)(buffOffset / MemoryManager.PageSize);
+ int endIndex = (int)(buffEndOffset / MemoryManager.PageSize);
+
+ for (int index = startIndex; index < endIndex; index++)
+ {
+ if (_sequenceNumbers[index] != currentSequenceNumber)
+ {
+ _sequenceNumbers[index] = currentSequenceNumber;
+
+ needsSync = true;
+ }
+ }
+
+ if (!needsSync)
+ {
+ return;
+ }
+
+ (ulong, ulong)[] modifiedRanges = _context.PhysicalMemory.GetModifiedRanges(address, size);
+
+ for (int index = 0; index < modifiedRanges.Length; index++)
+ {
+ (ulong mAddress, ulong mSize) = modifiedRanges[index];
+
+ int offset = (int)(mAddress - Address);
+
+ _buffer.SetData(offset, _context.PhysicalMemory.Read(mAddress, mSize));
+ }
+ }
+
+ public void CopyTo(Buffer destination, int dstOffset)
+ {
+ _buffer.CopyTo(destination._buffer, 0, dstOffset, (int)Size);
+ }
+
+ public void Invalidate()
+ {
+ _buffer.SetData(0, _context.PhysicalMemory.Read(Address, Size));
+ }
+
+ public void Dispose()
+ {
+ _buffer.Dispose();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/BufferBounds.cs b/Ryujinx.Graphics.Gpu/Memory/BufferBounds.cs
new file mode 100644
index 000000000..2a074bd3d
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/BufferBounds.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ struct BufferBounds
+ {
+ public ulong Address;
+ public ulong Size;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs b/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs
new file mode 100644
index 000000000..eb2e0ca9c
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/BufferManager.cs
@@ -0,0 +1,530 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.InputAssembler;
+using Ryujinx.Graphics.Gpu.State;
+using Ryujinx.Graphics.Shader;
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ class BufferManager
+ {
+ private const ulong BufferAlignmentSize = 0x1000;
+ private const ulong BufferAlignmentMask = BufferAlignmentSize - 1;
+
+ private GpuContext _context;
+
+ private RangeList _buffers;
+
+ private IndexBuffer _indexBuffer;
+
+ private VertexBuffer[] _vertexBuffers;
+
+ private class BuffersPerStage
+ {
+ public uint EnableMask { get; set; }
+
+ public BufferBounds[] Buffers { get; }
+
+ public BuffersPerStage(int count)
+ {
+ Buffers = new BufferBounds[count];
+ }
+
+ public void Bind(int index, ulong address, ulong size)
+ {
+ Buffers[index].Address = address;
+ Buffers[index].Size = size;
+ }
+ }
+
+ private BuffersPerStage _cpStorageBuffers;
+ private BuffersPerStage _cpUniformBuffers;
+ private BuffersPerStage[] _gpStorageBuffers;
+ private BuffersPerStage[] _gpUniformBuffers;
+
+ private bool _gpStorageBuffersDirty;
+ private bool _gpUniformBuffersDirty;
+
+ private bool _indexBufferDirty;
+ private bool _vertexBuffersDirty;
+
+ private bool _rebind;
+
+ public BufferManager(GpuContext context)
+ {
+ _context = context;
+
+ _buffers = new RangeList();
+
+ _vertexBuffers = new VertexBuffer[Constants.TotalVertexBuffers];
+
+ _cpStorageBuffers = new BuffersPerStage(Constants.TotalCpStorageBuffers);
+ _cpUniformBuffers = new BuffersPerStage(Constants.TotalCpUniformBuffers);
+
+ _gpStorageBuffers = new BuffersPerStage[Constants.TotalShaderStages];
+ _gpUniformBuffers = new BuffersPerStage[Constants.TotalShaderStages];
+
+ for (int index = 0; index < Constants.TotalShaderStages; index++)
+ {
+ _gpStorageBuffers[index] = new BuffersPerStage(Constants.TotalGpStorageBuffers);
+ _gpUniformBuffers[index] = new BuffersPerStage(Constants.TotalGpUniformBuffers);
+ }
+ }
+
+ public void SetIndexBuffer(ulong gpuVa, ulong size, IndexType type)
+ {
+ ulong address = TranslateAndCreateBuffer(gpuVa, size);
+
+ _indexBuffer.Address = address;
+ _indexBuffer.Size = size;
+ _indexBuffer.Type = type;
+
+ _indexBufferDirty = true;
+ }
+
+ public void SetVertexBuffer(int index, ulong gpuVa, ulong size, int stride, int divisor)
+ {
+ ulong address = TranslateAndCreateBuffer(gpuVa, size);
+
+ _vertexBuffers[index].Address = address;
+ _vertexBuffers[index].Size = size;
+ _vertexBuffers[index].Stride = stride;
+ _vertexBuffers[index].Divisor = divisor;
+
+ _vertexBuffersDirty = true;
+ }
+
+ public void SetComputeStorageBuffer(int index, ulong gpuVa, ulong size)
+ {
+ // TODO: Improve
+ size += gpuVa & 0x3fUL;
+
+ gpuVa &= ~0x3fUL;
+
+ ulong address = TranslateAndCreateBuffer(gpuVa, size);
+
+ _cpStorageBuffers.Bind(index, address, size);
+ }
+
+ public void SetGraphicsStorageBuffer(int stage, int index, ulong gpuVa, ulong size)
+ {
+ // TODO: Improve
+ size += gpuVa & 0x3fUL;
+
+ gpuVa &= ~0x3fUL;
+
+ ulong address = TranslateAndCreateBuffer(gpuVa, size);
+
+ _gpStorageBuffers[stage].Bind(index, address, size);
+
+ _gpStorageBuffersDirty = true;
+ }
+
+ public void SetComputeUniformBuffer(int index, ulong gpuVa, ulong size)
+ {
+ ulong address = TranslateAndCreateBuffer(gpuVa, size);
+
+ _cpUniformBuffers.Bind(index, address, size);
+ }
+
+ public void SetGraphicsUniformBuffer(int stage, int index, ulong gpuVa, ulong size)
+ {
+ ulong address = TranslateAndCreateBuffer(gpuVa, size);
+
+ _gpUniformBuffers[stage].Bind(index, address, size);
+
+ _gpUniformBuffersDirty = true;
+ }
+
+ public void SetComputeStorageBufferEnableMask(uint mask)
+ {
+ _cpStorageBuffers.EnableMask = mask;
+ }
+
+ public void SetGraphicsStorageBufferEnableMask(int stage, uint mask)
+ {
+ _gpStorageBuffers[stage].EnableMask = mask;
+
+ _gpStorageBuffersDirty = true;
+ }
+
+ public void SetComputeUniformBufferEnableMask(uint mask)
+ {
+ _cpUniformBuffers.EnableMask = mask;
+ }
+
+ public void SetGraphicsUniformBufferEnableMask(int stage, uint mask)
+ {
+ _gpUniformBuffers[stage].EnableMask = mask;
+
+ _gpUniformBuffersDirty = true;
+ }
+
+ private ulong TranslateAndCreateBuffer(ulong gpuVa, ulong size)
+ {
+ if (gpuVa == 0)
+ {
+ return 0;
+ }
+
+ ulong address = _context.MemoryManager.Translate(gpuVa);
+
+ if (address == MemoryManager.BadAddress)
+ {
+ return 0;
+ }
+
+ ulong endAddress = address + size;
+
+ ulong alignedAddress = address & ~BufferAlignmentMask;
+
+ ulong alignedEndAddress = (endAddress + BufferAlignmentMask) & ~BufferAlignmentMask;
+
+ // The buffer must have the size of at least one page.
+ if (alignedEndAddress == alignedAddress)
+ {
+ alignedEndAddress += BufferAlignmentSize;
+ }
+
+ CreateBuffer(alignedAddress, alignedEndAddress - alignedAddress);
+
+ return address;
+ }
+
+ private void CreateBuffer(ulong address, ulong size)
+ {
+ Buffer[] overlaps = _buffers.FindOverlaps(address, size);
+
+ if (overlaps.Length != 0)
+ {
+ // The buffer already exists. We can just return the existing buffer
+ // if the buffer we need is fully contained inside the overlapping buffer.
+ // Otherwise, we must delete the overlapping buffers and create a bigger buffer
+ // that fits all the data we need. We also need to copy the contents from the
+ // old buffer(s) to the new buffer.
+ ulong endAddress = address + size;
+
+ if (overlaps[0].Address > address || overlaps[0].EndAddress < endAddress)
+ {
+ foreach (Buffer buffer in overlaps)
+ {
+ address = Math.Min(address, buffer.Address);
+ endAddress = Math.Max(endAddress, buffer.EndAddress);
+
+ buffer.SynchronizeMemory(buffer.Address, buffer.Size);
+
+ _buffers.Remove(buffer);
+ }
+
+ Buffer newBuffer = new Buffer(_context, address, endAddress - address);
+
+ _buffers.Add(newBuffer);
+
+ foreach (Buffer buffer in overlaps)
+ {
+ int dstOffset = (int)(buffer.Address - newBuffer.Address);
+
+ buffer.CopyTo(newBuffer, dstOffset);
+
+ buffer.Dispose();
+ }
+
+ _rebind = true;
+ }
+ }
+ else
+ {
+ // No overlap, just create a new buffer.
+ Buffer buffer = new Buffer(_context, address, size);
+
+ _buffers.Add(buffer);
+ }
+ }
+
+ public ulong GetComputeUniformBufferAddress(int index)
+ {
+ return _cpUniformBuffers.Buffers[index].Address;
+ }
+
+ public ulong GetGraphicsUniformBufferAddress(int stage, int index)
+ {
+ return _gpUniformBuffers[stage].Buffers[index].Address;
+ }
+
+ public void CommitComputeBindings()
+ {
+ uint enableMask = _cpStorageBuffers.EnableMask;
+
+ for (int index = 0; (enableMask >> index) != 0; index++)
+ {
+ if ((enableMask & (1u << index)) == 0)
+ {
+ continue;
+ }
+
+ BufferBounds bounds = _cpStorageBuffers.Buffers[index];
+
+ if (bounds.Address == 0)
+ {
+ continue;
+ }
+
+ BufferRange buffer = GetBufferRange(bounds.Address, bounds.Size);
+
+ _context.Renderer.ComputePipeline.SetStorageBuffer(index, buffer);
+ }
+
+ enableMask = _cpUniformBuffers.EnableMask;
+
+ for (int index = 0; (enableMask >> index) != 0; index++)
+ {
+ if ((enableMask & (1u << index)) == 0)
+ {
+ continue;
+ }
+
+ BufferBounds bounds = _cpUniformBuffers.Buffers[index];
+
+ if (bounds.Address == 0)
+ {
+ continue;
+ }
+
+ BufferRange buffer = GetBufferRange(bounds.Address, bounds.Size);
+
+ _context.Renderer.ComputePipeline.SetUniformBuffer(index, buffer);
+
+ if (index == 0)
+ {
+ // TODO: Improve
+ Span data = _context.PhysicalMemory.Read(bounds.Address + 0x310, 0x100);
+
+ Span words = MemoryMarshal.Cast(data);
+
+ for (int offset = 0; offset < 0x40; offset += 4)
+ {
+ words[offset] &= 0x3f;
+ }
+
+ buffer = GetBufferRange(bounds.Address + 0x310, 0x100);
+
+ buffer.Buffer.SetData(buffer.Offset, data);
+ }
+ }
+ }
+
+ public void CommitBindings()
+ {
+ if (_indexBufferDirty || _rebind)
+ {
+ _indexBufferDirty = false;
+
+ if (_indexBuffer.Address != 0)
+ {
+ BufferRange buffer = GetBufferRange(_indexBuffer.Address, _indexBuffer.Size);
+
+ _context.Renderer.GraphicsPipeline.BindIndexBuffer(buffer, _indexBuffer.Type);
+ }
+ }
+ else if (_indexBuffer.Address != 0)
+ {
+ SynchronizeBufferRange(_indexBuffer.Address, _indexBuffer.Size);
+ }
+
+ if (_vertexBuffersDirty || _rebind)
+ {
+ _vertexBuffersDirty = false;
+
+ VertexBufferDescriptor[] vertexBuffers = new VertexBufferDescriptor[Constants.TotalVertexBuffers];
+
+ for (int index = 0; index < Constants.TotalVertexBuffers; index++)
+ {
+ VertexBuffer vb = _vertexBuffers[index];
+
+ if (vb.Address == 0)
+ {
+ continue;
+ }
+
+ BufferRange buffer = GetBufferRange(vb.Address, vb.Size);
+
+ vertexBuffers[index] = new VertexBufferDescriptor(buffer, vb.Stride, vb.Divisor);
+ }
+
+ _context.Renderer.GraphicsPipeline.BindVertexBuffers(vertexBuffers);
+ }
+ else
+ {
+ for (int index = 0; index < Constants.TotalVertexBuffers; index++)
+ {
+ VertexBuffer vb = _vertexBuffers[index];
+
+ if (vb.Address == 0)
+ {
+ continue;
+ }
+
+ SynchronizeBufferRange(vb.Address, vb.Size);
+ }
+ }
+
+ if (_gpStorageBuffersDirty || _rebind)
+ {
+ _gpStorageBuffersDirty = false;
+
+ BindBuffers(_gpStorageBuffers, isStorage: true);
+ }
+ else
+ {
+ UpdateBuffers(_gpStorageBuffers);
+ }
+
+ if (_gpUniformBuffersDirty || _rebind)
+ {
+ _gpUniformBuffersDirty = false;
+
+ BindBuffers(_gpUniformBuffers, isStorage: false);
+ }
+ else
+ {
+ UpdateBuffers(_gpUniformBuffers);
+ }
+
+ _rebind = false;
+ }
+
+ private void BindBuffers(BuffersPerStage[] bindings, bool isStorage)
+ {
+ BindOrUpdateBuffers(bindings, bind: true, isStorage);
+ }
+
+ private void UpdateBuffers(BuffersPerStage[] bindings)
+ {
+ BindOrUpdateBuffers(bindings, bind: false);
+ }
+
+ private void BindOrUpdateBuffers(BuffersPerStage[] bindings, bool bind, bool isStorage = false)
+ {
+ for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
+ {
+ uint enableMask = bindings[(int)stage - 1].EnableMask;
+
+ if (enableMask == 0)
+ {
+ continue;
+ }
+
+ for (int index = 0; (enableMask >> index) != 0; index++)
+ {
+ if ((enableMask & (1u << index)) == 0)
+ {
+ continue;
+ }
+
+ BufferBounds bounds = bindings[(int)stage - 1].Buffers[index];
+
+ if (bounds.Address == 0)
+ {
+ continue;
+ }
+
+ if (bind)
+ {
+ BindBuffer(index, stage, bounds, isStorage);
+ }
+ else
+ {
+ SynchronizeBufferRange(bounds.Address, bounds.Size);
+ }
+ }
+ }
+ }
+
+ private void BindBuffer(int index, ShaderStage stage, BufferBounds bounds, bool isStorage)
+ {
+ BufferRange buffer = GetBufferRange(bounds.Address, bounds.Size);
+
+ BufferRange[] buffers = new BufferRange[] { buffer };
+
+ if (isStorage)
+ {
+ _context.Renderer.GraphicsPipeline.BindStorageBuffers(index, stage, buffers);
+ }
+ else
+ {
+ _context.Renderer.GraphicsPipeline.BindUniformBuffers(index, stage, buffers);
+ }
+
+ if (!isStorage && index == 0)
+ {
+ // TODO: Improve
+ Span data = _context.PhysicalMemory.Read(bounds.Address + 0x110, 0x100);
+
+ Span words = MemoryMarshal.Cast(data);
+
+ for (int offset = 0; offset < 0x40; offset += 4)
+ {
+ words[offset] &= 0x3f;
+ }
+
+ buffer = GetBufferRange(bounds.Address + 0x110, 0x100);
+
+ buffer.Buffer.SetData(buffer.Offset, data);
+ }
+ }
+
+ public void CopyBuffer(GpuVa srcVa, GpuVa dstVa, ulong size)
+ {
+ ulong srcAddress = TranslateAndCreateBuffer(srcVa.Pack(), size);
+ ulong dstAddress = TranslateAndCreateBuffer(dstVa.Pack(), size);
+
+ BufferRange srcBuffer = GetBufferRange(srcAddress, size);
+ BufferRange dstBuffer = GetBufferRange(dstAddress, size);
+
+ srcBuffer.Buffer.CopyTo(
+ dstBuffer.Buffer,
+ srcBuffer.Offset,
+ dstBuffer.Offset,
+ (int)size);
+ }
+
+ private BufferRange GetBufferRange(ulong address, ulong size)
+ {
+ Buffer buffer;
+
+ if (size != 0)
+ {
+ buffer = _buffers.FindFirstOverlap(address, size);
+
+ buffer.SynchronizeMemory(address, size);
+ }
+ else
+ {
+ buffer = _buffers.FindFirstOverlap(address, 1);
+ }
+
+ return buffer.GetRange(address, size);
+ }
+
+ private void SynchronizeBufferRange(ulong address, ulong size)
+ {
+ if (size != 0)
+ {
+ Buffer buffer = _buffers.FindFirstOverlap(address, size);
+
+ buffer.SynchronizeMemory(address, size);
+ }
+ }
+
+ public void InvalidateRange(ulong address, ulong size)
+ {
+ Buffer[] overlappingBuffers = _buffers.FindOverlaps(address, size);
+
+ foreach (Buffer buffer in overlappingBuffers)
+ {
+ buffer.Invalidate();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/IPhysicalMemory.cs b/Ryujinx.Graphics.Gpu/Memory/IPhysicalMemory.cs
new file mode 100644
index 000000000..5f21704d4
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/IPhysicalMemory.cs
@@ -0,0 +1,15 @@
+using System;
+
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ public interface IPhysicalMemory
+ {
+ int GetPageSize();
+
+ Span Read(ulong address, ulong size);
+
+ void Write(ulong address, Span data);
+
+ (ulong, ulong)[] GetModifiedRanges(ulong address, ulong size);
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/IRange.cs b/Ryujinx.Graphics.Gpu/Memory/IRange.cs
new file mode 100644
index 000000000..ee3d5c0be
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/IRange.cs
@@ -0,0 +1,10 @@
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ interface IRange
+ {
+ ulong Address { get; }
+ ulong Size { get; }
+
+ bool OverlapsWith(ulong address, ulong size);
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/IndexBuffer.cs b/Ryujinx.Graphics.Gpu/Memory/IndexBuffer.cs
new file mode 100644
index 000000000..ce2a2c744
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/IndexBuffer.cs
@@ -0,0 +1,12 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ struct IndexBuffer
+ {
+ public ulong Address;
+ public ulong Size;
+
+ public IndexType Type;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/MemoryAccessor.cs b/Ryujinx.Graphics.Gpu/Memory/MemoryAccessor.cs
new file mode 100644
index 000000000..500c36e50
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/MemoryAccessor.cs
@@ -0,0 +1,54 @@
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ class MemoryAccessor
+ {
+ private GpuContext _context;
+
+ public MemoryAccessor(GpuContext context)
+ {
+ _context = context;
+ }
+
+ public Span Read(ulong gpuVa, ulong maxSize)
+ {
+ ulong processVa = _context.MemoryManager.Translate(gpuVa);
+
+ ulong size = Math.Min(_context.MemoryManager.GetSubSize(gpuVa), maxSize);
+
+ return _context.PhysicalMemory.Read(processVa, size);
+ }
+
+ public T Read(ulong gpuVa) where T : struct
+ {
+ ulong processVa = _context.MemoryManager.Translate(gpuVa);
+
+ ulong size = (uint)Marshal.SizeOf();
+
+ return MemoryMarshal.Cast(_context.PhysicalMemory.Read(processVa, size))[0];
+ }
+
+ public int ReadInt32(ulong gpuVa)
+ {
+ ulong processVa = _context.MemoryManager.Translate(gpuVa);
+
+ return BitConverter.ToInt32(_context.PhysicalMemory.Read(processVa, 4));
+ }
+
+ public void Write(ulong gpuVa, int value)
+ {
+ ulong processVa = _context.MemoryManager.Translate(gpuVa);
+
+ _context.PhysicalMemory.Write(processVa, BitConverter.GetBytes(value));
+ }
+
+ public void Write(ulong gpuVa, Span data)
+ {
+ ulong processVa = _context.MemoryManager.Translate(gpuVa);
+
+ _context.PhysicalMemory.Write(processVa, data);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs b/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs
new file mode 100644
index 000000000..d1a3e69cd
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/MemoryManager.cs
@@ -0,0 +1,265 @@
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ public class MemoryManager
+ {
+ private const ulong AddressSpaceSize = 1UL << 40;
+
+ public const ulong BadAddress = ulong.MaxValue;
+
+ private const int PtLvl0Bits = 14;
+ private const int PtLvl1Bits = 14;
+ private const int PtPageBits = 12;
+
+ private const ulong PtLvl0Size = 1UL << PtLvl0Bits;
+ private const ulong PtLvl1Size = 1UL << PtLvl1Bits;
+ public const ulong PageSize = 1UL << PtPageBits;
+
+ private const ulong PtLvl0Mask = PtLvl0Size - 1;
+ private const ulong PtLvl1Mask = PtLvl1Size - 1;
+ public const ulong PageMask = PageSize - 1;
+
+ private const int PtLvl0Bit = PtPageBits + PtLvl1Bits;
+ private const int PtLvl1Bit = PtPageBits;
+
+ private const ulong PteUnmapped = 0xffffffff_ffffffff;
+ private const ulong PteReserved = 0xffffffff_fffffffe;
+
+ private ulong[][] _pageTable;
+
+ public MemoryManager()
+ {
+ _pageTable = new ulong[PtLvl0Size][];
+ }
+
+ public ulong Map(ulong pa, ulong va, ulong size)
+ {
+ lock (_pageTable)
+ {
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ SetPte(va + offset, pa + offset);
+ }
+ }
+
+ return va;
+ }
+
+ public ulong Map(ulong pa, ulong size)
+ {
+ lock (_pageTable)
+ {
+ ulong va = GetFreePosition(size);
+
+ if (va != PteUnmapped)
+ {
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ SetPte(va + offset, pa + offset);
+ }
+ }
+
+ return va;
+ }
+ }
+
+ public ulong MapLow(ulong pa, ulong size)
+ {
+ lock (_pageTable)
+ {
+ ulong va = GetFreePosition(size, 1, PageSize);
+
+ if (va != PteUnmapped && va <= uint.MaxValue && (va + size) <= uint.MaxValue)
+ {
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ SetPte(va + offset, pa + offset);
+ }
+ }
+ else
+ {
+ va = PteUnmapped;
+ }
+
+ return va;
+ }
+ }
+
+ public ulong ReserveFixed(ulong va, ulong size)
+ {
+ lock (_pageTable)
+ {
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ if (IsPageInUse(va + offset))
+ {
+ return PteUnmapped;
+ }
+ }
+
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ SetPte(va + offset, PteReserved);
+ }
+ }
+
+ return va;
+ }
+
+ public ulong Reserve(ulong size, ulong alignment)
+ {
+ lock (_pageTable)
+ {
+ ulong address = GetFreePosition(size, alignment);
+
+ if (address != PteUnmapped)
+ {
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ SetPte(address + offset, PteReserved);
+ }
+ }
+
+ return address;
+ }
+ }
+
+ public void Free(ulong va, ulong size)
+ {
+ lock (_pageTable)
+ {
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ SetPte(va + offset, PteUnmapped);
+ }
+ }
+ }
+
+ private ulong GetFreePosition(ulong size, ulong alignment = 1, ulong start = 1UL << 32)
+ {
+ // Note: Address 0 is not considered valid by the driver,
+ // when 0 is returned it's considered a mapping error.
+ ulong address = start;
+ ulong freeSize = 0;
+
+ if (alignment == 0)
+ {
+ alignment = 1;
+ }
+
+ alignment = (alignment + PageMask) & ~PageMask;
+
+ while (address + freeSize < AddressSpaceSize)
+ {
+ if (!IsPageInUse(address + freeSize))
+ {
+ freeSize += PageSize;
+
+ if (freeSize >= size)
+ {
+ return address;
+ }
+ }
+ else
+ {
+ address += freeSize + PageSize;
+ freeSize = 0;
+
+ ulong remainder = address % alignment;
+
+ if (remainder != 0)
+ {
+ address = (address - remainder) + alignment;
+ }
+ }
+ }
+
+ return PteUnmapped;
+ }
+
+ internal ulong GetSubSize(ulong gpuVa)
+ {
+ ulong size = 0;
+
+ while (GetPte(gpuVa + size) != PteUnmapped)
+ {
+ size += PageSize;
+ }
+
+ return size;
+ }
+
+ internal ulong Translate(ulong gpuVa)
+ {
+ ulong baseAddress = GetPte(gpuVa);
+
+ if (baseAddress == PteUnmapped || baseAddress == PteReserved)
+ {
+ return PteUnmapped;
+ }
+
+ return baseAddress + (gpuVa & PageMask);
+ }
+
+ public bool IsRegionFree(ulong va, ulong size)
+ {
+ for (ulong offset = 0; offset < size; offset += PageSize)
+ {
+ if (IsPageInUse(va + offset))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private bool IsPageInUse(ulong va)
+ {
+ if (va >> PtLvl0Bits + PtLvl1Bits + PtPageBits != 0)
+ {
+ return false;
+ }
+
+ ulong l0 = (va >> PtLvl0Bit) & PtLvl0Mask;
+ ulong l1 = (va >> PtLvl1Bit) & PtLvl1Mask;
+
+ if (_pageTable[l0] == null)
+ {
+ return false;
+ }
+
+ return _pageTable[l0][l1] != PteUnmapped;
+ }
+
+ private ulong GetPte(ulong address)
+ {
+ ulong l0 = (address >> PtLvl0Bit) & PtLvl0Mask;
+ ulong l1 = (address >> PtLvl1Bit) & PtLvl1Mask;
+
+ if (_pageTable[l0] == null)
+ {
+ return PteUnmapped;
+ }
+
+ return _pageTable[l0][l1];
+ }
+
+ private void SetPte(ulong address, ulong tgtAddr)
+ {
+ ulong l0 = (address >> PtLvl0Bit) & PtLvl0Mask;
+ ulong l1 = (address >> PtLvl1Bit) & PtLvl1Mask;
+
+ if (_pageTable[l0] == null)
+ {
+ _pageTable[l0] = new ulong[PtLvl1Size];
+
+ for (ulong index = 0; index < PtLvl1Size; index++)
+ {
+ _pageTable[l0][index] = PteUnmapped;
+ }
+ }
+
+ _pageTable[l0][l1] = tgtAddr;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/RangeList.cs b/Ryujinx.Graphics.Gpu/Memory/RangeList.cs
new file mode 100644
index 000000000..6114f15df
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/RangeList.cs
@@ -0,0 +1,208 @@
+using System.Collections.Generic;
+
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ class RangeList where T : IRange
+ {
+ private List _items;
+
+ public RangeList()
+ {
+ _items = new List();
+ }
+
+ public void Add(T item)
+ {
+ lock (_items)
+ {
+ int index = BinarySearch(item.Address);
+
+ if (index < 0)
+ {
+ index = ~index;
+ }
+
+ _items.Insert(index, item);
+ }
+ }
+
+ public bool Remove(T item)
+ {
+ lock (_items)
+ {
+ int index = BinarySearch(item.Address);
+
+ if (index >= 0)
+ {
+ while (index > 0 && _items[index - 1].Address == item.Address)
+ {
+ index--;
+ }
+
+ while (index < _items.Count)
+ {
+ if (_items[index].Equals(item))
+ {
+ _items.RemoveAt(index);
+
+ return true;
+ }
+
+ if (_items[index].Address > item.Address)
+ {
+ break;
+ }
+
+ index++;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public T FindFirstOverlap(T item)
+ {
+ return FindFirstOverlap(item.Address, item.Size);
+ }
+
+ public T FindFirstOverlap(ulong address, ulong size)
+ {
+ lock (_items)
+ {
+ int index = BinarySearch(address, size);
+
+ if (index < 0)
+ {
+ return default(T);
+ }
+
+ return _items[index];
+ }
+ }
+
+ public T[] FindOverlaps(T item)
+ {
+ return FindOverlaps(item.Address, item.Size);
+ }
+
+ public T[] FindOverlaps(ulong address, ulong size)
+ {
+ List overlapsList = new List();
+
+ ulong endAddress = address + size;
+
+ lock (_items)
+ {
+ foreach (T item in _items)
+ {
+ if (item.Address >= endAddress)
+ {
+ break;
+ }
+
+ if (item.OverlapsWith(address, size))
+ {
+ overlapsList.Add(item);
+ }
+ }
+ }
+
+ return overlapsList.ToArray();
+ }
+
+ public T[] FindOverlaps(ulong address)
+ {
+ List overlapsList = new List();
+
+ lock (_items)
+ {
+ int index = BinarySearch(address);
+
+ if (index >= 0)
+ {
+ while (index > 0 && _items[index - 1].Address == address)
+ {
+ index--;
+ }
+
+ while (index < _items.Count)
+ {
+ T overlap = _items[index++];
+
+ if (overlap.Address != address)
+ {
+ break;
+ }
+
+ overlapsList.Add(overlap);
+ }
+ }
+ }
+
+ return overlapsList.ToArray();
+ }
+
+ private int BinarySearch(ulong address)
+ {
+ int left = 0;
+ int right = _items.Count - 1;
+
+ while (left <= right)
+ {
+ int range = right - left;
+
+ int middle = left + (range >> 1);
+
+ T item = _items[middle];
+
+ if (item.Address == address)
+ {
+ return middle;
+ }
+
+ if (address < item.Address)
+ {
+ right = middle - 1;
+ }
+ else
+ {
+ left = middle + 1;
+ }
+ }
+
+ return ~left;
+ }
+
+ private int BinarySearch(ulong address, ulong size)
+ {
+ int left = 0;
+ int right = _items.Count - 1;
+
+ while (left <= right)
+ {
+ int range = right - left;
+
+ int middle = left + (range >> 1);
+
+ T item = _items[middle];
+
+ if (item.OverlapsWith(address, size))
+ {
+ return middle;
+ }
+
+ if (address < item.Address)
+ {
+ right = middle - 1;
+ }
+ else
+ {
+ left = middle + 1;
+ }
+ }
+
+ return ~left;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/Memory/VertexBuffer.cs b/Ryujinx.Graphics.Gpu/Memory/VertexBuffer.cs
new file mode 100644
index 000000000..1cb854d63
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Memory/VertexBuffer.cs
@@ -0,0 +1,10 @@
+namespace Ryujinx.Graphics.Gpu.Memory
+{
+ struct VertexBuffer
+ {
+ public ulong Address;
+ public ulong Size;
+ public int Stride;
+ public int Divisor;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/GpuMethodCall.cs b/Ryujinx.Graphics.Gpu/MethodParams.cs
similarity index 91%
rename from Ryujinx.Graphics/GpuMethodCall.cs
rename to Ryujinx.Graphics.Gpu/MethodParams.cs
index 4a310b075..fea4eb303 100644
--- a/Ryujinx.Graphics/GpuMethodCall.cs
+++ b/Ryujinx.Graphics.Gpu/MethodParams.cs
@@ -1,6 +1,6 @@
namespace Ryujinx.Graphics
{
- struct GpuMethodCall
+ struct MethodParams
{
public int Method { get; private set; }
public int Argument { get; private set; }
@@ -9,7 +9,7 @@ namespace Ryujinx.Graphics
public bool IsLastCall => MethodCount <= 1;
- public GpuMethodCall(
+ public MethodParams(
int method,
int argument,
int subChannel = 0,
diff --git a/Ryujinx.Graphics.Gpu/NvGpuFifo.cs b/Ryujinx.Graphics.Gpu/NvGpuFifo.cs
new file mode 100644
index 000000000..f4deea54d
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/NvGpuFifo.cs
@@ -0,0 +1,150 @@
+namespace Ryujinx.Graphics.Gpu
+{
+ 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 GpuContext _context;
+
+ private struct CachedMacro
+ {
+ public int Position { get; private set; }
+
+ private bool _executionPending;
+ private int _argument;
+
+ private MacroInterpreter _interpreter;
+
+ public CachedMacro(GpuContext context, NvGpuFifo fifo, int position)
+ {
+ Position = position;
+
+ _executionPending = false;
+ _argument = 0;
+
+ _interpreter = new MacroInterpreter(context, fifo);
+ }
+
+ public void StartExecution(int argument)
+ {
+ _argument = argument;
+
+ _executionPending = true;
+ }
+
+ public void Execute(int[] mme)
+ {
+ if (_executionPending)
+ {
+ _executionPending = false;
+
+ _interpreter?.Execute(mme, Position, _argument);
+ }
+ }
+
+ public void PushArgument(int argument)
+ {
+ _interpreter?.Fifo.Enqueue(argument);
+ }
+ }
+
+ private int _currMacroPosition;
+ private int _currMacroBindIndex;
+
+ private CachedMacro[] _macros;
+
+ private int[] _mme;
+
+ private ClassId[] _subChannels;
+
+ public NvGpuFifo(GpuContext context)
+ {
+ _context = context;
+
+ _macros = new CachedMacro[MacrosCount];
+
+ _mme = new int[MmeWords];
+
+ _subChannels = new ClassId[8];
+ }
+
+ public void CallMethod(MethodParams meth)
+ {
+ if ((NvGpuFifoMeth)meth.Method == NvGpuFifoMeth.BindChannel)
+ {
+ _subChannels[meth.SubChannel] = (ClassId)meth.Argument;
+ }
+ else if (meth.Method < 0x60)
+ {
+ switch ((NvGpuFifoMeth)meth.Method)
+ {
+ case NvGpuFifoMeth.WaitForIdle:
+ {
+ _context.Renderer.FlushPipelines();
+
+ break;
+ }
+
+ case NvGpuFifoMeth.SetMacroUploadAddress:
+ {
+ _currMacroPosition = meth.Argument;
+
+ break;
+ }
+
+ case NvGpuFifoMeth.SendMacroCodeData:
+ {
+ _mme[_currMacroPosition++] = meth.Argument;
+
+ break;
+ }
+
+ case NvGpuFifoMeth.SetMacroBindingIndex:
+ {
+ _currMacroBindIndex = meth.Argument;
+
+ break;
+ }
+
+ case NvGpuFifoMeth.BindMacro:
+ {
+ int position = meth.Argument;
+
+ _macros[_currMacroBindIndex++] = new CachedMacro(_context, this, position);
+
+ break;
+ }
+ }
+ }
+ else if (meth.Method < 0xe00)
+ {
+ _context.State.CallMethod(meth);
+ }
+ else
+ {
+ int macroIndex = (meth.Method >> 1) & MacroIndexMask;
+
+ if ((meth.Method & 1) != 0)
+ {
+ _macros[macroIndex].PushArgument(meth.Argument);
+ }
+ else
+ {
+ _macros[macroIndex].StartExecution(meth.Argument);
+ }
+
+ if (meth.IsLastCall)
+ {
+ _macros[macroIndex].Execute(_mme);
+
+ _context.Methods.PerformDeferredDraws();
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Graphics3d/NvGpuFifoMeth.cs b/Ryujinx.Graphics.Gpu/NvGpuFifoMeth.cs
similarity index 76%
rename from Ryujinx.Graphics/Graphics3d/NvGpuFifoMeth.cs
rename to Ryujinx.Graphics.Gpu/NvGpuFifoMeth.cs
index 9bf528b3f..09aaa6c3b 100644
--- a/Ryujinx.Graphics/Graphics3d/NvGpuFifoMeth.cs
+++ b/Ryujinx.Graphics.Gpu/NvGpuFifoMeth.cs
@@ -1,8 +1,9 @@
-namespace Ryujinx.Graphics.Graphics3d
+namespace Ryujinx.Graphics.Gpu
{
enum NvGpuFifoMeth
{
BindChannel = 0,
+ WaitForIdle = 0x44,
SetMacroUploadAddress = 0x45,
SendMacroCodeData = 0x46,
SetMacroBindingIndex = 0x47,
diff --git a/Ryujinx.Graphics.Gpu/Ryujinx.Graphics.Gpu.csproj b/Ryujinx.Graphics.Gpu/Ryujinx.Graphics.Gpu.csproj
new file mode 100644
index 000000000..88761ddff
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/Ryujinx.Graphics.Gpu.csproj
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+ netcoreapp3.0
+
+
+
diff --git a/Ryujinx.Graphics.Gpu/State/BlendState.cs b/Ryujinx.Graphics.Gpu/State/BlendState.cs
new file mode 100644
index 000000000..cf22dc1b0
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/BlendState.cs
@@ -0,0 +1,15 @@
+using Ryujinx.Graphics.GAL.Blend;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct BlendState
+ {
+ public Bool SeparateAlpha;
+ public BlendOp ColorOp;
+ public BlendFactor ColorSrcFactor;
+ public BlendFactor ColorDstFactor;
+ public BlendOp AlphaOp;
+ public BlendFactor AlphaSrcFactor;
+ public BlendFactor AlphaDstFactor;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/Bool.cs b/Ryujinx.Graphics.Gpu/State/Bool.cs
new file mode 100644
index 000000000..8aadcfcc9
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/Bool.cs
@@ -0,0 +1,17 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct Bool
+ {
+ private uint _value;
+
+ public bool IsTrue()
+ {
+ return (_value & 1) != 0;
+ }
+
+ public bool IsFalse()
+ {
+ return (_value & 1) == 0;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/ClearColors.cs b/Ryujinx.Graphics.Gpu/State/ClearColors.cs
new file mode 100644
index 000000000..584c4791d
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ClearColors.cs
@@ -0,0 +1,10 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct ClearColors
+ {
+ public float Red;
+ public float Green;
+ public float Blue;
+ public float Alpha;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/Condition.cs b/Ryujinx.Graphics.Gpu/State/Condition.cs
new file mode 100644
index 000000000..41cce5197
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/Condition.cs
@@ -0,0 +1,11 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum Condition
+ {
+ Never,
+ Always,
+ ResultNonZero,
+ Equal,
+ NotEqual
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/ConditionState.cs b/Ryujinx.Graphics.Gpu/State/ConditionState.cs
new file mode 100644
index 000000000..24302c607
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ConditionState.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct ConditionState
+ {
+ public GpuVa Address;
+ public Condition Condition;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/CopyBufferParams.cs b/Ryujinx.Graphics.Gpu/State/CopyBufferParams.cs
new file mode 100644
index 000000000..2876dedd6
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/CopyBufferParams.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct CopyBufferParams
+ {
+ public GpuVa SrcAddress;
+ public GpuVa DstAddress;
+ public int SrcStride;
+ public int DstStride;
+ public int XCount;
+ public int YCount;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/CopyBufferSwizzle.cs b/Ryujinx.Graphics.Gpu/State/CopyBufferSwizzle.cs
new file mode 100644
index 000000000..24071372e
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/CopyBufferSwizzle.cs
@@ -0,0 +1,22 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct CopyBufferSwizzle
+ {
+ public uint Swizzle;
+
+ public int UnpackComponentSize()
+ {
+ return (int)((Swizzle >> 16) & 3) + 1;
+ }
+
+ public int UnpackSrcComponentsCount()
+ {
+ return (int)((Swizzle >> 20) & 7) + 1;
+ }
+
+ public int UnpackDstComponentsCount()
+ {
+ return (int)((Swizzle >> 24) & 7) + 1;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/CopyBufferTexture.cs b/Ryujinx.Graphics.Gpu/State/CopyBufferTexture.cs
new file mode 100644
index 000000000..cb63c607d
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/CopyBufferTexture.cs
@@ -0,0 +1,13 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct CopyBufferTexture
+ {
+ public MemoryLayout MemoryLayout;
+ public int Width;
+ public int Height;
+ public int Depth;
+ public int RegionZ;
+ public ushort RegionX;
+ public ushort RegionY;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/CopyRegion.cs b/Ryujinx.Graphics.Gpu/State/CopyRegion.cs
new file mode 100644
index 000000000..cad9a5db8
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/CopyRegion.cs
@@ -0,0 +1,14 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct CopyRegion
+ {
+ public int DstX;
+ public int DstY;
+ public int DstWidth;
+ public int DstHeight;
+ public long SrcWidthRF;
+ public long SrcHeightRF;
+ public long SrcXF;
+ public long SrcYF;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/CopyTexture.cs b/Ryujinx.Graphics.Gpu/State/CopyTexture.cs
new file mode 100644
index 000000000..363d84a2b
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/CopyTexture.cs
@@ -0,0 +1,15 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct CopyTexture
+ {
+ public RtFormat Format;
+ public bool LinearLayout;
+ public MemoryLayout MemoryLayout;
+ public int Depth;
+ public int Layer;
+ public int Stride;
+ public int Width;
+ public int Height;
+ public GpuVa Address;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/CopyTextureControl.cs b/Ryujinx.Graphics.Gpu/State/CopyTextureControl.cs
new file mode 100644
index 000000000..c49cf2765
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/CopyTextureControl.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct CopyTextureControl
+ {
+ public uint Packed;
+
+ public bool UnpackLinearFilter()
+ {
+ return (Packed & (1u << 4)) != 0;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/DepthBiasState.cs b/Ryujinx.Graphics.Gpu/State/DepthBiasState.cs
new file mode 100644
index 000000000..c88d27dda
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/DepthBiasState.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct DepthBiasState
+ {
+ public Bool PointEnable;
+ public Bool LineEnable;
+ public Bool FillEnable;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/FaceState.cs b/Ryujinx.Graphics.Gpu/State/FaceState.cs
new file mode 100644
index 000000000..53763032b
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/FaceState.cs
@@ -0,0 +1,11 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct FaceState
+ {
+ public Bool CullEnable;
+ public FrontFace FrontFace;
+ public Face CullFace;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/GpuState.cs b/Ryujinx.Graphics.Gpu/State/GpuState.cs
new file mode 100644
index 000000000..4e4241ca8
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/GpuState.cs
@@ -0,0 +1,425 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Gpu.Image;
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ class GpuState
+ {
+ private const int RegistersCount = 0xe00;
+
+ public delegate void MethodCallback(int argument);
+
+ private int[] _backingMemory;
+
+ private struct Register
+ {
+ public MethodCallback Callback;
+
+ public StateWriteFlags WriteFlag;
+ }
+
+ private Register[] _registers;
+
+ public StateWriteFlags StateWriteFlags { get; set; }
+
+ public GpuState()
+ {
+ _backingMemory = new int[RegistersCount];
+
+ _registers = new Register[RegistersCount];
+
+ StateWriteFlags = StateWriteFlags.Any;
+
+ InitializeDefaultState();
+ InitializeStateWatchers();
+ }
+
+ public bool ExitEarly;
+
+ public void CallMethod(MethodParams meth)
+ {
+ if (ExitEarly)
+ {
+ return;
+ }
+
+ Register register = _registers[meth.Method];
+
+ if (_backingMemory[meth.Method] != meth.Argument)
+ {
+ StateWriteFlags |= register.WriteFlag;
+ }
+
+ _backingMemory[meth.Method] = meth.Argument;
+
+ MethodCallback callback = register.Callback;
+
+ if (callback != null)
+ {
+ callback(meth.Argument);
+ }
+ }
+
+ public int Read(int offset)
+ {
+ return _backingMemory[offset];
+ }
+
+ public void RegisterCopyBufferCallback(MethodCallback callback)
+ {
+ RegisterCallback(0xc0, callback);
+ }
+
+ public void RegisterCopyTextureCallback(MethodCallback callback)
+ {
+ RegisterCallback(0x237, callback);
+ }
+
+ public void RegisterDrawEndCallback(MethodCallback callback)
+ {
+ RegisterCallback(0x585, callback);
+ }
+
+ public void RegisterDrawBeginCallback(MethodCallback callback)
+ {
+ RegisterCallback(0x586, callback);
+ }
+
+ public void RegisterSetIndexCountCallback(MethodCallback callback)
+ {
+ RegisterCallback(0x5f8, callback);
+ }
+
+ public void RegisterClearCallback(MethodCallback callback)
+ {
+ RegisterCallback(0x674, callback);
+ }
+
+ public void RegisterReportCallback(MethodCallback callback)
+ {
+ RegisterCallback(0x6c3, callback);
+ }
+
+ public void RegisterUniformBufferUpdateCallback(MethodCallback callback)
+ {
+ for (int index = 0; index < 16; index++)
+ {
+ RegisterCallback(0x8e4 + index, callback);
+ }
+ }
+
+ public void RegisterUniformBufferBind0Callback(MethodCallback callback)
+ {
+ RegisterCallback(0x904, callback);
+ }
+
+ public void RegisterUniformBufferBind1Callback(MethodCallback callback)
+ {
+ RegisterCallback(0x90c, callback);
+ }
+
+ public void RegisterUniformBufferBind2Callback(MethodCallback callback)
+ {
+ RegisterCallback(0x914, callback);
+ }
+
+ public void RegisterUniformBufferBind3Callback(MethodCallback callback)
+ {
+ RegisterCallback(0x91c, callback);
+ }
+
+ public void RegisterUniformBufferBind4Callback(MethodCallback callback)
+ {
+ RegisterCallback(0x924, callback);
+ }
+
+ public CopyTexture GetCopyDstTexture()
+ {
+ return Get(MethodOffset.CopyDstTexture);
+ }
+
+ public CopyTexture GetCopySrcTexture()
+ {
+ return Get(MethodOffset.CopySrcTexture);
+ }
+
+ public RtColorState GetRtColorState(int index)
+ {
+ return Get(MethodOffset.RtColorState + 16 * index);
+ }
+
+ public CopyTextureControl GetCopyTextureControl()
+ {
+ return Get(MethodOffset.CopyTextureControl);
+ }
+
+ public CopyRegion GetCopyRegion()
+ {
+ return Get(MethodOffset.CopyRegion);
+ }
+
+ public ViewportTransform GetViewportTransform(int index)
+ {
+ return Get(MethodOffset.ViewportTransform + 8 * index);
+ }
+
+ public ViewportExtents GetViewportExtents(int index)
+ {
+ return Get(MethodOffset.ViewportExtents + 4 * index);
+ }
+
+ public VertexBufferDrawState GetVertexBufferDrawState()
+ {
+ return Get(MethodOffset.VertexBufferDrawState);
+ }
+
+ public ClearColors GetClearColors()
+ {
+ return Get(MethodOffset.ClearColors);
+ }
+
+ public float GetClearDepthValue()
+ {
+ return Get(MethodOffset.ClearDepthValue);
+ }
+
+ public int GetClearStencilValue()
+ {
+ return _backingMemory[(int)MethodOffset.ClearStencilValue];
+ }
+
+ public StencilBackMasks GetStencilBackMasks()
+ {
+ return Get(MethodOffset.StencilBackMasks);
+ }
+
+ public RtDepthStencilState GetRtDepthStencilState()
+ {
+ return Get(MethodOffset.RtDepthStencilState);
+ }
+
+ public VertexAttribState GetVertexAttribState(int index)
+ {
+ return Get(MethodOffset.VertexAttribState + index);
+ }
+
+ public Size3D GetRtDepthStencilSize()
+ {
+ return Get(MethodOffset.RtDepthStencilSize);
+ }
+
+ public Bool GetDepthTestEnable()
+ {
+ return Get(MethodOffset.DepthTestEnable);
+ }
+
+ public CompareOp GetDepthTestFunc()
+ {
+ return Get(MethodOffset.DepthTestFunc);
+ }
+
+ public Bool GetDepthWriteEnable()
+ {
+ return Get(MethodOffset.DepthWriteEnable);
+ }
+
+ public Bool GetBlendEnable(int index)
+ {
+ return Get(MethodOffset.BlendEnable + index);
+ }
+
+ public StencilTestState GetStencilTestState()
+ {
+ return Get(MethodOffset.StencilTestState);
+ }
+
+ public int GetBaseVertex()
+ {
+ return _backingMemory[(int)MethodOffset.FirstVertex];
+ }
+
+ public int GetBaseInstance()
+ {
+ return _backingMemory[(int)MethodOffset.FirstInstance];
+ }
+
+ public PoolState GetSamplerPoolState()
+ {
+ return Get(MethodOffset.SamplerPoolState);
+ }
+
+ public PoolState GetTexturePoolState()
+ {
+ return Get(MethodOffset.TexturePoolState);
+ }
+
+ public StencilBackTestState GetStencilBackTestState()
+ {
+ return Get(MethodOffset.StencilBackTestState);
+ }
+
+ public TextureMsaaMode GetRtMsaaMode()
+ {
+ return Get(MethodOffset.RtMsaaMode);
+ }
+
+ public GpuVa GetShaderBaseAddress()
+ {
+ return Get(MethodOffset.ShaderBaseAddress);
+ }
+
+ public PrimitiveRestartState GetPrimitiveRestartState()
+ {
+ return Get(MethodOffset.PrimitiveRestartState);
+ }
+
+ public IndexBufferState GetIndexBufferState()
+ {
+ return Get(MethodOffset.IndexBufferState);
+ }
+
+ public FaceState GetFaceState()
+ {
+ return Get(MethodOffset.FaceState);
+ }
+
+ public ReportState GetReportState()
+ {
+ return Get(MethodOffset.ReportState);
+ }
+
+ public VertexBufferState GetVertexBufferState(int index)
+ {
+ return Get(MethodOffset.VertexBufferState + 4 * index);
+ }
+
+ public BlendState GetBlendState(int index)
+ {
+ return Get(MethodOffset.BlendState + 8 * index);
+ }
+
+ public GpuVa GetVertexBufferEndAddress(int index)
+ {
+ return Get(MethodOffset.VertexBufferEndAddress + 2 * index);
+ }
+
+ public ShaderState GetShaderState(int index)
+ {
+ return Get(MethodOffset.ShaderState + 16 * index);
+ }
+
+ public UniformBufferState GetUniformBufferState()
+ {
+ return Get(MethodOffset.UniformBufferState);
+ }
+
+ public void SetUniformBufferOffset(int offset)
+ {
+ _backingMemory[(int)MethodOffset.UniformBufferState + 3] = offset;
+ }
+
+ public int GetTextureBufferIndex()
+ {
+ return _backingMemory[(int)MethodOffset.TextureBufferIndex];
+ }
+
+ private void InitializeDefaultState()
+ {
+ // Depth ranges.
+ for (int index = 0; index < 8; index++)
+ {
+ _backingMemory[(int)MethodOffset.ViewportExtents + index * 4 + 2] = 0;
+ _backingMemory[(int)MethodOffset.ViewportExtents + index * 4 + 3] = 0x3F800000;
+ }
+
+ // Default front stencil mask.
+ _backingMemory[0x4e7] = 0xff;
+
+ // Default color mask.
+ _backingMemory[(int)MethodOffset.RtColorMask] = 0x1111;
+ }
+
+ private void InitializeStateWatchers()
+ {
+ SetWriteStateFlag(MethodOffset.RtColorState, StateWriteFlags.RtColorState, 16 * 8);
+
+ SetWriteStateFlag(MethodOffset.ViewportTransform, StateWriteFlags.ViewportTransform, 8 * 8);
+ SetWriteStateFlag(MethodOffset.ViewportExtents, StateWriteFlags.ViewportTransform, 4 * 8);
+
+ SetWriteStateFlag(MethodOffset.VertexBufferDrawState, StateWriteFlags.VertexBufferState);
+
+ SetWriteStateFlag(MethodOffset.DepthBiasState, StateWriteFlags.DepthBiasState);
+
+ SetWriteStateFlag(MethodOffset.DepthBiasFactor, StateWriteFlags.DepthBiasState, 1);
+ SetWriteStateFlag(MethodOffset.DepthBiasUnits, StateWriteFlags.DepthBiasState, 1);
+ SetWriteStateFlag(MethodOffset.DepthBiasClamp, StateWriteFlags.DepthBiasState, 1);
+
+ SetWriteStateFlag(MethodOffset.RtDepthStencilState, StateWriteFlags.RtDepthStencilState);
+ SetWriteStateFlag (MethodOffset.RtDepthStencilSize, StateWriteFlags.RtDepthStencilState);
+
+ SetWriteStateFlag(MethodOffset.DepthTestEnable, StateWriteFlags.DepthTestState, 1);
+ SetWriteStateFlag(MethodOffset.DepthWriteEnable, StateWriteFlags.DepthTestState, 1);
+ SetWriteStateFlag(MethodOffset.DepthTestFunc, StateWriteFlags.DepthTestState, 1);
+
+ SetWriteStateFlag(MethodOffset.VertexAttribState, StateWriteFlags.VertexAttribState, 16);
+
+ SetWriteStateFlag (MethodOffset.StencilBackMasks, StateWriteFlags.StencilTestState);
+ SetWriteStateFlag (MethodOffset.StencilTestState, StateWriteFlags.StencilTestState);
+ SetWriteStateFlag(MethodOffset.StencilBackTestState, StateWriteFlags.StencilTestState);
+
+ SetWriteStateFlag(MethodOffset.SamplerPoolState, StateWriteFlags.SamplerPoolState);
+ SetWriteStateFlag(MethodOffset.TexturePoolState, StateWriteFlags.TexturePoolState);
+
+ SetWriteStateFlag(MethodOffset.ShaderBaseAddress, StateWriteFlags.ShaderState);
+
+ SetWriteStateFlag(MethodOffset.PrimitiveRestartState, StateWriteFlags.PrimitiveRestartState);
+
+ SetWriteStateFlag(MethodOffset.IndexBufferState, StateWriteFlags.IndexBufferState);
+
+ SetWriteStateFlag(MethodOffset.FaceState, StateWriteFlags.FaceState);
+
+ SetWriteStateFlag(MethodOffset.RtColorMask, StateWriteFlags.RtColorMask);
+
+ SetWriteStateFlag(MethodOffset.VertexBufferInstanced, StateWriteFlags.VertexBufferState, 16);
+ SetWriteStateFlag(MethodOffset.VertexBufferState, StateWriteFlags.VertexBufferState, 4 * 16);
+ SetWriteStateFlag(MethodOffset.VertexBufferEndAddress, StateWriteFlags.VertexBufferState, 2 * 16);
+
+ SetWriteStateFlag(MethodOffset.BlendEnable, StateWriteFlags.BlendState, 8);
+ SetWriteStateFlag(MethodOffset.BlendState, StateWriteFlags.BlendState, 8 * 8);
+
+ SetWriteStateFlag(MethodOffset.ShaderState, StateWriteFlags.ShaderState, 16 * 6);
+
+ SetWriteStateFlag(MethodOffset.TextureBufferIndex, StateWriteFlags.TexturePoolState, 1);
+ }
+
+ private void SetWriteStateFlag(MethodOffset offset, StateWriteFlags flag)
+ {
+ SetWriteStateFlag(offset, flag, Marshal.SizeOf());
+ }
+
+ private void SetWriteStateFlag(MethodOffset offset, StateWriteFlags flag, int size)
+ {
+ for (int index = 0; index < size; index++)
+ {
+ _registers[(int)offset + index].WriteFlag = flag;
+ }
+ }
+
+ public void RegisterCallback(MethodOffset offset, MethodCallback callback)
+ {
+ _registers[(int)offset].Callback = callback;
+ }
+
+ private void RegisterCallback(int offset, MethodCallback callback)
+ {
+ _registers[offset].Callback = callback;
+ }
+
+ public T Get(MethodOffset offset) where T : struct
+ {
+ return MemoryMarshal.Cast(_backingMemory.AsSpan().Slice((int)offset))[0];
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/GpuVa.cs b/Ryujinx.Graphics.Gpu/State/GpuVa.cs
new file mode 100644
index 000000000..01ad70b7c
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/GpuVa.cs
@@ -0,0 +1,18 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct GpuVa
+ {
+ public uint High;
+ public uint Low;
+
+ public ulong Pack()
+ {
+ return Low | ((ulong)High << 32);
+ }
+
+ public bool IsNullPtr()
+ {
+ return (Low | High) == 0;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/IndexBufferState.cs b/Ryujinx.Graphics.Gpu/State/IndexBufferState.cs
new file mode 100644
index 000000000..8a07bb520
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/IndexBufferState.cs
@@ -0,0 +1,13 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct IndexBufferState
+ {
+ public GpuVa Address;
+ public GpuVa EndAddress;
+ public IndexType Type;
+ public int First;
+ public int Count;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/Inline2MemoryParams.cs b/Ryujinx.Graphics.Gpu/State/Inline2MemoryParams.cs
new file mode 100644
index 000000000..10d249002
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/Inline2MemoryParams.cs
@@ -0,0 +1,17 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct Inline2MemoryParams
+ {
+ public int LineLengthIn;
+ public int LineCount;
+ public GpuVa DstAddress;
+ public int DstStride;
+ public MemoryLayout DstMemoryLayout;
+ public int DstWidth;
+ public int DstHeight;
+ public int DstDepth;
+ public int DstZ;
+ public int DstX;
+ public int DstY;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/MemoryLayout.cs b/Ryujinx.Graphics.Gpu/State/MemoryLayout.cs
new file mode 100644
index 000000000..8e53a36a1
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/MemoryLayout.cs
@@ -0,0 +1,32 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct MemoryLayout
+ {
+ public uint Packed;
+
+ public int UnpackGobBlocksInX()
+ {
+ return 1 << (int)(Packed & 0xf);
+ }
+
+ public int UnpackGobBlocksInY()
+ {
+ return 1 << (int)((Packed >> 4) & 0xf);
+ }
+
+ public int UnpackGobBlocksInZ()
+ {
+ return 1 << (int)((Packed >> 8) & 0xf);
+ }
+
+ public bool UnpackIsLinear()
+ {
+ return (Packed & 0x1000) != 0;
+ }
+
+ public bool UnpackIsTarget3D()
+ {
+ return (Packed & 0x10000) != 0;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/MethodOffset.cs b/Ryujinx.Graphics.Gpu/State/MethodOffset.cs
new file mode 100644
index 000000000..91dffe9f3
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/MethodOffset.cs
@@ -0,0 +1,62 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum MethodOffset
+ {
+ Inline2MemoryParams = 0x60,
+ Inline2MemoryExecute = 0x6c,
+ Inline2MemoryPushData = 0x6d,
+ CopyDstTexture = 0x80,
+ CopySrcTexture = 0x8c,
+ DispatchParamsAddress = 0xad,
+ Dispatch = 0xaf,
+ CopyBufferParams = 0x100,
+ CopyBufferSwizzle = 0x1c2,
+ CopyBufferDstTexture = 0x1c3,
+ CopyBufferSrcTexture = 0x1ca,
+ RtColorState = 0x200,
+ CopyTextureControl = 0x223,
+ CopyRegion = 0x22c,
+ ViewportTransform = 0x280,
+ ViewportExtents = 0x300,
+ VertexBufferDrawState = 0x35d,
+ ClearColors = 0x360,
+ ClearDepthValue = 0x364,
+ ClearStencilValue = 0x368,
+ DepthBiasState = 0x370,
+ StencilBackMasks = 0x3d5,
+ InvalidateTextures = 0x3dd,
+ RtDepthStencilState = 0x3f8,
+ VertexAttribState = 0x458,
+ RtDepthStencilSize = 0x48a,
+ DepthTestEnable = 0x4b3,
+ DepthWriteEnable = 0x4ba,
+ DepthTestFunc = 0x4c3,
+ BlendEnable = 0x4d8,
+ StencilTestState = 0x4e0,
+ FirstVertex = 0x50d,
+ FirstInstance = 0x50e,
+ ResetCounter = 0x54c,
+ RtDepthStencilEnable = 0x54e,
+ ConditionState = 0x554,
+ SamplerPoolState = 0x557,
+ DepthBiasFactor = 0x55b,
+ TexturePoolState = 0x55d,
+ StencilBackTestState = 0x565,
+ DepthBiasUnits = 0x56f,
+ RtMsaaMode = 0x574,
+ ShaderBaseAddress = 0x582,
+ PrimitiveRestartState = 0x591,
+ IndexBufferState = 0x5f2,
+ DepthBiasClamp = 0x61f,
+ VertexBufferInstanced = 0x620,
+ FaceState = 0x646,
+ RtColorMask = 0x680,
+ ReportState = 0x6c0,
+ VertexBufferState = 0x700,
+ BlendState = 0x780,
+ VertexBufferEndAddress = 0x7c0,
+ ShaderState = 0x800,
+ UniformBufferState = 0x8e0,
+ TextureBufferIndex = 0x982
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/PoolState.cs b/Ryujinx.Graphics.Gpu/State/PoolState.cs
new file mode 100644
index 000000000..3d51eb7e5
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/PoolState.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct PoolState
+ {
+ public GpuVa Address;
+ public int MaximumId;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/PrimitiveRestartState.cs b/Ryujinx.Graphics.Gpu/State/PrimitiveRestartState.cs
new file mode 100644
index 000000000..21405be78
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/PrimitiveRestartState.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct PrimitiveRestartState
+ {
+ public bool Enable;
+ public int Index;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/PrimitiveTopology.cs b/Ryujinx.Graphics.Gpu/State/PrimitiveTopology.cs
new file mode 100644
index 000000000..02df9ac16
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/PrimitiveTopology.cs
@@ -0,0 +1,50 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum PrimitiveType
+ {
+ Points,
+ Lines,
+ LineLoop,
+ LineStrip,
+ Triangles,
+ TriangleStrip,
+ TriangleFan,
+ Quads,
+ QuadStrip,
+ Polygon,
+ LinesAdjacency,
+ LineStripAdjacency,
+ TrianglesAdjacency,
+ TriangleStripAdjacency,
+ Patches
+ }
+
+ static class PrimitiveTypeConverter
+ {
+ public static PrimitiveTopology Convert(this PrimitiveType topology)
+ {
+ switch (topology)
+ {
+ case PrimitiveType.Points: return PrimitiveTopology.Points;
+ case PrimitiveType.Lines: return PrimitiveTopology.Lines;
+ case PrimitiveType.LineLoop: return PrimitiveTopology.LineLoop;
+ case PrimitiveType.LineStrip: return PrimitiveTopology.LineStrip;
+ case PrimitiveType.Triangles: return PrimitiveTopology.Triangles;
+ case PrimitiveType.TriangleStrip: return PrimitiveTopology.TriangleStrip;
+ case PrimitiveType.TriangleFan: return PrimitiveTopology.TriangleFan;
+ case PrimitiveType.Quads: return PrimitiveTopology.Quads;
+ case PrimitiveType.QuadStrip: return PrimitiveTopology.QuadStrip;
+ case PrimitiveType.Polygon: return PrimitiveTopology.Polygon;
+ case PrimitiveType.LinesAdjacency: return PrimitiveTopology.LinesAdjacency;
+ case PrimitiveType.LineStripAdjacency: return PrimitiveTopology.LineStripAdjacency;
+ case PrimitiveType.TrianglesAdjacency: return PrimitiveTopology.TrianglesAdjacency;
+ case PrimitiveType.TriangleStripAdjacency: return PrimitiveTopology.TriangleStripAdjacency;
+ case PrimitiveType.Patches: return PrimitiveTopology.Patches;
+ }
+
+ return PrimitiveTopology.Triangles;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/ReportCounterType.cs b/Ryujinx.Graphics.Gpu/State/ReportCounterType.cs
new file mode 100644
index 000000000..38a0de711
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ReportCounterType.cs
@@ -0,0 +1,25 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum ReportCounterType
+ {
+ Zero = 0,
+ InputVertices = 1,
+ InputPrimitives = 3,
+ VertexShaderInvocations = 5,
+ GeometryShaderInvocations = 7,
+ GeometryShaderPrimitives = 9,
+ TransformFeedbackPrimitivesWritten = 0xb,
+ ClipperInputPrimitives = 0xf,
+ ClipperOutputPrimitives = 0x11,
+ PrimitivesGenerated = 0x12,
+ FragmentShaderInvocations = 0x13,
+ SamplesPassed = 0x15,
+ TessControlShaderInvocations = 0x1b,
+ TessEvaluationShaderInvocations = 0x1d,
+ TessEvaluationShaderPrimitives = 0x1f,
+ ZcullStats0 = 0x2a,
+ ZcullStats1 = 0x2c,
+ ZcullStats2 = 0x2e,
+ ZcullStats3 = 0x30
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/ReportMode.cs b/Ryujinx.Graphics.Gpu/State/ReportMode.cs
new file mode 100644
index 000000000..84af3d75f
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ReportMode.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum ReportMode
+ {
+ Semaphore = 0,
+ Counter = 2
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/ReportState.cs b/Ryujinx.Graphics.Gpu/State/ReportState.cs
new file mode 100644
index 000000000..212281aa2
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ReportState.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct ReportState
+ {
+ public GpuVa Address;
+ public int Payload;
+ public uint Control;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/ResetCounterType.cs b/Ryujinx.Graphics.Gpu/State/ResetCounterType.cs
new file mode 100644
index 000000000..49b3b6da0
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ResetCounterType.cs
@@ -0,0 +1,21 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum ResetCounterType
+ {
+ SamplesPassed = 1,
+ ZcullStats = 2,
+ TransformFeedbackPrimitivesWritten = 0x10,
+ InputVertices = 0x12,
+ InputPrimitives = 0x13,
+ VertexShaderInvocations = 0x15,
+ TessControlShaderInvocations = 0x16,
+ TessEvaluationShaderInvocations = 0x17,
+ TessEvaluationShaderPrimitives = 0x18,
+ GeometryShaderInvocations = 0x1a,
+ GeometryShaderPrimitives = 0x1b,
+ ClipperInputPrimitives = 0x1c,
+ ClipperOutputPrimitives = 0x1d,
+ FragmentShaderInvocations = 0x1e,
+ PrimitivesGenerated = 0x1f
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/RtColorMask.cs b/Ryujinx.Graphics.Gpu/State/RtColorMask.cs
new file mode 100644
index 000000000..5992673f6
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/RtColorMask.cs
@@ -0,0 +1,27 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct RtColorMask
+ {
+ public uint Packed;
+
+ public bool UnpackRed()
+ {
+ return (Packed & 0x1) != 0;
+ }
+
+ public bool UnpackGreen()
+ {
+ return (Packed & 0x10) != 0;
+ }
+
+ public bool UnpackBlue()
+ {
+ return (Packed & 0x100) != 0;
+ }
+
+ public bool UnpackAlpha()
+ {
+ return (Packed & 0x1000) != 0;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/RtColorState.cs b/Ryujinx.Graphics.Gpu/State/RtColorState.cs
new file mode 100644
index 000000000..bb6ae208d
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/RtColorState.cs
@@ -0,0 +1,13 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct RtColorState
+ {
+ public GpuVa Address;
+ public int WidthOrStride;
+ public int Height;
+ public RtFormat Format;
+ public MemoryLayout MemoryLayout;
+ public int Depth;
+ public int LayerSize;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/RtDepthStencilState.cs b/Ryujinx.Graphics.Gpu/State/RtDepthStencilState.cs
new file mode 100644
index 000000000..bfa812cb9
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/RtDepthStencilState.cs
@@ -0,0 +1,10 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct RtDepthStencilState
+ {
+ public GpuVa Address;
+ public RtFormat Format;
+ public MemoryLayout MemoryLayout;
+ public int LayerSize;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/RtFormat.cs b/Ryujinx.Graphics.Gpu/State/RtFormat.cs
new file mode 100644
index 000000000..960da445e
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/RtFormat.cs
@@ -0,0 +1,137 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Gpu.Image;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum RtFormat
+ {
+ D32Float = 0xa,
+ D16Unorm = 0x13,
+ D24UnormS8Uint = 0x14,
+ S8Uint = 0x17,
+ D32FloatS8Uint = 0x19,
+ R32G32B32A32Float = 0xc0,
+ R32G32B32A32Sint = 0xc1,
+ R32G32B32A32Uint = 0xc2,
+ R32G32B32X32Float = 0xc3,
+ R32G32B32X32Sint = 0xc4,
+ R32G32B32X32Uint = 0xc5,
+ R16G16B16X16Unorm = 0xc6,
+ R16G16B16X16Snorm = 0xc7,
+ R16G16B16X16Sint = 0xc8,
+ R16G16B16X16Uint = 0xc9,
+ R16G16B16A16Float = 0xca,
+ R32G32Float = 0xcb,
+ R32G32Sint = 0xcc,
+ R32G32Uint = 0xcd,
+ R16G16B16X16Float = 0xce,
+ B8G8R8A8Unorm = 0xcf,
+ B8G8R8A8Srgb = 0xd0,
+ R10G10B10A2Unorm = 0xd1,
+ R10G10B10A2Uint = 0xd2,
+ R8G8B8A8Unorm = 0xd5,
+ R8G8B8A8Srgb = 0xd6,
+ R8G8B8X8Snorm = 0xd7,
+ R8G8B8X8Sint = 0xd8,
+ R8G8B8X8Uint = 0xd9,
+ R16G16Unorm = 0xda,
+ R16G16Snorm = 0xdb,
+ R16G16Sint = 0xdc,
+ R16G16Uint = 0xdd,
+ R16G16Float = 0xde,
+ R11G11B10Float = 0xe0,
+ R32Sint = 0xe3,
+ R32Uint = 0xe4,
+ R32Float = 0xe5,
+ B8G8R8X8Unorm = 0xe6,
+ B8G8R8X8Srgb = 0xe7,
+ B5G6R5Unorm = 0xe8,
+ B5G5R5A1Unorm = 0xe9,
+ R8G8Unorm = 0xea,
+ R8G8Snorm = 0xeb,
+ R8G8Sint = 0xec,
+ R8G8Uint = 0xed,
+ R16Unorm = 0xee,
+ R16Snorm = 0xef,
+ R16Sint = 0xf0,
+ R16Uint = 0xf1,
+ R16Float = 0xf2,
+ R8Unorm = 0xf3,
+ R8Snorm = 0xf4,
+ R8Sint = 0xf5,
+ R8Uint = 0xf6,
+ B5G5R5X1Unorm = 0xf8,
+ R8G8B8X8Unorm = 0xf9,
+ R8G8B8X8Srgb = 0xfa
+ }
+
+ static class RtFormatConverter
+ {
+ public static FormatInfo Convert(this RtFormat format)
+ {
+ switch (format)
+ {
+ case RtFormat.D32Float: return new FormatInfo(Format.D32Float, 1, 1, 4);
+ case RtFormat.D16Unorm: return new FormatInfo(Format.D16Unorm, 1, 1, 2);
+ case RtFormat.D24UnormS8Uint: return new FormatInfo(Format.D24UnormS8Uint, 1, 1, 4);
+ case RtFormat.S8Uint: return new FormatInfo(Format.S8Uint, 1, 1, 1);
+ case RtFormat.D32FloatS8Uint: return new FormatInfo(Format.D32FloatS8Uint, 1, 1, 8);
+ case RtFormat.R32G32B32A32Float: return new FormatInfo(Format.R32G32B32A32Float, 1, 1, 16);
+ case RtFormat.R32G32B32A32Sint: return new FormatInfo(Format.R32G32B32A32Sint, 1, 1, 16);
+ case RtFormat.R32G32B32A32Uint: return new FormatInfo(Format.R32G32B32A32Uint, 1, 1, 16);
+ case RtFormat.R32G32B32X32Float: return new FormatInfo(Format.R32G32B32A32Float, 1, 1, 16);
+ case RtFormat.R32G32B32X32Sint: return new FormatInfo(Format.R32G32B32A32Sint, 1, 1, 16);
+ case RtFormat.R32G32B32X32Uint: return new FormatInfo(Format.R32G32B32A32Uint, 1, 1, 16);
+ case RtFormat.R16G16B16X16Unorm: return new FormatInfo(Format.R16G16B16A16Unorm, 1, 1, 8);
+ case RtFormat.R16G16B16X16Snorm: return new FormatInfo(Format.R16G16B16A16Snorm, 1, 1, 8);
+ case RtFormat.R16G16B16X16Sint: return new FormatInfo(Format.R16G16B16A16Sint, 1, 1, 8);
+ case RtFormat.R16G16B16X16Uint: return new FormatInfo(Format.R16G16B16A16Uint, 1, 1, 8);
+ case RtFormat.R16G16B16A16Float: return new FormatInfo(Format.R16G16B16A16Float, 1, 1, 8);
+ case RtFormat.R32G32Float: return new FormatInfo(Format.R32G32Float, 1, 1, 8);
+ case RtFormat.R32G32Sint: return new FormatInfo(Format.R32G32Sint, 1, 1, 8);
+ case RtFormat.R32G32Uint: return new FormatInfo(Format.R32G32Uint, 1, 1, 8);
+ case RtFormat.R16G16B16X16Float: return new FormatInfo(Format.R16G16B16A16Float, 1, 1, 8);
+ case RtFormat.B8G8R8A8Unorm: return new FormatInfo(Format.B8G8R8A8Unorm, 1, 1, 4);
+ case RtFormat.B8G8R8A8Srgb: return new FormatInfo(Format.B8G8R8A8Srgb, 1, 1, 4);
+ case RtFormat.R10G10B10A2Unorm: return new FormatInfo(Format.R10G10B10A2Unorm, 1, 1, 4);
+ case RtFormat.R10G10B10A2Uint: return new FormatInfo(Format.R10G10B10A2Uint, 1, 1, 4);
+ case RtFormat.R8G8B8A8Unorm: return new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4);
+ case RtFormat.R8G8B8A8Srgb: return new FormatInfo(Format.R8G8B8A8Srgb, 1, 1, 4);
+ case RtFormat.R8G8B8X8Snorm: return new FormatInfo(Format.R8G8B8A8Snorm, 1, 1, 4);
+ case RtFormat.R8G8B8X8Sint: return new FormatInfo(Format.R8G8B8A8Sint, 1, 1, 4);
+ case RtFormat.R8G8B8X8Uint: return new FormatInfo(Format.R8G8B8A8Uint, 1, 1, 4);
+ case RtFormat.R16G16Unorm: return new FormatInfo(Format.R16G16Unorm, 1, 1, 4);
+ case RtFormat.R16G16Snorm: return new FormatInfo(Format.R16G16Snorm, 1, 1, 4);
+ case RtFormat.R16G16Sint: return new FormatInfo(Format.R16G16Sint, 1, 1, 4);
+ case RtFormat.R16G16Uint: return new FormatInfo(Format.R16G16Uint, 1, 1, 4);
+ case RtFormat.R16G16Float: return new FormatInfo(Format.R16G16Float, 1, 1, 4);
+ case RtFormat.R11G11B10Float: return new FormatInfo(Format.R11G11B10Float, 1, 1, 4);
+ case RtFormat.R32Sint: return new FormatInfo(Format.R32Sint, 1, 1, 4);
+ case RtFormat.R32Uint: return new FormatInfo(Format.R32Uint, 1, 1, 4);
+ case RtFormat.R32Float: return new FormatInfo(Format.R32Float, 1, 1, 4);
+ case RtFormat.B8G8R8X8Unorm: return new FormatInfo(Format.B8G8R8A8Unorm, 1, 1, 4);
+ case RtFormat.B8G8R8X8Srgb: return new FormatInfo(Format.B8G8R8A8Srgb, 1, 1, 4);
+ case RtFormat.B5G6R5Unorm: return new FormatInfo(Format.B5G6R5Unorm, 1, 1, 2);
+ case RtFormat.B5G5R5A1Unorm: return new FormatInfo(Format.B5G5R5A1Unorm, 1, 1, 2);
+ case RtFormat.R8G8Unorm: return new FormatInfo(Format.R8G8Unorm, 1, 1, 2);
+ case RtFormat.R8G8Snorm: return new FormatInfo(Format.R8G8Snorm, 1, 1, 2);
+ case RtFormat.R8G8Sint: return new FormatInfo(Format.R8G8Sint, 1, 1, 2);
+ case RtFormat.R8G8Uint: return new FormatInfo(Format.R8G8Uint, 1, 1, 2);
+ case RtFormat.R16Unorm: return new FormatInfo(Format.R16Unorm, 1, 1, 2);
+ case RtFormat.R16Snorm: return new FormatInfo(Format.R16Snorm, 1, 1, 2);
+ case RtFormat.R16Sint: return new FormatInfo(Format.R16Sint, 1, 1, 2);
+ case RtFormat.R16Uint: return new FormatInfo(Format.R16Uint, 1, 1, 2);
+ case RtFormat.R16Float: return new FormatInfo(Format.R16Float, 1, 1, 2);
+ case RtFormat.R8Unorm: return new FormatInfo(Format.R8Unorm, 1, 1, 1);
+ case RtFormat.R8Snorm: return new FormatInfo(Format.R8Snorm, 1, 1, 1);
+ case RtFormat.R8Sint: return new FormatInfo(Format.R8Sint, 1, 1, 1);
+ case RtFormat.R8Uint: return new FormatInfo(Format.R8Uint, 1, 1, 1);
+ case RtFormat.B5G5R5X1Unorm: return new FormatInfo(Format.B5G5R5X1Unorm, 1, 1, 2);
+ case RtFormat.R8G8B8X8Unorm: return new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4);
+ case RtFormat.R8G8B8X8Srgb: return new FormatInfo(Format.R8G8B8A8Srgb, 1, 1, 4);
+ }
+
+ return FormatInfo.Default;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Gpu/State/ShaderState.cs b/Ryujinx.Graphics.Gpu/State/ShaderState.cs
new file mode 100644
index 000000000..536d7dcfd
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ShaderState.cs
@@ -0,0 +1,19 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct ShaderState
+ {
+ public uint Control;
+ public uint Offset;
+ public uint Unknown0x8;
+ public int MaxRegisters;
+ public ShaderType Type;
+ public uint Unknown0x14;
+ public uint Unknown0x18;
+ public uint Unknown0x1c;
+
+ public bool UnpackEnable()
+ {
+ return (Control & 1) != 0;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/ShaderType.cs b/Ryujinx.Graphics.Gpu/State/ShaderType.cs
new file mode 100644
index 000000000..703159f4a
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ShaderType.cs
@@ -0,0 +1,11 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum ShaderType
+ {
+ Vertex,
+ TessellationControl,
+ TessellationEvaluation,
+ Geometry,
+ Fragment
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/Size3D.cs b/Ryujinx.Graphics.Gpu/State/Size3D.cs
new file mode 100644
index 000000000..827713897
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/Size3D.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct Size3D
+ {
+ public int Width;
+ public int Height;
+ public int Depth;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/StateWriteFlags.cs b/Ryujinx.Graphics.Gpu/State/StateWriteFlags.cs
new file mode 100644
index 000000000..32d5127a2
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/StateWriteFlags.cs
@@ -0,0 +1,34 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ enum StateWriteFlags
+ {
+ InputAssemblerGroup =
+ VertexAttribState |
+ PrimitiveRestartState |
+ IndexBufferState |
+ VertexBufferState,
+
+ RenderTargetGroup =
+ RtColorState |
+ RtDepthStencilState,
+
+ RtColorState = 1 << 0,
+ ViewportTransform = 1 << 1,
+ DepthBiasState = 1 << 2,
+ RtDepthStencilState = 1 << 3,
+ DepthTestState = 1 << 4,
+ VertexAttribState = 1 << 5,
+ StencilTestState = 1 << 6,
+ SamplerPoolState = 1 << 7,
+ TexturePoolState = 1 << 8,
+ PrimitiveRestartState = 1 << 9,
+ IndexBufferState = 1 << 10,
+ FaceState = 1 << 11,
+ RtColorMask = 1 << 12,
+ VertexBufferState = 1 << 13,
+ BlendState = 1 << 14,
+ ShaderState = 1 << 15,
+
+ Any = -1
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/StencilBackMasks.cs b/Ryujinx.Graphics.Gpu/State/StencilBackMasks.cs
new file mode 100644
index 000000000..d3779f874
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/StencilBackMasks.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct StencilBackMasks
+ {
+ public int FuncRef;
+ public int Mask;
+ public int FuncMask;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/StencilBackTestState.cs b/Ryujinx.Graphics.Gpu/State/StencilBackTestState.cs
new file mode 100644
index 000000000..18b31eaa0
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/StencilBackTestState.cs
@@ -0,0 +1,14 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.DepthStencil;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct StencilBackTestState
+ {
+ public Bool TwoSided;
+ public StencilOp BackSFail;
+ public StencilOp BackDpFail;
+ public StencilOp BackDpPass;
+ public CompareOp BackFunc;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/StencilTestState.cs b/Ryujinx.Graphics.Gpu/State/StencilTestState.cs
new file mode 100644
index 000000000..b60f002fc
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/StencilTestState.cs
@@ -0,0 +1,17 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.DepthStencil;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct StencilTestState
+ {
+ public Bool Enable;
+ public StencilOp FrontSFail;
+ public StencilOp FrontDpFail;
+ public StencilOp FrontDpPass;
+ public CompareOp FrontFunc;
+ public int FrontFuncRef;
+ public int FrontFuncMask;
+ public int FrontMask;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/UniformBufferState.cs b/Ryujinx.Graphics.Gpu/State/UniformBufferState.cs
new file mode 100644
index 000000000..80e4b6bc5
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/UniformBufferState.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct UniformBufferState
+ {
+ public int Size;
+ public GpuVa Address;
+ public int Offset;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/VertexAttribState.cs b/Ryujinx.Graphics.Gpu/State/VertexAttribState.cs
new file mode 100644
index 000000000..0e327a75c
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/VertexAttribState.cs
@@ -0,0 +1,22 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct VertexAttribState
+ {
+ public uint Attribute;
+
+ public int UnpackBufferIndex()
+ {
+ return (int)(Attribute & 0x1f);
+ }
+
+ public int UnpackOffset()
+ {
+ return (int)((Attribute >> 7) & 0x3fff);
+ }
+
+ public uint UnpackFormat()
+ {
+ return Attribute & 0x3fe00000;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/VertexBufferDrawState.cs b/Ryujinx.Graphics.Gpu/State/VertexBufferDrawState.cs
new file mode 100644
index 000000000..c2f3b7bbd
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/VertexBufferDrawState.cs
@@ -0,0 +1,8 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct VertexBufferDrawState
+ {
+ public int First;
+ public int Count;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/VertexBufferState.cs b/Ryujinx.Graphics.Gpu/State/VertexBufferState.cs
new file mode 100644
index 000000000..a8bd2c925
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/VertexBufferState.cs
@@ -0,0 +1,19 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct VertexBufferState
+ {
+ public uint Control;
+ public GpuVa Address;
+ public int Divisor;
+
+ public int UnpackStride()
+ {
+ return (int)(Control & 0xfff);
+ }
+
+ public bool UnpackEnable()
+ {
+ return (Control & (1 << 12)) != 0;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/ViewportExtents.cs b/Ryujinx.Graphics.Gpu/State/ViewportExtents.cs
new file mode 100644
index 000000000..4be2db90d
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ViewportExtents.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct ViewportExtents
+ {
+ public ushort X;
+ public ushort Width;
+ public ushort Y;
+ public ushort Height;
+ public float DepthNear;
+ public float DepthFar;
+ }
+}
diff --git a/Ryujinx.Graphics.Gpu/State/ViewportTransform.cs b/Ryujinx.Graphics.Gpu/State/ViewportTransform.cs
new file mode 100644
index 000000000..335b039c8
--- /dev/null
+++ b/Ryujinx.Graphics.Gpu/State/ViewportTransform.cs
@@ -0,0 +1,36 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.Gpu.State
+{
+ struct ViewportTransform
+ {
+ public float ScaleX;
+ public float ScaleY;
+ public float ScaleZ;
+ public float TranslateX;
+ public float TranslateY;
+ public float TranslateZ;
+ public uint Swizzle;
+ public uint SubpixelPrecisionBias;
+
+ public ViewportSwizzle UnpackSwizzleX()
+ {
+ return (ViewportSwizzle)(Swizzle & 7);
+ }
+
+ public ViewportSwizzle UnpackSwizzleY()
+ {
+ return (ViewportSwizzle)((Swizzle >> 4) & 7);
+ }
+
+ public ViewportSwizzle UnpackSwizzleZ()
+ {
+ return (ViewportSwizzle)((Swizzle >> 8) & 7);
+ }
+
+ public ViewportSwizzle UnpackSwizzleW()
+ {
+ return (ViewportSwizzle)((Swizzle >> 12) & 7);
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Buffer.cs b/Ryujinx.Graphics.OpenGL/Buffer.cs
new file mode 100644
index 000000000..b86719ceb
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Buffer.cs
@@ -0,0 +1,74 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class Buffer : IBuffer
+ {
+ public int Handle { get; }
+
+ public Buffer(int size)
+ {
+ Handle = GL.GenBuffer();
+
+ GL.BindBuffer(BufferTarget.CopyWriteBuffer, Handle);
+ GL.BufferData(BufferTarget.CopyWriteBuffer, size, IntPtr.Zero, BufferUsageHint.DynamicDraw);
+ }
+
+ public void CopyTo(IBuffer destination, int srcOffset, int dstOffset, int size)
+ {
+ GL.BindBuffer(BufferTarget.CopyReadBuffer, Handle);
+ GL.BindBuffer(BufferTarget.CopyWriteBuffer, ((Buffer)destination).Handle);
+
+ GL.CopyBufferSubData(
+ BufferTarget.CopyReadBuffer,
+ BufferTarget.CopyWriteBuffer,
+ (IntPtr)srcOffset,
+ (IntPtr)dstOffset,
+ (IntPtr)size);
+ }
+
+ public byte[] GetData(int offset, int size)
+ {
+ GL.BindBuffer(BufferTarget.CopyReadBuffer, Handle);
+
+ byte[] data = new byte[size];
+
+ GL.GetBufferSubData(BufferTarget.CopyReadBuffer, (IntPtr)offset, size, data);
+
+ return data;
+ }
+
+ public void SetData(Span data)
+ {
+ unsafe
+ {
+ GL.BindBuffer(BufferTarget.CopyWriteBuffer, Handle);
+
+ fixed (byte* ptr = data)
+ {
+ GL.BufferData(BufferTarget.CopyWriteBuffer, data.Length, (IntPtr)ptr, BufferUsageHint.DynamicDraw);
+ }
+ }
+ }
+
+ public void SetData(int offset, Span data)
+ {
+ GL.BindBuffer(BufferTarget.CopyWriteBuffer, Handle);
+
+ unsafe
+ {
+ fixed (byte* ptr = data)
+ {
+ GL.BufferSubData(BufferTarget.CopyWriteBuffer, (IntPtr)offset, data.Length, (IntPtr)ptr);
+ }
+ }
+ }
+
+ public void Dispose()
+ {
+ GL.DeleteBuffer(Handle);
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/ComputePipeline.cs b/Ryujinx.Graphics.OpenGL/ComputePipeline.cs
new file mode 100644
index 000000000..bee96832d
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/ComputePipeline.cs
@@ -0,0 +1,95 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Shader;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class ComputePipeline : IComputePipeline
+ {
+ private Renderer _renderer;
+
+ private Program _program;
+
+ public ComputePipeline(Renderer renderer)
+ {
+ _renderer = renderer;
+ }
+
+ public void Dispatch(int groupsX, int groupsY, int groupsZ)
+ {
+ BindProgram();
+
+ GL.DispatchCompute(groupsX, groupsY, groupsZ);
+
+ UnbindProgram();
+ }
+
+ public void SetProgram(IProgram program)
+ {
+ _program = (Program)program;
+ }
+
+ public void SetStorageBuffer(int index, BufferRange buffer)
+ {
+ BindProgram();
+
+ BindBuffer(index, buffer, isStorage: true);
+
+ UnbindProgram();
+ }
+
+ public void SetUniformBuffer(int index, BufferRange buffer)
+ {
+ BindProgram();
+
+ BindBuffer(index, buffer, isStorage: false);
+
+ UnbindProgram();
+ }
+
+ private void BindBuffer(int index, BufferRange buffer, bool isStorage)
+ {
+ int bindingPoint = isStorage
+ ? _program.GetStorageBufferBindingPoint(ShaderStage.Compute, index)
+ : _program.GetUniformBufferBindingPoint(ShaderStage.Compute, index);
+
+ if (bindingPoint == -1)
+ {
+ return;
+ }
+
+ BufferRangeTarget target = isStorage
+ ? BufferRangeTarget.ShaderStorageBuffer
+ : BufferRangeTarget.UniformBuffer;
+
+ if (buffer.Buffer == null)
+ {
+ GL.BindBufferRange(target, bindingPoint, 0, IntPtr.Zero, 0);
+
+ return;
+ }
+
+ int bufferHandle = ((Buffer)buffer.Buffer).Handle;
+
+ IntPtr bufferOffset = (IntPtr)buffer.Offset;
+
+ GL.BindBufferRange(
+ target,
+ bindingPoint,
+ bufferHandle,
+ bufferOffset,
+ buffer.Size);
+ }
+
+ private void BindProgram()
+ {
+ _program.Bind();
+ }
+
+ private void UnbindProgram()
+ {
+ ((GraphicsPipeline)_renderer.GraphicsPipeline).RebindProgram();
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/AddressModeConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/AddressModeConverter.cs
new file mode 100644
index 000000000..8f9b5074f
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/AddressModeConverter.cs
@@ -0,0 +1,26 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Sampler;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class AddressModeConverter
+ {
+ public static TextureWrapMode Convert(this AddressMode mode)
+ {
+ switch (mode)
+ {
+ case AddressMode.Clamp : return TextureWrapMode.Clamp;
+ case AddressMode.Repeat : return TextureWrapMode.Repeat;
+ case AddressMode.MirrorClamp : return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampExt;
+ case AddressMode.MirrorClampToEdge : return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampToEdgeExt;
+ case AddressMode.MirrorClampToBorder : return (TextureWrapMode)ExtTextureMirrorClamp.MirrorClampToBorderExt;
+ case AddressMode.ClampToBorder : return TextureWrapMode.ClampToBorder;
+ case AddressMode.MirroredRepeat : return TextureWrapMode.MirroredRepeat;
+ case AddressMode.ClampToEdge : return TextureWrapMode.ClampToEdge;
+ }
+
+ throw new ArgumentException($"Invalid address mode \"{mode}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/BlendFactorConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/BlendFactorConverter.cs
new file mode 100644
index 000000000..1dc405226
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/BlendFactorConverter.cs
@@ -0,0 +1,39 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Blend;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class BlendFactorConverter
+ {
+ public static All Convert(this BlendFactor factor)
+ {
+ switch (factor)
+ {
+ case BlendFactor.Zero: return All.Zero;
+ case BlendFactor.One: return All.One;
+ case BlendFactor.SrcColor: return All.SrcColor;
+ case BlendFactor.OneMinusSrcColor: return All.OneMinusSrcColor;
+ case BlendFactor.SrcAlpha: return All.SrcAlpha;
+ case BlendFactor.OneMinusSrcAlpha: return All.OneMinusSrcAlpha;
+ case BlendFactor.DstAlpha: return All.DstAlpha;
+ case BlendFactor.OneMinusDstAlpha: return All.OneMinusDstAlpha;
+ case BlendFactor.DstColor: return All.DstColor;
+ case BlendFactor.OneMinusDstColor: return All.OneMinusDstColor;
+ case BlendFactor.SrcAlphaSaturate: return All.SrcAlphaSaturate;
+ case BlendFactor.Src1Color: return All.Src1Color;
+ case BlendFactor.OneMinusSrc1Color: return All.OneMinusSrc1Color;
+ case BlendFactor.Src1Alpha: return All.Src1Alpha;
+ case BlendFactor.OneMinusSrc1Alpha: return All.OneMinusSrc1Alpha;
+ case BlendFactor.ConstantColor: return All.ConstantColor;
+ case BlendFactor.OneMinusConstantColor: return All.OneMinusConstantColor;
+ case BlendFactor.ConstantAlpha: return All.ConstantAlpha;
+ case BlendFactor.OneMinusConstantAlpha: return All.OneMinusConstantAlpha;
+ }
+
+ return All.Zero;
+
+ throw new ArgumentException($"Invalid blend factor \"{factor}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/BlendOpConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/BlendOpConverter.cs
new file mode 100644
index 000000000..b33a3bf89
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/BlendOpConverter.cs
@@ -0,0 +1,25 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Blend;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class BlendOpConverter
+ {
+ public static BlendEquationMode Convert(this BlendOp op)
+ {
+ switch (op)
+ {
+ case BlendOp.Add: return BlendEquationMode.FuncAdd;
+ case BlendOp.Subtract: return BlendEquationMode.FuncSubtract;
+ case BlendOp.ReverseSubtract: return BlendEquationMode.FuncReverseSubtract;
+ case BlendOp.Minimum: return BlendEquationMode.Min;
+ case BlendOp.Maximum: return BlendEquationMode.Max;
+ }
+
+ return BlendEquationMode.FuncAdd;
+
+ throw new ArgumentException($"Invalid blend operation \"{op}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/CompareModeConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/CompareModeConverter.cs
new file mode 100644
index 000000000..c0287d8a3
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/CompareModeConverter.cs
@@ -0,0 +1,20 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Sampler;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class CompareModeConverter
+ {
+ public static TextureCompareMode Convert(this CompareMode mode)
+ {
+ switch (mode)
+ {
+ case CompareMode.None: return TextureCompareMode.None;
+ case CompareMode.CompareRToTexture: return TextureCompareMode.CompareRToTexture;
+ }
+
+ throw new ArgumentException($"Invalid compare mode \"{mode}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/CompareOpConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/CompareOpConverter.cs
new file mode 100644
index 000000000..f592735bd
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/CompareOpConverter.cs
@@ -0,0 +1,28 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class CompareOpConverter
+ {
+ public static All Convert(this CompareOp op)
+ {
+ switch (op)
+ {
+ case CompareOp.Never: return All.Never;
+ case CompareOp.Less: return All.Less;
+ case CompareOp.Equal: return All.Equal;
+ case CompareOp.LessOrEqual: return All.Lequal;
+ case CompareOp.Greater: return All.Greater;
+ case CompareOp.NotEqual: return All.Notequal;
+ case CompareOp.GreaterOrEqual: return All.Gequal;
+ case CompareOp.Always: return All.Always;
+ }
+
+ return All.Never;
+
+ throw new ArgumentException($"Invalid compare operation \"{op}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/DepthStencilModeConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/DepthStencilModeConverter.cs
new file mode 100644
index 000000000..4d14bdea2
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/DepthStencilModeConverter.cs
@@ -0,0 +1,20 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Texture;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class DepthStencilModeConverter
+ {
+ public static All Convert(this DepthStencilMode mode)
+ {
+ switch (mode)
+ {
+ case DepthStencilMode.Depth: return All.Depth;
+ case DepthStencilMode.Stencil: return All.Stencil;
+ }
+
+ throw new ArgumentException($"Invalid depth stencil mode \"{mode}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/FaceConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/FaceConverter.cs
new file mode 100644
index 000000000..5c23b68a4
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/FaceConverter.cs
@@ -0,0 +1,23 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class FaceConverter
+ {
+ public static CullFaceMode Convert(this Face face)
+ {
+ switch (face)
+ {
+ case Face.Back: return CullFaceMode.Back;
+ case Face.Front: return CullFaceMode.Front;
+ case Face.FrontAndBack: return CullFaceMode.FrontAndBack;
+ }
+
+ return CullFaceMode.FrontAndBack;
+
+ throw new ArgumentException($"Invalid face \"{face}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/FrontFaceConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/FrontFaceConverter.cs
new file mode 100644
index 000000000..1cae36cd1
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/FrontFaceConverter.cs
@@ -0,0 +1,22 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class FrontFaceConverter
+ {
+ public static FrontFaceDirection Convert(this FrontFace frontFace)
+ {
+ switch (frontFace)
+ {
+ case FrontFace.Clockwise: return FrontFaceDirection.Cw;
+ case FrontFace.CounterClockwise: return FrontFaceDirection.Ccw;
+ }
+
+ return FrontFaceDirection.Cw;
+
+ throw new ArgumentException($"Invalid front face \"{frontFace}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/IndexTypeConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/IndexTypeConverter.cs
new file mode 100644
index 000000000..d3100b98f
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/IndexTypeConverter.cs
@@ -0,0 +1,21 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class IndexTypeConverter
+ {
+ public static DrawElementsType Convert(this IndexType type)
+ {
+ switch (type)
+ {
+ case IndexType.UByte: return DrawElementsType.UnsignedByte;
+ case IndexType.UShort: return DrawElementsType.UnsignedShort;
+ case IndexType.UInt: return DrawElementsType.UnsignedInt;
+ }
+
+ throw new ArgumentException($"Invalid index type \"{type}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/MagFilterConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/MagFilterConverter.cs
new file mode 100644
index 000000000..d86d8014a
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/MagFilterConverter.cs
@@ -0,0 +1,20 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Sampler;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class MagFilterConverter
+ {
+ public static TextureMagFilter Convert(this MagFilter filter)
+ {
+ switch (filter)
+ {
+ case MagFilter.Nearest: return TextureMagFilter.Nearest;
+ case MagFilter.Linear: return TextureMagFilter.Linear;
+ }
+
+ throw new ArgumentException($"Invalid filter \"{filter}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/MinFilterConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/MinFilterConverter.cs
new file mode 100644
index 000000000..128577f85
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/MinFilterConverter.cs
@@ -0,0 +1,24 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Sampler;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class MinFilterConverter
+ {
+ public static TextureMinFilter Convert(this MinFilter filter)
+ {
+ switch (filter)
+ {
+ case MinFilter.Nearest: return TextureMinFilter.Nearest;
+ case MinFilter.Linear: return TextureMinFilter.Linear;
+ case MinFilter.NearestMipmapNearest: return TextureMinFilter.NearestMipmapNearest;
+ case MinFilter.LinearMipmapNearest: return TextureMinFilter.LinearMipmapNearest;
+ case MinFilter.NearestMipmapLinear: return TextureMinFilter.NearestMipmapLinear;
+ case MinFilter.LinearMipmapLinear: return TextureMinFilter.LinearMipmapLinear;
+ }
+
+ throw new ArgumentException($"Invalid filter \"{filter}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/PrimitiveTopologyConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/PrimitiveTopologyConverter.cs
new file mode 100644
index 000000000..fe1dfe39b
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/PrimitiveTopologyConverter.cs
@@ -0,0 +1,33 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class PrimitiveTopologyConverter
+ {
+ public static PrimitiveType Convert(this PrimitiveTopology topology)
+ {
+ switch (topology)
+ {
+ case PrimitiveTopology.Points: return PrimitiveType.Points;
+ case PrimitiveTopology.Lines: return PrimitiveType.Lines;
+ case PrimitiveTopology.LineLoop: return PrimitiveType.LineLoop;
+ case PrimitiveTopology.LineStrip: return PrimitiveType.LineStrip;
+ case PrimitiveTopology.Triangles: return PrimitiveType.Triangles;
+ case PrimitiveTopology.TriangleStrip: return PrimitiveType.TriangleStrip;
+ case PrimitiveTopology.TriangleFan: return PrimitiveType.TriangleFan;
+ case PrimitiveTopology.Quads: return PrimitiveType.Quads;
+ case PrimitiveTopology.QuadStrip: return PrimitiveType.QuadStrip;
+ case PrimitiveTopology.Polygon: return PrimitiveType.Polygon;
+ case PrimitiveTopology.LinesAdjacency: return PrimitiveType.LinesAdjacency;
+ case PrimitiveTopology.LineStripAdjacency: return PrimitiveType.LineStripAdjacency;
+ case PrimitiveTopology.TrianglesAdjacency: return PrimitiveType.TrianglesAdjacency;
+ case PrimitiveTopology.TriangleStripAdjacency: return PrimitiveType.TriangleStripAdjacency;
+ case PrimitiveTopology.Patches: return PrimitiveType.Patches;
+ }
+
+ throw new ArgumentException($"Invalid primitive topology \"{topology}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/StencilOpConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/StencilOpConverter.cs
new file mode 100644
index 000000000..44fbe0a50
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/StencilOpConverter.cs
@@ -0,0 +1,27 @@
+using OpenTK.Graphics.OpenGL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class StencilOpConverter
+ {
+ public static StencilOp Convert(this GAL.DepthStencil.StencilOp op)
+ {
+ switch (op)
+ {
+ case GAL.DepthStencil.StencilOp.Keep: return StencilOp.Keep;
+ case GAL.DepthStencil.StencilOp.Zero: return StencilOp.Zero;
+ case GAL.DepthStencil.StencilOp.Replace: return StencilOp.Replace;
+ case GAL.DepthStencil.StencilOp.IncrementAndClamp: return StencilOp.Incr;
+ case GAL.DepthStencil.StencilOp.DecrementAndClamp: return StencilOp.Decr;
+ case GAL.DepthStencil.StencilOp.Invert: return StencilOp.Invert;
+ case GAL.DepthStencil.StencilOp.IncrementAndWrap: return StencilOp.IncrWrap;
+ case GAL.DepthStencil.StencilOp.DecrementAndWrap: return StencilOp.DecrWrap;
+ }
+
+ return StencilOp.Keep;
+
+ throw new ArgumentException($"Invalid stencil operation \"{op}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/SwizzleComponentConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/SwizzleComponentConverter.cs
new file mode 100644
index 000000000..d9ce650f4
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/SwizzleComponentConverter.cs
@@ -0,0 +1,24 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Texture;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class SwizzleComponentConverter
+ {
+ public static All Convert(this SwizzleComponent swizzleComponent)
+ {
+ switch (swizzleComponent)
+ {
+ case SwizzleComponent.Zero: return All.Zero;
+ case SwizzleComponent.One: return All.One;
+ case SwizzleComponent.Red: return All.Red;
+ case SwizzleComponent.Green: return All.Green;
+ case SwizzleComponent.Blue: return All.Blue;
+ case SwizzleComponent.Alpha: return All.Alpha;
+ }
+
+ throw new ArgumentException($"Invalid swizzle component \"{swizzleComponent}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Converters/TargetConverter.cs b/Ryujinx.Graphics.OpenGL/Converters/TargetConverter.cs
new file mode 100644
index 000000000..6b5249800
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Converters/TargetConverter.cs
@@ -0,0 +1,33 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.Texture;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class TargetConverter
+ {
+ public static ImageTarget ConvertToImageTarget(this Target target)
+ {
+ return (ImageTarget)target.Convert();
+ }
+
+ public static TextureTarget Convert(this Target target)
+ {
+ switch (target)
+ {
+ case Target.Texture1D: return TextureTarget.Texture1D;
+ case Target.Texture2D: return TextureTarget.Texture2D;
+ case Target.Texture3D: return TextureTarget.Texture3D;
+ case Target.Texture1DArray: return TextureTarget.Texture1DArray;
+ case Target.Texture2DArray: return TextureTarget.Texture2DArray;
+ case Target.Texture2DMultisample: return TextureTarget.Texture2DMultisample;
+ case Target.Rectangle: return TextureTarget.TextureRectangle;
+ case Target.Cubemap: return TextureTarget.TextureCubeMap;
+ case Target.CubemapArray: return TextureTarget.TextureCubeMapArray;
+ case Target.TextureBuffer: return TextureTarget.TextureBuffer;
+ }
+
+ throw new ArgumentException($"Invalid target \"{target}\".");
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Counters.cs b/Ryujinx.Graphics.OpenGL/Counters.cs
new file mode 100644
index 000000000..e82a040f0
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Counters.cs
@@ -0,0 +1,77 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class Counters
+ {
+ private int[] _queryObjects;
+
+ private ulong[] _accumulatedCounters;
+
+ public Counters()
+ {
+ int count = Enum.GetNames(typeof(CounterType)).Length;
+
+ _queryObjects = new int[count];
+
+ _accumulatedCounters = new ulong[count];
+ }
+
+ public void Initialize()
+ {
+ for (int index = 0; index < _queryObjects.Length; index++)
+ {
+ int handle = GL.GenQuery();
+
+ _queryObjects[index] = handle;
+
+ CounterType type = (CounterType)index;
+
+ GL.BeginQuery(GetTarget(type), handle);
+ }
+ }
+
+ public ulong GetCounter(CounterType type)
+ {
+ UpdateAccumulatedCounter(type);
+
+ return _accumulatedCounters[(int)type];
+ }
+
+ public void ResetCounter(CounterType type)
+ {
+ UpdateAccumulatedCounter(type);
+
+ _accumulatedCounters[(int)type] = 0;
+ }
+
+ private void UpdateAccumulatedCounter(CounterType type)
+ {
+ int handle = _queryObjects[(int)type];
+
+ QueryTarget target = GetTarget(type);
+
+ GL.EndQuery(target);
+
+ GL.GetQueryObject(handle, GetQueryObjectParam.QueryResult, out long result);
+
+ _accumulatedCounters[(int)type] += (ulong)result;
+
+ GL.BeginQuery(target, handle);
+ }
+
+ private static QueryTarget GetTarget(CounterType type)
+ {
+ switch (type)
+ {
+ case CounterType.SamplesPassed: return QueryTarget.SamplesPassed;
+ case CounterType.PrimitivesGenerated: return QueryTarget.PrimitivesGenerated;
+ case CounterType.TransformFeedbackPrimitivesWritten: return QueryTarget.TransformFeedbackPrimitivesWritten;
+ }
+
+ return QueryTarget.SamplesPassed;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Debugger.cs b/Ryujinx.Graphics.OpenGL/Debugger.cs
new file mode 100644
index 000000000..9da98ae1a
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Debugger.cs
@@ -0,0 +1,43 @@
+using OpenTK.Graphics.OpenGL;
+using System;
+using System.Runtime.InteropServices;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ public static class Debugger
+ {
+ private static DebugProc _debugCallback;
+
+ public static void Initialize()
+ {
+ GL.Enable(EnableCap.DebugOutputSynchronous);
+
+ int[] array = null;
+
+ GL.DebugMessageControl(DebugSourceControl.DontCare, DebugTypeControl.DontCare, DebugSeverityControl.DontCare, 0, array, true);
+
+ _debugCallback = PrintDbg;
+
+ GL.DebugMessageCallback(_debugCallback, IntPtr.Zero);
+ }
+
+ private static void PrintDbg(
+ DebugSource source,
+ DebugType type,
+ int id,
+ DebugSeverity severity,
+ int length,
+ IntPtr message,
+ IntPtr userParam)
+ {
+ string msg = Marshal.PtrToStringAnsi(message);
+
+ if (type == DebugType.DebugTypeError && !msg.Contains("link"))
+ {
+ throw new Exception(msg);
+ }
+
+ System.Console.WriteLine("GL message: " + source + " " + type + " " + severity + " " + msg);
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Formats/FormatInfo.cs b/Ryujinx.Graphics.OpenGL/Formats/FormatInfo.cs
new file mode 100644
index 000000000..a1fd723f2
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Formats/FormatInfo.cs
@@ -0,0 +1,45 @@
+using OpenTK.Graphics.OpenGL;
+
+namespace Ryujinx.Graphics.OpenGL.Formats
+{
+ struct FormatInfo
+ {
+ public int Components { get; }
+ public bool Normalized { get; }
+ public bool Scaled { get; }
+
+ public PixelInternalFormat PixelInternalFormat { get; }
+ public PixelFormat PixelFormat { get; }
+ public PixelType PixelType { get; }
+
+ public bool IsCompressed { get; }
+
+ public FormatInfo(
+ int components,
+ bool normalized,
+ bool scaled,
+ All pixelInternalFormat,
+ PixelFormat pixelFormat,
+ PixelType pixelType)
+ {
+ Components = components;
+ Normalized = normalized;
+ Scaled = scaled;
+ PixelInternalFormat = (PixelInternalFormat)pixelInternalFormat;
+ PixelFormat = pixelFormat;
+ PixelType = pixelType;
+ IsCompressed = false;
+ }
+
+ public FormatInfo(int components, bool normalized, bool scaled, All pixelFormat)
+ {
+ Components = components;
+ Normalized = normalized;
+ Scaled = scaled;
+ PixelInternalFormat = 0;
+ PixelFormat = (PixelFormat)pixelFormat;
+ PixelType = 0;
+ IsCompressed = true;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Formats/FormatTable.cs b/Ryujinx.Graphics.OpenGL/Formats/FormatTable.cs
new file mode 100644
index 000000000..13e88c556
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Formats/FormatTable.cs
@@ -0,0 +1,183 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL.Formats
+{
+ struct FormatTable
+ {
+ private static FormatInfo[] _table;
+
+ static FormatTable()
+ {
+ _table = new FormatInfo[Enum.GetNames(typeof(Format)).Length];
+
+ Add(Format.R8Unorm, new FormatInfo(1, true, false, All.R8, PixelFormat.Red, PixelType.UnsignedByte));
+ Add(Format.R8Snorm, new FormatInfo(1, true, false, All.R8Snorm, PixelFormat.Red, PixelType.Byte));
+ Add(Format.R8Uint, new FormatInfo(1, false, false, All.R8ui, PixelFormat.RedInteger, PixelType.UnsignedByte));
+ Add(Format.R8Sint, new FormatInfo(1, false, false, All.R8i, PixelFormat.RedInteger, PixelType.Byte));
+ Add(Format.R16Float, new FormatInfo(1, false, false, All.R16f, PixelFormat.Red, PixelType.HalfFloat));
+ Add(Format.R16Unorm, new FormatInfo(1, true, false, All.R16, PixelFormat.Red, PixelType.UnsignedShort));
+ Add(Format.R16Snorm, new FormatInfo(1, true, false, All.R16Snorm, PixelFormat.Red, PixelType.Short));
+ Add(Format.R16Uint, new FormatInfo(1, false, false, All.R16ui, PixelFormat.RedInteger, PixelType.UnsignedShort));
+ Add(Format.R16Sint, new FormatInfo(1, false, false, All.R16i, PixelFormat.RedInteger, PixelType.Short));
+ Add(Format.R32Float, new FormatInfo(1, false, false, All.R32f, PixelFormat.Red, PixelType.Float));
+ Add(Format.R32Uint, new FormatInfo(1, false, false, All.R32ui, PixelFormat.RedInteger, PixelType.UnsignedInt));
+ Add(Format.R32Sint, new FormatInfo(1, false, false, All.R32i, PixelFormat.RedInteger, PixelType.Int));
+ Add(Format.R8G8Unorm, new FormatInfo(2, true, false, All.Rg8, PixelFormat.Rg, PixelType.UnsignedByte));
+ Add(Format.R8G8Snorm, new FormatInfo(2, true, false, All.Rg8Snorm, PixelFormat.Rg, PixelType.Byte));
+ Add(Format.R8G8Uint, new FormatInfo(2, false, false, All.Rg8ui, PixelFormat.RgInteger, PixelType.UnsignedByte));
+ Add(Format.R8G8Sint, new FormatInfo(2, false, false, All.Rg8i, PixelFormat.RgInteger, PixelType.Byte));
+ Add(Format.R16G16Float, new FormatInfo(2, false, false, All.Rg16f, PixelFormat.Rg, PixelType.HalfFloat));
+ Add(Format.R16G16Unorm, new FormatInfo(2, true, false, All.Rg16, PixelFormat.Rg, PixelType.UnsignedShort));
+ Add(Format.R16G16Snorm, new FormatInfo(2, true, false, All.Rg16Snorm, PixelFormat.Rg, PixelType.Short));
+ Add(Format.R16G16Uint, new FormatInfo(2, false, false, All.Rg16ui, PixelFormat.RgInteger, PixelType.UnsignedShort));
+ Add(Format.R16G16Sint, new FormatInfo(2, false, false, All.Rg16i, PixelFormat.RgInteger, PixelType.Short));
+ Add(Format.R32G32Float, new FormatInfo(2, false, false, All.Rg32f, PixelFormat.Rg, PixelType.Float));
+ Add(Format.R32G32Uint, new FormatInfo(2, false, false, All.Rg32ui, PixelFormat.RgInteger, PixelType.UnsignedInt));
+ Add(Format.R32G32Sint, new FormatInfo(2, false, false, All.Rg32i, PixelFormat.RgInteger, PixelType.Int));
+ Add(Format.R8G8B8Unorm, new FormatInfo(3, true, false, All.Rgb8, PixelFormat.Rgb, PixelType.UnsignedByte));
+ Add(Format.R8G8B8Snorm, new FormatInfo(3, true, false, All.Rgb8Snorm, PixelFormat.Rgb, PixelType.Byte));
+ Add(Format.R8G8B8Uint, new FormatInfo(3, false, false, All.Rgb8ui, PixelFormat.RgbInteger, PixelType.UnsignedByte));
+ Add(Format.R8G8B8Sint, new FormatInfo(3, false, false, All.Rgb8i, PixelFormat.RgbInteger, PixelType.Byte));
+ Add(Format.R16G16B16Float, new FormatInfo(3, false, false, All.Rgb16f, PixelFormat.Rgb, PixelType.HalfFloat));
+ Add(Format.R16G16B16Unorm, new FormatInfo(3, true, false, All.Rgb16, PixelFormat.Rgb, PixelType.UnsignedShort));
+ Add(Format.R16G16B16Snorm, new FormatInfo(3, true, false, All.Rgb16Snorm, PixelFormat.Rgb, PixelType.Short));
+ Add(Format.R16G16B16Uint, new FormatInfo(3, false, false, All.Rgb16ui, PixelFormat.RgbInteger, PixelType.UnsignedShort));
+ Add(Format.R16G16B16Sint, new FormatInfo(3, false, false, All.Rgb16i, PixelFormat.RgbInteger, PixelType.Short));
+ Add(Format.R32G32B32Float, new FormatInfo(3, false, false, All.Rgb32f, PixelFormat.Rgb, PixelType.Float));
+ Add(Format.R32G32B32Uint, new FormatInfo(3, false, false, All.Rgb32ui, PixelFormat.RgbInteger, PixelType.UnsignedInt));
+ Add(Format.R32G32B32Sint, new FormatInfo(3, false, false, All.Rgb32i, PixelFormat.RgbInteger, PixelType.Int));
+ Add(Format.R8G8B8A8Unorm, new FormatInfo(4, true, false, All.Rgba8, PixelFormat.Rgba, PixelType.UnsignedByte));
+ Add(Format.R8G8B8A8Snorm, new FormatInfo(4, true, false, All.Rgba8Snorm, PixelFormat.Rgba, PixelType.Byte));
+ Add(Format.R8G8B8A8Uint, new FormatInfo(4, false, false, All.Rgba8ui, PixelFormat.RgbaInteger, PixelType.UnsignedByte));
+ Add(Format.R8G8B8A8Sint, new FormatInfo(4, false, false, All.Rgba8i, PixelFormat.RgbaInteger, PixelType.Byte));
+ Add(Format.R16G16B16A16Float, new FormatInfo(4, false, false, All.Rgba16f, PixelFormat.Rgba, PixelType.HalfFloat));
+ Add(Format.R16G16B16A16Unorm, new FormatInfo(4, true, false, All.Rgba16, PixelFormat.Rgba, PixelType.UnsignedShort));
+ Add(Format.R16G16B16A16Snorm, new FormatInfo(4, true, false, All.Rgba16Snorm, PixelFormat.Rgba, PixelType.Short));
+ Add(Format.R16G16B16A16Uint, new FormatInfo(4, false, false, All.Rgba16ui, PixelFormat.RgbaInteger, PixelType.UnsignedShort));
+ Add(Format.R16G16B16A16Sint, new FormatInfo(4, false, false, All.Rgba16i, PixelFormat.RgbaInteger, PixelType.Short));
+ Add(Format.R32G32B32A32Float, new FormatInfo(4, false, false, All.Rgba32f, PixelFormat.Rgba, PixelType.Float));
+ Add(Format.R32G32B32A32Uint, new FormatInfo(4, false, false, All.Rgba32ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt));
+ Add(Format.R32G32B32A32Sint, new FormatInfo(4, false, false, All.Rgba32i, PixelFormat.RgbaInteger, PixelType.Int));
+ Add(Format.S8Uint, new FormatInfo(1, false, false, All.StencilIndex8, PixelFormat.StencilIndex, PixelType.UnsignedByte));
+ Add(Format.D16Unorm, new FormatInfo(1, false, false, All.DepthComponent16, PixelFormat.DepthComponent, PixelType.UnsignedShort));
+ Add(Format.D24X8Unorm, new FormatInfo(1, false, false, All.DepthComponent24, PixelFormat.DepthComponent, PixelType.UnsignedInt));
+ Add(Format.D32Float, new FormatInfo(1, false, false, All.DepthComponent32f, PixelFormat.DepthComponent, PixelType.Float));
+ Add(Format.D24UnormS8Uint, new FormatInfo(1, false, false, All.Depth24Stencil8, PixelFormat.DepthStencil, PixelType.UnsignedInt248));
+ Add(Format.D32FloatS8Uint, new FormatInfo(1, false, false, All.Depth32fStencil8, PixelFormat.DepthStencil, PixelType.Float32UnsignedInt248Rev));
+ Add(Format.R8G8B8X8Srgb, new FormatInfo(4, false, false, All.Srgb8, PixelFormat.Rgba, PixelType.UnsignedByte));
+ Add(Format.R8G8B8A8Srgb, new FormatInfo(4, false, false, All.Srgb8Alpha8, PixelFormat.Rgba, PixelType.UnsignedByte));
+ Add(Format.R4G4B4A4Unorm, new FormatInfo(4, true, false, All.Rgba4, PixelFormat.Rgba, PixelType.UnsignedShort4444Reversed));
+ Add(Format.R5G5B5X1Unorm, new FormatInfo(4, true, false, All.Rgb5, PixelFormat.Rgb, PixelType.UnsignedShort1555Reversed));
+ Add(Format.R5G5B5A1Unorm, new FormatInfo(4, true, false, All.Rgb5A1, PixelFormat.Rgba, PixelType.UnsignedShort1555Reversed));
+ Add(Format.R5G6B5Unorm, new FormatInfo(3, true, false, All.Rgb565, PixelFormat.Rgb, PixelType.UnsignedShort565Reversed));
+ Add(Format.R10G10B10A2Unorm, new FormatInfo(4, true, false, All.Rgb10A2, PixelFormat.Rgba, PixelType.UnsignedInt2101010Reversed));
+ Add(Format.R10G10B10A2Uint, new FormatInfo(4, false, false, All.Rgb10A2ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt2101010Reversed));
+ Add(Format.R11G11B10Float, new FormatInfo(3, false, false, All.R11fG11fB10f, PixelFormat.Rgb, PixelType.UnsignedInt10F11F11FRev));
+ Add(Format.R9G9B9E5Float, new FormatInfo(3, false, false, All.Rgb9E5, PixelFormat.Rgb, PixelType.UnsignedInt5999Rev));
+ Add(Format.Bc1RgbUnorm, new FormatInfo(2, true, false, All.CompressedRgbS3tcDxt1Ext));
+ Add(Format.Bc1RgbaUnorm, new FormatInfo(1, true, false, All.CompressedRgbaS3tcDxt1Ext));
+ Add(Format.Bc2Unorm, new FormatInfo(1, true, false, All.CompressedRgbaS3tcDxt3Ext));
+ Add(Format.Bc3Unorm, new FormatInfo(1, true, false, All.CompressedRgbaS3tcDxt5Ext));
+ Add(Format.Bc1RgbSrgb, new FormatInfo(2, false, false, All.CompressedSrgbS3tcDxt1Ext));
+ Add(Format.Bc1RgbaSrgb, new FormatInfo(1, true, false, All.CompressedSrgbAlphaS3tcDxt1Ext));
+ Add(Format.Bc2Srgb, new FormatInfo(1, false, false, All.CompressedSrgbAlphaS3tcDxt3Ext));
+ Add(Format.Bc3Srgb, new FormatInfo(1, false, false, All.CompressedSrgbAlphaS3tcDxt5Ext));
+ Add(Format.Bc4Unorm, new FormatInfo(1, true, false, All.CompressedRedRgtc1));
+ Add(Format.Bc4Snorm, new FormatInfo(1, true, false, All.CompressedSignedRedRgtc1));
+ Add(Format.Bc5Unorm, new FormatInfo(1, true, false, All.CompressedRgRgtc2));
+ Add(Format.Bc5Snorm, new FormatInfo(1, true, false, All.CompressedSignedRgRgtc2));
+ Add(Format.Bc7Unorm, new FormatInfo(1, true, false, All.CompressedRgbaBptcUnorm));
+ Add(Format.Bc7Srgb, new FormatInfo(1, false, false, All.CompressedSrgbAlphaBptcUnorm));
+ Add(Format.Bc6HUfloat, new FormatInfo(1, false, false, All.CompressedRgbBptcUnsignedFloat));
+ Add(Format.Bc6HSfloat, new FormatInfo(1, false, false, All.CompressedRgbBptcSignedFloat));
+ Add(Format.R8Uscaled, new FormatInfo(1, false, true, All.R8ui, PixelFormat.RedInteger, PixelType.UnsignedByte));
+ Add(Format.R8Sscaled, new FormatInfo(1, false, true, All.R8i, PixelFormat.RedInteger, PixelType.Byte));
+ Add(Format.R16Uscaled, new FormatInfo(1, false, true, All.R16ui, PixelFormat.RedInteger, PixelType.UnsignedShort));
+ Add(Format.R16Sscaled, new FormatInfo(1, false, true, All.R16i, PixelFormat.RedInteger, PixelType.Short));
+ Add(Format.R32Uscaled, new FormatInfo(1, false, true, All.R32ui, PixelFormat.RedInteger, PixelType.UnsignedInt));
+ Add(Format.R32Sscaled, new FormatInfo(1, false, true, All.R32i, PixelFormat.RedInteger, PixelType.Int));
+ Add(Format.R8G8Uscaled, new FormatInfo(2, false, true, All.Rg8ui, PixelFormat.RgInteger, PixelType.UnsignedByte));
+ Add(Format.R8G8Sscaled, new FormatInfo(2, false, true, All.Rg8i, PixelFormat.RgInteger, PixelType.Byte));
+ Add(Format.R16G16Uscaled, new FormatInfo(2, false, true, All.Rg16ui, PixelFormat.RgInteger, PixelType.UnsignedShort));
+ Add(Format.R16G16Sscaled, new FormatInfo(2, false, true, All.Rg16i, PixelFormat.RgInteger, PixelType.Short));
+ Add(Format.R32G32Uscaled, new FormatInfo(2, false, true, All.Rg32ui, PixelFormat.RgInteger, PixelType.UnsignedInt));
+ Add(Format.R32G32Sscaled, new FormatInfo(2, false, true, All.Rg32i, PixelFormat.RgInteger, PixelType.Int));
+ Add(Format.R8G8B8Uscaled, new FormatInfo(3, false, true, All.Rgb8ui, PixelFormat.RgbInteger, PixelType.UnsignedByte));
+ Add(Format.R8G8B8Sscaled, new FormatInfo(3, false, true, All.Rgb8i, PixelFormat.RgbInteger, PixelType.Byte));
+ Add(Format.R16G16B16Uscaled, new FormatInfo(3, false, true, All.Rgb16ui, PixelFormat.RgbInteger, PixelType.UnsignedShort));
+ Add(Format.R16G16B16Sscaled, new FormatInfo(3, false, true, All.Rgb16i, PixelFormat.RgbInteger, PixelType.Short));
+ Add(Format.R32G32B32Uscaled, new FormatInfo(3, false, true, All.Rgb32ui, PixelFormat.RgbInteger, PixelType.UnsignedInt));
+ Add(Format.R32G32B32Sscaled, new FormatInfo(3, false, true, All.Rgb32i, PixelFormat.RgbInteger, PixelType.Int));
+ Add(Format.R8G8B8A8Uscaled, new FormatInfo(4, false, true, All.Rgba8ui, PixelFormat.RgbaInteger, PixelType.UnsignedByte));
+ Add(Format.R8G8B8A8Sscaled, new FormatInfo(4, false, true, All.Rgba8i, PixelFormat.RgbaInteger, PixelType.Byte));
+ Add(Format.R16G16B16A16Uscaled, new FormatInfo(4, false, true, All.Rgba16ui, PixelFormat.RgbaInteger, PixelType.UnsignedShort));
+ Add(Format.R16G16B16A16Sscaled, new FormatInfo(4, false, true, All.Rgba16i, PixelFormat.RgbaInteger, PixelType.Short));
+ Add(Format.R32G32B32A32Uscaled, new FormatInfo(4, false, true, All.Rgba32ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt));
+ Add(Format.R32G32B32A32Sscaled, new FormatInfo(4, false, true, All.Rgba32i, PixelFormat.RgbaInteger, PixelType.Int));
+ Add(Format.R10G10B10A2Snorm, new FormatInfo(4, true, false, All.Rgb10A2, PixelFormat.Rgba, (PixelType)All.Int2101010Rev));
+ Add(Format.R10G10B10A2Sint, new FormatInfo(4, false, false, All.Rgb10A2, PixelFormat.RgbaInteger, (PixelType)All.Int2101010Rev));
+ Add(Format.R10G10B10A2Uscaled, new FormatInfo(4, false, true, All.Rgb10A2ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt2101010Reversed));
+ Add(Format.R10G10B10A2Sscaled, new FormatInfo(4, false, true, All.Rgb10A2, PixelFormat.RgbaInteger, PixelType.UnsignedInt2101010Reversed));
+ Add(Format.R8G8B8X8Unorm, new FormatInfo(4, true, false, All.Rgb8, PixelFormat.Rgba, PixelType.UnsignedByte));
+ Add(Format.R8G8B8X8Snorm, new FormatInfo(4, true, false, All.Rgb8Snorm, PixelFormat.Rgba, PixelType.Byte));
+ Add(Format.R8G8B8X8Uint, new FormatInfo(4, false, false, All.Rgb8ui, PixelFormat.RgbaInteger, PixelType.UnsignedByte));
+ Add(Format.R8G8B8X8Sint, new FormatInfo(4, false, false, All.Rgb8i, PixelFormat.RgbaInteger, PixelType.Byte));
+ Add(Format.R16G16B16X16Float, new FormatInfo(4, false, false, All.Rgb16f, PixelFormat.Rgba, PixelType.HalfFloat));
+ Add(Format.R16G16B16X16Unorm, new FormatInfo(4, true, false, All.Rgb16, PixelFormat.Rgba, PixelType.UnsignedShort));
+ Add(Format.R16G16B16X16Snorm, new FormatInfo(4, true, false, All.Rgb16Snorm, PixelFormat.Rgba, PixelType.Short));
+ Add(Format.R16G16B16X16Uint, new FormatInfo(4, false, false, All.Rgb16ui, PixelFormat.RgbaInteger, PixelType.UnsignedShort));
+ Add(Format.R16G16B16X16Sint, new FormatInfo(4, false, false, All.Rgb16i, PixelFormat.RgbaInteger, PixelType.Short));
+ Add(Format.R32G32B32X32Float, new FormatInfo(4, false, false, All.Rgb32f, PixelFormat.Rgba, PixelType.Float));
+ Add(Format.R32G32B32X32Uint, new FormatInfo(4, false, false, All.Rgb32ui, PixelFormat.RgbaInteger, PixelType.UnsignedInt));
+ Add(Format.R32G32B32X32Sint, new FormatInfo(4, false, false, All.Rgb32i, PixelFormat.RgbaInteger, PixelType.Int));
+ Add(Format.Astc4x4Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc4X4Khr));
+ Add(Format.Astc5x4Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc5X4Khr));
+ Add(Format.Astc5x5Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc5X5Khr));
+ Add(Format.Astc6x5Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc6X5Khr));
+ Add(Format.Astc6x6Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc6X6Khr));
+ Add(Format.Astc8x5Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc8X5Khr));
+ Add(Format.Astc8x6Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc8X6Khr));
+ Add(Format.Astc8x8Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc8X8Khr));
+ Add(Format.Astc10x5Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc10X5Khr));
+ Add(Format.Astc10x6Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc10X6Khr));
+ Add(Format.Astc10x8Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc10X8Khr));
+ Add(Format.Astc10x10Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc10X10Khr));
+ Add(Format.Astc12x10Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc12X10Khr));
+ Add(Format.Astc12x12Unorm, new FormatInfo(1, true, false, All.CompressedRgbaAstc12X12Khr));
+ Add(Format.Astc4x4Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc4X4Khr));
+ Add(Format.Astc5x4Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc5X4Khr));
+ Add(Format.Astc5x5Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc5X5Khr));
+ Add(Format.Astc6x5Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc6X5Khr));
+ Add(Format.Astc6x6Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc6X6Khr));
+ Add(Format.Astc8x5Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc8X5Khr));
+ Add(Format.Astc8x6Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc8X6Khr));
+ Add(Format.Astc8x8Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc8X8Khr));
+ Add(Format.Astc10x5Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc10X5Khr));
+ Add(Format.Astc10x6Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc10X6Khr));
+ Add(Format.Astc10x8Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc10X8Khr));
+ Add(Format.Astc10x10Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc10X10Khr));
+ Add(Format.Astc12x10Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc12X10Khr));
+ Add(Format.Astc12x12Srgb, new FormatInfo(1, false, false, All.CompressedSrgb8Alpha8Astc12X12Khr));
+ Add(Format.B5G6R5Unorm, new FormatInfo(3, true, false, All.Rgb565, PixelFormat.Bgr, PixelType.UnsignedShort565));
+ Add(Format.B5G5R5X1Unorm, new FormatInfo(4, true, false, All.Rgb5, PixelFormat.Bgra, PixelType.UnsignedShort5551));
+ Add(Format.B5G5R5A1Unorm, new FormatInfo(4, true, false, All.Rgb5A1, PixelFormat.Bgra, PixelType.UnsignedShort5551));
+ Add(Format.A1B5G5R5Unorm, new FormatInfo(4, true, false, All.Rgb5A1, PixelFormat.Bgra, PixelType.UnsignedShort1555Reversed));
+ Add(Format.B8G8R8X8Unorm, new FormatInfo(4, true, false, All.Rgba8, PixelFormat.Bgra, PixelType.UnsignedByte));
+ Add(Format.B8G8R8A8Unorm, new FormatInfo(4, true, false, All.Rgba8, PixelFormat.Bgra, PixelType.UnsignedByte));
+ Add(Format.B8G8R8X8Srgb, new FormatInfo(4, false, false, All.Srgb8, PixelFormat.BgraInteger, PixelType.UnsignedByte));
+ Add(Format.B8G8R8A8Srgb, new FormatInfo(4, false, false, All.Srgb8Alpha8, PixelFormat.BgraInteger, PixelType.UnsignedByte));
+ }
+
+ private static void Add(Format format, FormatInfo info)
+ {
+ _table[(int)format] = info;
+ }
+
+ public static FormatInfo GetFormatInfo(Format format)
+ {
+ return _table[(int)format];
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Framebuffer.cs b/Ryujinx.Graphics.OpenGL/Framebuffer.cs
new file mode 100644
index 000000000..409130094
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Framebuffer.cs
@@ -0,0 +1,116 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class Framebuffer : IDisposable
+ {
+ public int Handle { get; private set; }
+
+ private FramebufferAttachment _lastDsAttachment;
+
+ public Framebuffer()
+ {
+ Handle = GL.GenFramebuffer();
+ }
+
+ public void Bind()
+ {
+ GL.BindFramebuffer(FramebufferTarget.Framebuffer, Handle);
+ }
+
+ public void AttachColor(int index, TextureView color)
+ {
+ GL.FramebufferTexture(
+ FramebufferTarget.Framebuffer,
+ FramebufferAttachment.ColorAttachment0 + index,
+ color?.Handle ?? 0,
+ 0);
+ }
+
+ public void AttachColor(int index, TextureView color, int layer)
+ {
+ GL.FramebufferTextureLayer(
+ FramebufferTarget.Framebuffer,
+ FramebufferAttachment.ColorAttachment0 + index,
+ color?.Handle ?? 0,
+ 0,
+ layer);
+ }
+
+ public void AttachDepthStencil(TextureView depthStencil)
+ {
+ // Detach the last depth/stencil buffer if there is any.
+ if (_lastDsAttachment != 0)
+ {
+ GL.FramebufferTexture(FramebufferTarget.Framebuffer, _lastDsAttachment, 0, 0);
+ }
+
+ if (depthStencil != null)
+ {
+ FramebufferAttachment attachment;
+
+ if (IsPackedDepthStencilFormat(depthStencil.Format))
+ {
+ attachment = FramebufferAttachment.DepthStencilAttachment;
+ }
+ else if (IsDepthOnlyFormat(depthStencil.Format))
+ {
+ attachment = FramebufferAttachment.DepthAttachment;
+ }
+ else
+ {
+ attachment = FramebufferAttachment.StencilAttachment;
+ }
+
+ GL.FramebufferTexture(
+ FramebufferTarget.Framebuffer,
+ attachment,
+ depthStencil.Handle,
+ 0);
+
+ _lastDsAttachment = attachment;
+ }
+ else
+ {
+ _lastDsAttachment = 0;
+ }
+ }
+
+ public void SetDrawBuffers(int colorsCount)
+ {
+ DrawBuffersEnum[] drawBuffers = new DrawBuffersEnum[colorsCount];
+
+ for (int index = 0; index < colorsCount; index++)
+ {
+ drawBuffers[index] = DrawBuffersEnum.ColorAttachment0 + index;
+ }
+
+ GL.DrawBuffers(colorsCount, drawBuffers);
+ }
+
+ private static bool IsPackedDepthStencilFormat(Format format)
+ {
+ return format == Format.D24UnormS8Uint ||
+ format == Format.D32FloatS8Uint;
+ }
+
+ private static bool IsDepthOnlyFormat(Format format)
+ {
+ return format == Format.D16Unorm ||
+ format == Format.D24X8Unorm ||
+ format == Format.D32Float;
+ }
+
+ public void Dispose()
+ {
+ if (Handle != 0)
+ {
+ GL.DeleteFramebuffer(Handle);
+
+ Handle = 0;
+ }
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/GraphicsPipeline.cs b/Ryujinx.Graphics.OpenGL/GraphicsPipeline.cs
new file mode 100644
index 000000000..e9f6b2fbf
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/GraphicsPipeline.cs
@@ -0,0 +1,718 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Blend;
+using Ryujinx.Graphics.GAL.Color;
+using Ryujinx.Graphics.GAL.DepthStencil;
+using Ryujinx.Graphics.GAL.InputAssembler;
+using Ryujinx.Graphics.Shader;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class GraphicsPipeline : IGraphicsPipeline
+ {
+ private Program _program;
+
+ private VertexArray _vertexArray;
+ private Framebuffer _framebuffer;
+
+ private IntPtr _indexBaseOffset;
+
+ private DrawElementsType _elementsType;
+
+ private PrimitiveType _primitiveType;
+
+ private int _stencilFrontMask;
+ private bool _depthMask;
+ private bool _depthTest;
+ private bool _hasDepthBuffer;
+
+ private TextureView _unit0Texture;
+
+ private ClipOrigin _clipOrigin;
+
+ private uint[] _componentMasks;
+
+ internal GraphicsPipeline()
+ {
+ _clipOrigin = ClipOrigin.LowerLeft;
+ }
+
+ public void BindBlendState(int index, BlendDescriptor blend)
+ {
+ if (!blend.Enable)
+ {
+ GL.Disable(IndexedEnableCap.Blend, index);
+
+ return;
+ }
+
+ GL.BlendEquationSeparate(
+ index,
+ blend.ColorOp.Convert(),
+ blend.AlphaOp.Convert());
+
+ GL.BlendFuncSeparate(
+ index,
+ (BlendingFactorSrc) blend.ColorSrcFactor.Convert(),
+ (BlendingFactorDest)blend.ColorDstFactor.Convert(),
+ (BlendingFactorSrc) blend.AlphaSrcFactor.Convert(),
+ (BlendingFactorDest)blend.AlphaDstFactor.Convert());
+
+ GL.Enable(IndexedEnableCap.Blend, index);
+ }
+
+ public void BindIndexBuffer(BufferRange buffer, IndexType type)
+ {
+ _elementsType = type.Convert();
+
+ _indexBaseOffset = (IntPtr)buffer.Offset;
+
+ EnsureVertexArray();
+
+ _vertexArray.SetIndexBuffer((Buffer)buffer.Buffer);
+ }
+
+ public void BindProgram(IProgram program)
+ {
+ _program = (Program)program;
+
+ _program.Bind();
+ }
+
+ public void BindSampler(int index, ShaderStage stage, ISampler sampler)
+ {
+ int unit = _program.GetTextureUnit(stage, index);
+
+ if (unit != -1 && sampler != null)
+ {
+ ((Sampler)sampler).Bind(unit);
+ }
+ }
+
+ public void BindTexture(int index, ShaderStage stage, ITexture texture)
+ {
+ int unit = _program.GetTextureUnit(stage, index);
+
+ if (unit != -1 && texture != null)
+ {
+ if (unit == 0)
+ {
+ _unit0Texture = ((TextureView)texture);
+ }
+ else
+ {
+ ((TextureView)texture).Bind(unit);
+ }
+ }
+ }
+
+ public void BindStorageBuffers(int index, ShaderStage stage, BufferRange[] buffers)
+ {
+ BindBuffers(index, stage, buffers, isStorage: true);
+ }
+
+ public void BindUniformBuffers(int index, ShaderStage stage, BufferRange[] buffers)
+ {
+ BindBuffers(index, stage, buffers, isStorage: false);
+ }
+
+ private void BindBuffers(int index, ShaderStage stage, BufferRange[] buffers, bool isStorage)
+ {
+ for (int bufferIndex = 0; bufferIndex < buffers.Length; bufferIndex++, index++)
+ {
+ int bindingPoint = isStorage
+ ? _program.GetStorageBufferBindingPoint(stage, index)
+ : _program.GetUniformBufferBindingPoint(stage, index);
+
+ if (bindingPoint == -1)
+ {
+ continue;
+ }
+
+ BufferRange buffer = buffers[bufferIndex];
+
+ BufferRangeTarget target = isStorage
+ ? BufferRangeTarget.ShaderStorageBuffer
+ : BufferRangeTarget.UniformBuffer;
+
+ if (buffer.Buffer == null)
+ {
+ GL.BindBufferRange(target, bindingPoint, 0, IntPtr.Zero, 0);
+
+ continue;
+ }
+
+ int bufferHandle = ((Buffer)buffer.Buffer).Handle;
+
+ IntPtr bufferOffset = (IntPtr)buffer.Offset;
+
+ GL.BindBufferRange(
+ target,
+ bindingPoint,
+ bufferHandle,
+ bufferOffset,
+ buffer.Size);
+ }
+ }
+
+ public void BindVertexAttribs(VertexAttribDescriptor[] vertexAttribs)
+ {
+ EnsureVertexArray();
+
+ _vertexArray.SetVertexAttributes(vertexAttribs);
+ }
+
+ public void BindVertexBuffers(VertexBufferDescriptor[] vertexBuffers)
+ {
+ EnsureVertexArray();
+
+ _vertexArray.SetVertexBuffers(vertexBuffers);
+ }
+
+ public void ClearRenderTargetColor(int index, uint componentMask, ColorF color)
+ {
+ GL.ColorMask(
+ index,
+ (componentMask & 1) != 0,
+ (componentMask & 2) != 0,
+ (componentMask & 4) != 0,
+ (componentMask & 8) != 0);
+
+ float[] colors = new float[] { color.Red, color.Green, color.Blue, color.Alpha };
+
+ GL.ClearBuffer(ClearBuffer.Color, index, colors);
+
+ RestoreComponentMask(index);
+ }
+
+ public void ClearRenderTargetColor(int index, uint componentMask, ColorSI color)
+ {
+ GL.ColorMask(
+ index,
+ (componentMask & 1u) != 0,
+ (componentMask & 2u) != 0,
+ (componentMask & 4u) != 0,
+ (componentMask & 8u) != 0);
+
+ int[] colors = new int[] { color.Red, color.Green, color.Blue, color.Alpha };
+
+ GL.ClearBuffer(ClearBuffer.Color, index, colors);
+
+ RestoreComponentMask(index);
+ }
+
+ public void ClearRenderTargetColor(int index, uint componentMask, ColorUI color)
+ {
+ GL.ColorMask(
+ index,
+ (componentMask & 1u) != 0,
+ (componentMask & 2u) != 0,
+ (componentMask & 4u) != 0,
+ (componentMask & 8u) != 0);
+
+ uint[] colors = new uint[] { color.Red, color.Green, color.Blue, color.Alpha };
+
+ GL.ClearBuffer(ClearBuffer.Color, index, colors);
+
+ RestoreComponentMask(index);
+ }
+
+ public void ClearRenderTargetDepthStencil(
+ float depthValue,
+ bool depthMask,
+ int stencilValue,
+ int stencilMask)
+ {
+ bool stencilMaskChanged =
+ stencilMask != 0 &&
+ stencilMask != _stencilFrontMask;
+
+ bool depthMaskChanged = depthMask && depthMask != _depthMask;
+
+ if (stencilMaskChanged)
+ {
+ GL.StencilMaskSeparate(StencilFace.Front, stencilMask);
+ }
+
+ if (depthMaskChanged)
+ {
+ GL.DepthMask(depthMask);
+ }
+
+ if (depthMask && stencilMask != 0)
+ {
+ GL.ClearBuffer(ClearBufferCombined.DepthStencil, 0, depthValue, stencilValue);
+ }
+ else if (depthMask)
+ {
+ GL.ClearBuffer(ClearBuffer.Depth, 0, ref depthValue);
+ }
+ else if (stencilMask != 0)
+ {
+ GL.ClearBuffer(ClearBuffer.Stencil, 0, ref stencilValue);
+ }
+
+ if (stencilMaskChanged)
+ {
+ GL.StencilMaskSeparate(StencilFace.Front, _stencilFrontMask);
+ }
+
+ if (depthMaskChanged)
+ {
+ GL.DepthMask(_depthMask);
+ }
+ }
+
+ public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
+ {
+ if (!_program.IsLinked)
+ {
+ return;
+ }
+
+ PrepareForDraw();
+
+ if (firstInstance == 0 && instanceCount == 1)
+ {
+ if (_primitiveType == PrimitiveType.Quads)
+ {
+ for (int offset = 0; offset < vertexCount; offset += 4)
+ {
+ GL.DrawArrays(PrimitiveType.TriangleFan, firstVertex + offset, 4);
+ }
+ }
+ else if (_primitiveType == PrimitiveType.QuadStrip)
+ {
+ GL.DrawArrays(PrimitiveType.TriangleFan, firstVertex, 4);
+
+ for (int offset = 2; offset < vertexCount; offset += 2)
+ {
+ GL.DrawArrays(PrimitiveType.TriangleFan, firstVertex + offset, 4);
+ }
+ }
+ else
+ {
+ GL.DrawArrays(_primitiveType, firstVertex, vertexCount);
+ }
+
+ // GL.DrawArrays(_primitiveType, firstVertex, vertexCount);
+ }
+ else if (firstInstance == 0)
+ {
+ GL.DrawArraysInstanced(_primitiveType, firstVertex, vertexCount, instanceCount);
+ }
+ else
+ {
+ GL.DrawArraysInstancedBaseInstance(
+ _primitiveType,
+ firstVertex,
+ vertexCount,
+ instanceCount,
+ firstInstance);
+ }
+ }
+
+ public void DrawIndexed(
+ int indexCount,
+ int instanceCount,
+ int firstIndex,
+ int firstVertex,
+ int firstInstance)
+ {
+ if (!_program.IsLinked)
+ {
+ return;
+ }
+
+ PrepareForDraw();
+
+ int firstIndexOffset = firstIndex;
+
+ switch (_elementsType)
+ {
+ case DrawElementsType.UnsignedShort: firstIndexOffset *= 2; break;
+ case DrawElementsType.UnsignedInt: firstIndexOffset *= 4; break;
+ }
+
+ IntPtr indexBaseOffset = _indexBaseOffset + firstIndexOffset;
+
+ if (firstInstance == 0 && firstVertex == 0 && instanceCount == 1)
+ {
+ GL.DrawElements(_primitiveType, indexCount, _elementsType, indexBaseOffset);
+ }
+ else if (firstInstance == 0 && instanceCount == 1)
+ {
+ GL.DrawElementsBaseVertex(
+ _primitiveType,
+ indexCount,
+ _elementsType,
+ indexBaseOffset,
+ firstVertex);
+ }
+ else if (firstInstance == 0 && firstVertex == 0)
+ {
+ GL.DrawElementsInstanced(
+ _primitiveType,
+ indexCount,
+ _elementsType,
+ indexBaseOffset,
+ instanceCount);
+ }
+ else if (firstInstance == 0)
+ {
+ GL.DrawElementsInstancedBaseVertex(
+ _primitiveType,
+ indexCount,
+ _elementsType,
+ indexBaseOffset,
+ instanceCount,
+ firstVertex);
+ }
+ else if (firstVertex == 0)
+ {
+ GL.DrawElementsInstancedBaseInstance(
+ _primitiveType,
+ indexCount,
+ _elementsType,
+ indexBaseOffset,
+ instanceCount,
+ firstInstance);
+ }
+ else
+ {
+ GL.DrawElementsInstancedBaseVertexBaseInstance(
+ _primitiveType,
+ indexCount,
+ _elementsType,
+ indexBaseOffset,
+ instanceCount,
+ firstVertex,
+ firstInstance);
+ }
+ }
+
+ public void DrawIndirect(BufferRange buffer, ulong offset, int drawCount, int stride)
+ {
+
+ }
+
+ public void DrawIndexedIndirect(BufferRange buffer, ulong offset, int drawCount, int stride)
+ {
+
+ }
+
+ public void SetBlendColor(ColorF color)
+ {
+ GL.BlendColor(color.Red, color.Green, color.Blue, color.Alpha);
+ }
+
+ public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
+ {
+ if ((enables & PolygonModeMask.Point) != 0)
+ {
+ GL.Enable(EnableCap.PolygonOffsetPoint);
+ }
+ else
+ {
+ GL.Disable(EnableCap.PolygonOffsetPoint);
+ }
+
+ if ((enables & PolygonModeMask.Line) != 0)
+ {
+ GL.Enable(EnableCap.PolygonOffsetLine);
+ }
+ else
+ {
+ GL.Disable(EnableCap.PolygonOffsetLine);
+ }
+
+ if ((enables & PolygonModeMask.Fill) != 0)
+ {
+ GL.Enable(EnableCap.PolygonOffsetFill);
+ }
+ else
+ {
+ GL.Disable(EnableCap.PolygonOffsetFill);
+ }
+
+ if (enables == 0)
+ {
+ return;
+ }
+
+ GL.PolygonOffset(factor, units);
+ // GL.PolygonOffsetClamp(factor, units, clamp);
+ }
+
+ public void SetDepthTest(DepthTestDescriptor depthTest)
+ {
+ GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
+
+ _depthMask = depthTest.WriteEnable;
+ _depthTest = depthTest.TestEnable;
+
+ UpdateDepthTest();
+ }
+
+ public void SetFaceCulling(bool enable, Face face)
+ {
+ if (!enable)
+ {
+ GL.Disable(EnableCap.CullFace);
+
+ return;
+ }
+
+ GL.CullFace(face.Convert());
+
+ GL.Enable(EnableCap.CullFace);
+ }
+
+ public void SetFrontFace(FrontFace frontFace)
+ {
+ GL.FrontFace(frontFace.Convert());
+ }
+
+ public void SetPrimitiveRestart(bool enable, int index)
+ {
+ if (!enable)
+ {
+ GL.Disable(EnableCap.PrimitiveRestart);
+
+ return;
+ }
+
+ GL.PrimitiveRestartIndex(index);
+
+ GL.Enable(EnableCap.PrimitiveRestart);
+ }
+
+ public void SetPrimitiveTopology(PrimitiveTopology topology)
+ {
+ _primitiveType = topology.Convert();
+ }
+
+ public void SetRenderTargetColorMasks(uint[] componentMasks)
+ {
+ _componentMasks = (uint[])componentMasks.Clone();
+
+ for (int index = 0; index < componentMasks.Length; index++)
+ {
+ RestoreComponentMask(index);
+ }
+ }
+
+ public void SetRenderTargets(ITexture color3D, ITexture depthStencil)
+ {
+ EnsureFramebuffer();
+
+ TextureView color = (TextureView)color3D;
+
+ for (int index = 0; index < color.DepthOrLayers; index++)
+ {
+ _framebuffer.AttachColor(index, color, index);
+ }
+
+ TextureView depthStencilView = (TextureView)depthStencil;
+
+ _framebuffer.AttachDepthStencil(depthStencilView);
+
+ _framebuffer.SetDrawBuffers(color.DepthOrLayers);
+
+ _hasDepthBuffer = depthStencil != null && depthStencilView.Format != Format.S8Uint;
+
+ UpdateDepthTest();
+ }
+
+ public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
+ {
+ EnsureFramebuffer();
+
+ for (int index = 0; index < colors.Length; index++)
+ {
+ TextureView color = (TextureView)colors[index];
+
+ _framebuffer.AttachColor(index, color);
+ }
+
+ TextureView depthStencilView = (TextureView)depthStencil;
+
+ _framebuffer.AttachDepthStencil(depthStencilView);
+
+ _framebuffer.SetDrawBuffers(colors.Length);
+
+ _hasDepthBuffer = depthStencil != null && depthStencilView.Format != Format.S8Uint;
+
+ UpdateDepthTest();
+ }
+
+ public void SetStencilTest(StencilTestDescriptor stencilTest)
+ {
+ if (!stencilTest.TestEnable)
+ {
+ GL.Disable(EnableCap.StencilTest);
+
+ return;
+ }
+
+ GL.StencilOpSeparate(
+ StencilFace.Front,
+ stencilTest.FrontSFail.Convert(),
+ stencilTest.FrontDpFail.Convert(),
+ stencilTest.FrontDpPass.Convert());
+
+ GL.StencilFuncSeparate(
+ StencilFace.Front,
+ (StencilFunction)stencilTest.FrontFunc.Convert(),
+ stencilTest.FrontFuncRef,
+ stencilTest.FrontFuncMask);
+
+ GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
+
+ GL.StencilOpSeparate(
+ StencilFace.Back,
+ stencilTest.BackSFail.Convert(),
+ stencilTest.BackDpFail.Convert(),
+ stencilTest.BackDpPass.Convert());
+
+ GL.StencilFuncSeparate(
+ StencilFace.Back,
+ (StencilFunction)stencilTest.BackFunc.Convert(),
+ stencilTest.BackFuncRef,
+ stencilTest.BackFuncMask);
+
+ GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
+
+ GL.Enable(EnableCap.StencilTest);
+
+ _stencilFrontMask = stencilTest.FrontMask;
+ }
+
+ public void SetViewports(int first, Viewport[] viewports)
+ {
+ bool flipY = false;
+
+ float[] viewportArray = new float[viewports.Length * 4];
+
+ double[] depthRangeArray = new double[viewports.Length * 2];
+
+ for (int index = 0; index < viewports.Length; index++)
+ {
+ int viewportElemIndex = index * 4;
+
+ Viewport viewport = viewports[index];
+
+ viewportArray[viewportElemIndex + 0] = viewport.Region.X;
+ viewportArray[viewportElemIndex + 1] = viewport.Region.Y;
+
+ // OpenGL does not support per-viewport flipping, so
+ // instead we decide that based on the viewport 0 value.
+ // It will apply to all viewports.
+ if (index == 0)
+ {
+ flipY = viewport.Region.Height < 0;
+ }
+
+ if (viewport.SwizzleY == ViewportSwizzle.NegativeY)
+ {
+ flipY = !flipY;
+ }
+
+ viewportArray[viewportElemIndex + 2] = MathF.Abs(viewport.Region.Width);
+ viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
+
+ depthRangeArray[index * 2 + 0] = viewport.DepthNear;
+ depthRangeArray[index * 2 + 1] = viewport.DepthFar;
+ }
+
+ GL.ViewportArray(first, viewports.Length, viewportArray);
+
+ GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
+
+ SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
+ }
+
+ private void SetOrigin(ClipOrigin origin)
+ {
+ if (_clipOrigin != origin)
+ {
+ _clipOrigin = origin;
+
+ GL.ClipControl(origin, ClipDepthMode.NegativeOneToOne);
+ }
+ }
+
+ private void EnsureVertexArray()
+ {
+ if (_vertexArray == null)
+ {
+ _vertexArray = new VertexArray();
+
+ _vertexArray.Bind();
+ }
+ }
+
+ private void EnsureFramebuffer()
+ {
+ if (_framebuffer == null)
+ {
+ _framebuffer = new Framebuffer();
+
+ _framebuffer.Bind();
+
+ GL.Enable(EnableCap.FramebufferSrgb);
+ }
+ }
+
+ private void UpdateDepthTest()
+ {
+ // Enabling depth operations is only valid when we have
+ // a depth buffer, otherwise it's not allowed.
+ if (_hasDepthBuffer)
+ {
+ if (_depthTest)
+ {
+ GL.Enable(EnableCap.DepthTest);
+ }
+ else
+ {
+ GL.Disable(EnableCap.DepthTest);
+ }
+
+ GL.DepthMask(_depthMask);
+ }
+ else
+ {
+ GL.Disable(EnableCap.DepthTest);
+
+ GL.DepthMask(false);
+ }
+ }
+
+ private void PrepareForDraw()
+ {
+ _vertexArray.Validate();
+
+ if (_unit0Texture != null)
+ {
+ _unit0Texture.Bind(0);
+ }
+ }
+
+ private void RestoreComponentMask(int index)
+ {
+ GL.ColorMask(
+ index,
+ (_componentMasks[index] & 1u) != 0,
+ (_componentMasks[index] & 2u) != 0,
+ (_componentMasks[index] & 4u) != 0,
+ (_componentMasks[index] & 8u) != 0);
+ }
+
+ public void RebindProgram()
+ {
+ _program?.Bind();
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/HwCapabilities.cs b/Ryujinx.Graphics.OpenGL/HwCapabilities.cs
new file mode 100644
index 000000000..f958946e7
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/HwCapabilities.cs
@@ -0,0 +1,27 @@
+using OpenTK.Graphics.OpenGL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class HwCapabilities
+ {
+ private static Lazy _astcCompression = new Lazy(() => HasExtension("GL_KHR_texture_compression_astc_ldr"));
+
+ public static bool SupportsAstcCompression => _astcCompression.Value;
+
+ private static bool HasExtension(string name)
+ {
+ int numExtensions = GL.GetInteger(GetPName.NumExtensions);
+
+ for (int extension = 0; extension < numExtensions; extension++)
+ {
+ if (GL.GetString(StringNameIndexed.Extensions, extension) == name)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.OpenGL/Program.cs b/Ryujinx.Graphics.OpenGL/Program.cs
new file mode 100644
index 000000000..1f95b449d
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Program.cs
@@ -0,0 +1,175 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Shader;
+using OpenTK.Graphics.OpenGL;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class Program : IProgram
+ {
+ private const int StageShift = 5;
+ private const int SbStageShift = 4;
+
+ public int Handle { get; private set; }
+
+ public bool IsLinked { get; private set; }
+
+ private int[] _ubBindingPoints;
+ private int[] _sbBindingPoints;
+ private int[] _textureUnits;
+
+ public Program(IShader[] shaders)
+ {
+ _ubBindingPoints = new int[32 * 6];
+ _sbBindingPoints = new int[16 * 6];
+ _textureUnits = new int[32 * 6];
+
+ for (int index = 0; index < _ubBindingPoints.Length; index++)
+ {
+ _ubBindingPoints[index] = -1;
+ }
+
+ for (int index = 0; index < _sbBindingPoints.Length; index++)
+ {
+ _sbBindingPoints[index] = -1;
+ }
+
+ for (int index = 0; index < _textureUnits.Length; index++)
+ {
+ _textureUnits[index] = -1;
+ }
+
+ Handle = GL.CreateProgram();
+
+ for (int index = 0; index < shaders.Length; index++)
+ {
+ int shaderHandle = ((Shader)shaders[index]).Handle;
+
+ GL.AttachShader(Handle, shaderHandle);
+ }
+
+ GL.LinkProgram(Handle);
+
+ CheckProgramLink();
+
+ Bind();
+
+ int extraBlockindex = GL.GetUniformBlockIndex(Handle, "Extra");
+
+ if (extraBlockindex >= 0)
+ {
+ GL.UniformBlockBinding(Handle, extraBlockindex, 0);
+ }
+
+ int ubBindingPoint = 1;
+ int sbBindingPoint = 0;
+ int textureUnit = 0;
+
+ for (int index = 0; index < shaders.Length; index++)
+ {
+ Shader shader = (Shader)shaders[index];
+
+ foreach (BufferDescriptor descriptor in shader.Info.CBuffers)
+ {
+ int location = GL.GetUniformBlockIndex(Handle, descriptor.Name);
+
+ if (location < 0)
+ {
+ continue;
+ }
+
+ GL.UniformBlockBinding(Handle, location, ubBindingPoint);
+
+ int bpIndex = (int)shader.Stage << StageShift | descriptor.Slot;
+
+ _ubBindingPoints[bpIndex] = ubBindingPoint;
+
+ ubBindingPoint++;
+ }
+
+ foreach (BufferDescriptor descriptor in shader.Info.SBuffers)
+ {
+ int location = GL.GetProgramResourceIndex(Handle, ProgramInterface.ShaderStorageBlock, descriptor.Name);
+
+ if (location < 0)
+ {
+ continue;
+ }
+
+ GL.ShaderStorageBlockBinding(Handle, location, sbBindingPoint);
+
+ int bpIndex = (int)shader.Stage << SbStageShift | descriptor.Slot;
+
+ _sbBindingPoints[bpIndex] = sbBindingPoint;
+
+ sbBindingPoint++;
+ }
+
+ int samplerIndex = 0;
+
+ foreach (TextureDescriptor descriptor in shader.Info.Textures)
+ {
+ int location = GL.GetUniformLocation(Handle, descriptor.Name);
+
+ if (location < 0)
+ {
+ continue;
+ }
+
+ GL.Uniform1(location, textureUnit);
+
+ int uIndex = (int)shader.Stage << StageShift | samplerIndex++;
+
+ _textureUnits[uIndex] = textureUnit;
+
+ textureUnit++;
+ }
+ }
+ }
+
+ public void Bind()
+ {
+ GL.UseProgram(Handle);
+ }
+
+ public int GetUniformBufferBindingPoint(ShaderStage stage, int index)
+ {
+ return _ubBindingPoints[(int)stage << StageShift | index];
+ }
+
+ public int GetStorageBufferBindingPoint(ShaderStage stage, int index)
+ {
+ return _sbBindingPoints[(int)stage << SbStageShift | index];
+ }
+
+ public int GetTextureUnit(ShaderStage stage, int index)
+ {
+ return _textureUnits[(int)stage << StageShift | index];
+ }
+
+ private void CheckProgramLink()
+ {
+ int status = 0;
+
+ GL.GetProgram(Handle, GetProgramParameterName.LinkStatus, out status);
+
+ if (status == 0)
+ {
+ // throw new System.Exception(GL.GetProgramInfoLog(Handle));
+ }
+ else
+ {
+ IsLinked = true;
+ }
+ }
+
+ public void Dispose()
+ {
+ if (Handle != 0)
+ {
+ GL.DeleteProgram(Handle);
+
+ Handle = 0;
+ }
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Renderer.cs b/Ryujinx.Graphics.OpenGL/Renderer.cs
new file mode 100644
index 000000000..56ba76244
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Renderer.cs
@@ -0,0 +1,84 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Sampler;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.Shader;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ public class Renderer : IRenderer
+ {
+ public IComputePipeline ComputePipeline { get; }
+ public IGraphicsPipeline GraphicsPipeline { get; }
+
+ private Counters _counters;
+
+ private Window _window;
+
+ public IWindow Window => _window;
+
+ internal TextureCopy TextureCopy { get; }
+
+ public Renderer()
+ {
+ ComputePipeline = new ComputePipeline(this);
+ GraphicsPipeline = new GraphicsPipeline();
+
+ _counters = new Counters();
+
+ _window = new Window();
+
+ TextureCopy = new TextureCopy();
+ }
+
+ public IShader CompileShader(ShaderProgram shader)
+ {
+ return new Shader(shader);
+ }
+
+ public IBuffer CreateBuffer(int size)
+ {
+ return new Buffer(size);
+ }
+
+ public IProgram CreateProgram(IShader[] shaders)
+ {
+ return new Program(shaders);
+ }
+
+ public ISampler CreateSampler(SamplerCreateInfo info)
+ {
+ return new Sampler(info);
+ }
+
+ public ITexture CreateTexture(TextureCreateInfo info)
+ {
+ return new TextureStorage(this, info).CreateDefaultView();
+ }
+
+ public void FlushPipelines()
+ {
+ GL.Finish();
+ }
+
+ public Capabilities GetCapabilities()
+ {
+ return new Capabilities(HwCapabilities.SupportsAstcCompression);
+ }
+
+ public ulong GetCounter(CounterType type)
+ {
+ return _counters.GetCounter(type);
+ }
+
+ public void InitializeCounters()
+ {
+ _counters.Initialize();
+ }
+
+ public void ResetCounter(CounterType type)
+ {
+ _counters.ResetCounter(type);
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Ryujinx.Graphics.OpenGL.csproj b/Ryujinx.Graphics.OpenGL/Ryujinx.Graphics.OpenGL.csproj
new file mode 100644
index 000000000..484e8682c
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Ryujinx.Graphics.OpenGL.csproj
@@ -0,0 +1,17 @@
+
+
+
+ true
+ netcoreapp3.0
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Ryujinx.Graphics.OpenGL/Sampler.cs b/Ryujinx.Graphics.OpenGL/Sampler.cs
new file mode 100644
index 000000000..9b9f09a10
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Sampler.cs
@@ -0,0 +1,60 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Sampler;
+using OpenTK.Graphics.OpenGL;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class Sampler : ISampler
+ {
+ public int Handle { get; private set; }
+
+ public Sampler(SamplerCreateInfo info)
+ {
+ Handle = GL.GenSampler();
+
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureMinFilter, (int)info.MinFilter.Convert());
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureMagFilter, (int)info.MagFilter.Convert());
+
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureWrapS, (int)info.AddressU.Convert());
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureWrapT, (int)info.AddressV.Convert());
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureWrapR, (int)info.AddressP.Convert());
+
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureCompareMode, (int)info.CompareMode.Convert());
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureCompareFunc, (int)info.CompareOp.Convert());
+
+ unsafe
+ {
+ float* borderColor = stackalloc float[4]
+ {
+ info.BorderColor.Red,
+ info.BorderColor.Green,
+ info.BorderColor.Blue,
+ info.BorderColor.Alpha
+ };
+
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureBorderColor, borderColor);
+ }
+
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureMinLod, info.MinLod);
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureMaxLod, info.MaxLod);
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureLodBias, info.MipLodBias);
+
+ GL.SamplerParameter(Handle, SamplerParameterName.TextureMaxAnisotropyExt, info.MaxAnisotropy);
+ }
+
+ public void Bind(int unit)
+ {
+ GL.BindSampler(unit, Handle);
+ }
+
+ public void Dispose()
+ {
+ if (Handle != 0)
+ {
+ GL.DeleteSampler(Handle);
+
+ Handle = 0;
+ }
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Shader.cs b/Ryujinx.Graphics.OpenGL/Shader.cs
new file mode 100644
index 000000000..f25845cfd
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Shader.cs
@@ -0,0 +1,49 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.Shader;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class Shader : IShader
+ {
+ public int Handle { get; private set; }
+
+ private ShaderProgram _program;
+
+ public ShaderProgramInfo Info => _program.Info;
+
+ public ShaderStage Stage => _program.Stage;
+
+ public Shader(ShaderProgram program)
+ {
+ _program = program;
+
+ ShaderType type = ShaderType.VertexShader;
+
+ switch (program.Stage)
+ {
+ case ShaderStage.Compute: type = ShaderType.ComputeShader; break;
+ case ShaderStage.Vertex: type = ShaderType.VertexShader; break;
+ case ShaderStage.TessellationControl: type = ShaderType.TessControlShader; break;
+ case ShaderStage.TessellationEvaluation: type = ShaderType.TessEvaluationShader; break;
+ case ShaderStage.Geometry: type = ShaderType.GeometryShader; break;
+ case ShaderStage.Fragment: type = ShaderType.FragmentShader; break;
+ }
+
+ Handle = GL.CreateShader(type);
+
+ GL.ShaderSource(Handle, program.Code);
+ GL.CompileShader(Handle);
+ }
+
+ public void Dispose()
+ {
+ if (Handle != 0)
+ {
+ GL.DeleteShader(Handle);
+
+ Handle = 0;
+ }
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/TextureCopy.cs b/Ryujinx.Graphics.OpenGL/TextureCopy.cs
new file mode 100644
index 000000000..75ef07c15
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/TextureCopy.cs
@@ -0,0 +1,128 @@
+using Ryujinx.Graphics.GAL;
+using OpenTK.Graphics.OpenGL;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class TextureCopy
+ {
+ private int _srcFramebuffer;
+ private int _dstFramebuffer;
+
+ public void Copy(
+ TextureView src,
+ TextureView dst,
+ Extents2D srcRegion,
+ Extents2D dstRegion,
+ bool linearFilter)
+ {
+ GL.Disable(EnableCap.FramebufferSrgb);
+
+ int oldReadFramebufferHandle = GL.GetInteger(GetPName.ReadFramebufferBinding);
+ int oldDrawFramebufferHandle = GL.GetInteger(GetPName.DrawFramebufferBinding);
+
+ GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, GetSrcFramebufferLazy());
+ GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, GetDstFramebufferLazy());
+
+ Attach(FramebufferTarget.ReadFramebuffer, src.Format, src.Handle);
+ Attach(FramebufferTarget.DrawFramebuffer, dst.Format, dst.Handle);
+
+ ClearBufferMask mask = GetMask(src.Format);
+
+ BlitFramebufferFilter filter = linearFilter
+ ? BlitFramebufferFilter.Linear
+ : BlitFramebufferFilter.Nearest;
+
+ GL.ReadBuffer(ReadBufferMode.ColorAttachment0);
+ GL.DrawBuffer(DrawBufferMode.ColorAttachment0);
+
+ GL.BlitFramebuffer(
+ srcRegion.X1,
+ srcRegion.Y1,
+ srcRegion.X2,
+ srcRegion.Y2,
+ dstRegion.X1,
+ dstRegion.Y1,
+ dstRegion.X2,
+ dstRegion.Y2,
+ mask,
+ filter);
+
+ GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, oldReadFramebufferHandle);
+ GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, oldDrawFramebufferHandle);
+
+ GL.Enable(EnableCap.FramebufferSrgb);
+ }
+
+ private static void Detach(FramebufferTarget target, Format format)
+ {
+ Attach(target, format, 0);
+ }
+
+ private static void Attach(FramebufferTarget target, Format format, int handle)
+ {
+ if (format == Format.D24UnormS8Uint || format == Format.D32FloatS8Uint)
+ {
+ GL.FramebufferTexture(target, FramebufferAttachment.DepthStencilAttachment, handle, 0);
+ }
+ else if (IsDepthOnly(format))
+ {
+ GL.FramebufferTexture(target, FramebufferAttachment.DepthAttachment, handle, 0);
+ }
+ else if (format == Format.S8Uint)
+ {
+ GL.FramebufferTexture(target, FramebufferAttachment.StencilAttachment, handle, 0);
+ }
+ else
+ {
+ GL.FramebufferTexture(target, FramebufferAttachment.ColorAttachment0, handle, 0);
+ }
+ }
+
+ private static ClearBufferMask GetMask(Format format)
+ {
+ if (format == Format.D24UnormS8Uint || format == Format.D32FloatS8Uint)
+ {
+ return ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit;
+ }
+ else if (IsDepthOnly(format))
+ {
+ return ClearBufferMask.DepthBufferBit;
+ }
+ else if (format == Format.S8Uint)
+ {
+ return ClearBufferMask.StencilBufferBit;
+ }
+ else
+ {
+ return ClearBufferMask.ColorBufferBit;
+ }
+ }
+
+ private static bool IsDepthOnly(Format format)
+ {
+ return format == Format.D16Unorm ||
+ format == Format.D24X8Unorm ||
+ format == Format.D32Float;
+ }
+
+ private int GetSrcFramebufferLazy()
+ {
+ if (_srcFramebuffer == 0)
+ {
+ _srcFramebuffer = GL.GenFramebuffer();
+ }
+
+ return _srcFramebuffer;
+ }
+
+ private int GetDstFramebufferLazy()
+ {
+ if (_dstFramebuffer == 0)
+ {
+ _dstFramebuffer = GL.GenFramebuffer();
+ }
+
+ return _dstFramebuffer;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/TextureCopyUnscaled.cs b/Ryujinx.Graphics.OpenGL/TextureCopyUnscaled.cs
new file mode 100644
index 000000000..dae492d9e
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/TextureCopyUnscaled.cs
@@ -0,0 +1,85 @@
+using Ryujinx.Common;
+using Ryujinx.Graphics.GAL.Texture;
+using OpenTK.Graphics.OpenGL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ static class TextureCopyUnscaled
+ {
+ public static void Copy(TextureView src, TextureView dst, int dstLayer, int dstLevel)
+ {
+ int srcWidth = src.Width;
+ int srcHeight = src.Height;
+ int srcDepth = src.DepthOrLayers;
+ int srcLevels = src.Levels;
+
+ srcWidth = Math.Max(1, srcWidth >> dstLevel);
+ srcHeight = Math.Max(1, srcHeight >> dstLevel);
+
+ if (src.Target == Target.Texture3D)
+ {
+ srcDepth = Math.Max(1, srcDepth >> dstLevel);
+ }
+
+ int dstWidth = dst.Width;
+ int dstHeight = dst.Height;
+ int dstDepth = dst.DepthOrLayers;
+ int dstLevels = dst.Levels;
+
+ // When copying from a compressed to a non-compressed format,
+ // the non-compressed texture will have the size of the texture
+ // in blocks (not in texels), so we must adjust that size to
+ // match the size in texels of the compressed texture.
+ if (!src.IsCompressed && dst.IsCompressed)
+ {
+ dstWidth = BitUtils.DivRoundUp(dstWidth, dst.BlockWidth);
+ dstHeight = BitUtils.DivRoundUp(dstHeight, dst.BlockHeight);
+ }
+ else if (src.IsCompressed && !dst.IsCompressed)
+ {
+ dstWidth *= dst.BlockWidth;
+ dstHeight *= dst.BlockHeight;
+ }
+
+ int width = Math.Min(srcWidth, dstWidth);
+ int height = Math.Min(srcHeight, dstHeight);
+ int depth = Math.Min(srcDepth, dstDepth);
+ int levels = Math.Min(srcLevels, dstLevels);
+
+ for (int level = 0; level < levels; level++)
+ {
+ // Stop copy if we are already out of the levels range.
+ if (level >= src.Levels || dstLevel + level >= dst.Levels)
+ {
+ break;
+ }
+
+ GL.CopyImageSubData(
+ src.Handle,
+ src.Target.ConvertToImageTarget(),
+ level,
+ 0,
+ 0,
+ 0,
+ dst.Handle,
+ dst.Target.ConvertToImageTarget(),
+ dstLevel + level,
+ 0,
+ 0,
+ dstLayer,
+ width,
+ height,
+ depth);
+
+ width = Math.Max(1, width >> 1);
+ height = Math.Max(1, height >> 1);
+
+ if (src.Target == Target.Texture3D)
+ {
+ depth = Math.Max(1, depth >> 1);
+ }
+ }
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/TextureStorage.cs b/Ryujinx.Graphics.OpenGL/TextureStorage.cs
new file mode 100644
index 000000000..d74b0a8ef
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/TextureStorage.cs
@@ -0,0 +1,179 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.OpenGL.Formats;
+using OpenTK.Graphics.OpenGL;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class TextureStorage
+ {
+ public int Handle { get; private set; }
+
+ private Renderer _renderer;
+
+ private TextureCreateInfo _info;
+
+ public Target Target => _info.Target;
+
+ private int _viewsCount;
+
+ public TextureStorage(Renderer renderer, TextureCreateInfo info)
+ {
+ _renderer = renderer;
+ _info = info;
+
+ Handle = GL.GenTexture();
+
+ CreateImmutableStorage();
+ }
+
+ private void CreateImmutableStorage()
+ {
+ TextureTarget target = _info.Target.Convert();
+
+ GL.ActiveTexture(TextureUnit.Texture0);
+
+ GL.BindTexture(target, Handle);
+
+ FormatInfo format = FormatTable.GetFormatInfo(_info.Format);
+
+ SizedInternalFormat internalFormat;
+
+ if (format.IsCompressed)
+ {
+ internalFormat = (SizedInternalFormat)format.PixelFormat;
+ }
+ else
+ {
+ internalFormat = (SizedInternalFormat)format.PixelInternalFormat;
+ }
+
+ switch (_info.Target)
+ {
+ case Target.Texture1D:
+ GL.TexStorage1D(
+ TextureTarget1d.Texture1D,
+ _info.Levels,
+ internalFormat,
+ _info.Width);
+ break;
+
+ case Target.Texture1DArray:
+ GL.TexStorage2D(
+ TextureTarget2d.Texture1DArray,
+ _info.Levels,
+ internalFormat,
+ _info.Width,
+ _info.Height);
+ break;
+
+ case Target.Texture2D:
+ GL.TexStorage2D(
+ TextureTarget2d.Texture2D,
+ _info.Levels,
+ internalFormat,
+ _info.Width,
+ _info.Height);
+ break;
+
+ case Target.Texture2DArray:
+ GL.TexStorage3D(
+ TextureTarget3d.Texture2DArray,
+ _info.Levels,
+ internalFormat,
+ _info.Width,
+ _info.Height,
+ _info.Depth);
+ break;
+
+ case Target.Texture2DMultisample:
+ GL.TexStorage2DMultisample(
+ TextureTargetMultisample2d.Texture2DMultisample,
+ _info.Samples,
+ internalFormat,
+ _info.Width,
+ _info.Height,
+ true);
+ break;
+
+ case Target.Texture2DMultisampleArray:
+ GL.TexStorage3DMultisample(
+ TextureTargetMultisample3d.Texture2DMultisampleArray,
+ _info.Samples,
+ internalFormat,
+ _info.Width,
+ _info.Height,
+ _info.Depth,
+ true);
+ break;
+
+ case Target.Texture3D:
+ GL.TexStorage3D(
+ TextureTarget3d.Texture3D,
+ _info.Levels,
+ internalFormat,
+ _info.Width,
+ _info.Height,
+ _info.Depth);
+ break;
+
+ case Target.Cubemap:
+ GL.TexStorage2D(
+ TextureTarget2d.TextureCubeMap,
+ _info.Levels,
+ internalFormat,
+ _info.Width,
+ _info.Height);
+ break;
+
+ case Target.CubemapArray:
+ GL.TexStorage3D(
+ (TextureTarget3d)All.TextureCubeMapArray,
+ _info.Levels,
+ internalFormat,
+ _info.Width,
+ _info.Height,
+ _info.Depth);
+ break;
+ }
+ }
+
+ public ITexture CreateDefaultView()
+ {
+ int layers = _info.GetLayers();
+
+ return CreateView(_info, 0, 0);
+ }
+
+ public ITexture CreateView(TextureCreateInfo info, int firstLayer, int firstLevel)
+ {
+ IncrementViewsCount();
+
+ return new TextureView(_renderer, this, info, firstLayer, firstLevel);
+ }
+
+ private void IncrementViewsCount()
+ {
+ _viewsCount++;
+ }
+
+ public void DecrementViewsCount()
+ {
+ // If we don't have any views, then the storage is now useless, delete it.
+ if (--_viewsCount == 0)
+ {
+ Dispose();
+ }
+ }
+
+ public void Dispose()
+ {
+ if (Handle != 0)
+ {
+ GL.DeleteTexture(Handle);
+
+ Handle = 0;
+ }
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/TextureView.cs b/Ryujinx.Graphics.OpenGL/TextureView.cs
new file mode 100644
index 000000000..8a2b50dc4
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/TextureView.cs
@@ -0,0 +1,425 @@
+using Ryujinx.Graphics.GAL;
+using Ryujinx.Graphics.GAL.Texture;
+using Ryujinx.Graphics.OpenGL.Formats;
+using OpenTK.Graphics.OpenGL;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class TextureView : ITexture
+ {
+ public int Handle { get; private set; }
+
+ private Renderer _renderer;
+
+ private TextureStorage _parent;
+
+ private TextureView _emulatedViewParent;
+
+ private TextureCreateInfo _info;
+
+ private int _firstLayer;
+ private int _firstLevel;
+
+ private bool _acquired;
+ private bool _pendingDelete;
+
+ public int Width => _info.Width;
+ public int Height => _info.Height;
+ public int DepthOrLayers => _info.GetDepthOrLayers();
+ public int Levels => _info.Levels;
+
+ public Target Target => _info.Target;
+ public Format Format => _info.Format;
+
+ public int BlockWidth => _info.BlockWidth;
+ public int BlockHeight => _info.BlockHeight;
+
+ public bool IsCompressed => _info.IsCompressed;
+
+ public TextureView(
+ Renderer renderer,
+ TextureStorage parent,
+ TextureCreateInfo info,
+ int firstLayer,
+ int firstLevel)
+ {
+ _renderer = renderer;
+ _parent = parent;
+ _info = info;
+
+ _firstLayer = firstLayer;
+ _firstLevel = firstLevel;
+
+ Handle = GL.GenTexture();
+
+ CreateView();
+ }
+
+ private void CreateView()
+ {
+ TextureTarget target = Target.Convert();
+
+ FormatInfo format = FormatTable.GetFormatInfo(_info.Format);
+
+ PixelInternalFormat pixelInternalFormat;
+
+ if (format.IsCompressed)
+ {
+ pixelInternalFormat = (PixelInternalFormat)format.PixelFormat;
+ }
+ else
+ {
+ pixelInternalFormat = format.PixelInternalFormat;
+ }
+
+ GL.TextureView(
+ Handle,
+ target,
+ _parent.Handle,
+ pixelInternalFormat,
+ _firstLevel,
+ _info.Levels,
+ _firstLayer,
+ _info.GetLayers());
+
+ GL.ActiveTexture(TextureUnit.Texture0);
+
+ GL.BindTexture(target, Handle);
+
+ int[] swizzleRgba = new int[]
+ {
+ (int)_info.SwizzleR.Convert(),
+ (int)_info.SwizzleG.Convert(),
+ (int)_info.SwizzleB.Convert(),
+ (int)_info.SwizzleA.Convert()
+ };
+
+ GL.TexParameter(target, TextureParameterName.TextureSwizzleRgba, swizzleRgba);
+
+ int maxLevel = _info.Levels - 1;
+
+ if (maxLevel < 0)
+ {
+ maxLevel = 0;
+ }
+
+ GL.TexParameter(target, TextureParameterName.TextureMaxLevel, maxLevel);
+
+ // GL.TexParameter(target, TextureParameterName.DepthStencilTextureMode, (int)_info.DepthStencilMode.Convert());
+ }
+
+ public ITexture CreateView(TextureCreateInfo info, int firstLayer, int firstLevel)
+ {
+ if (_info.IsCompressed == info.IsCompressed)
+ {
+ firstLayer += _firstLayer;
+ firstLevel += _firstLevel;
+
+ return _parent.CreateView(info, firstLayer, firstLevel);
+ }
+ else
+ {
+ // TODO: Improve
+ TextureView emulatedView = (TextureView)_renderer.CreateTexture(info);
+
+ emulatedView._emulatedViewParent = this;
+
+ emulatedView._firstLayer = firstLayer;
+ emulatedView._firstLevel = firstLevel;
+
+ return emulatedView;
+ }
+ }
+
+ public int GetStorageDebugId()
+ {
+ return _parent.GetHashCode();
+ }
+
+ public void CopyTo(ITexture destination)
+ {
+ TextureView destinationView = (TextureView)destination;
+
+ TextureCopyUnscaled.Copy(this, destinationView, 0, 0);
+
+ int width = Math.Min(Width, destinationView.Width);
+ int height = Math.Min(Height, destinationView.Height);
+
+ int depth = Math.Min(_info.GetDepthOrLayers(), destinationView._info.GetDepthOrLayers());
+
+ int levels = Math.Min(_info.Levels, destinationView._info.Levels);
+
+ if (destinationView._emulatedViewParent != null)
+ {
+ TextureCopyUnscaled.Copy(
+ this,
+ destinationView._emulatedViewParent,
+ destinationView._firstLayer,
+ destinationView._firstLevel);
+ }
+ }
+
+ public void CopyTo(ITexture destination, Extents2D srcRegion, Extents2D dstRegion, bool linearFilter)
+ {
+ _renderer.TextureCopy.Copy(this, (TextureView)destination, srcRegion, dstRegion, linearFilter);
+ }
+
+ public byte[] GetData(int face)
+ {
+ TextureTarget target = Target.Convert();
+
+ Bind(target, 0);
+
+ FormatInfo format = FormatTable.GetFormatInfo(_info.Format);
+
+ int depth = _info.GetDepthOrLayers();
+
+ if (target == TextureTarget.TextureCubeMap)
+ {
+ target = TextureTarget.TextureCubeMapPositiveX + face;
+ }
+
+ if (format.IsCompressed)
+ {
+ byte[] data = new byte[_info.Width * _info.Height * depth * 4];
+
+ GL.GetTexImage(target, 0, PixelFormat.Rgba, PixelType.UnsignedByte, data);
+
+ return data;
+ }
+ else
+ {
+ byte[] data = new byte[_info.GetMipSize(0)];
+
+ GL.GetTexImage(target, 0, format.PixelFormat, format.PixelType, data);
+
+ return data;
+ }
+ }
+
+ public void SetData(Span data)
+ {
+ unsafe
+ {
+ fixed (byte* ptr = data)
+ {
+ SetData((IntPtr)ptr, data.Length);
+ }
+ }
+ }
+
+ private void SetData(IntPtr data, int size)
+ {
+ TextureTarget target = Target.Convert();
+
+ Bind(target, 0);
+
+ FormatInfo format = FormatTable.GetFormatInfo(_info.Format);
+
+ int width = _info.Width;
+ int height = _info.Height;
+ int depth = _info.Depth;
+
+ int offset = 0;
+
+ for (int level = 0; level < _info.Levels; level++)
+ {
+ int mipSize = _info.GetMipSize(level);
+
+ int endOffset = offset + mipSize;
+
+ if ((uint)endOffset > (uint)size)
+ {
+ return;
+ }
+
+ switch (_info.Target)
+ {
+ case Target.Texture1D:
+ if (format.IsCompressed)
+ {
+ GL.CompressedTexSubImage1D(
+ target,
+ level,
+ 0,
+ width,
+ format.PixelFormat,
+ mipSize,
+ data);
+ }
+ else
+ {
+ GL.TexSubImage1D(
+ target,
+ level,
+ 0,
+ width,
+ format.PixelFormat,
+ format.PixelType,
+ data);
+ }
+ break;
+
+ case Target.Texture1DArray:
+ case Target.Texture2D:
+ if (format.IsCompressed)
+ {
+ GL.CompressedTexSubImage2D(
+ target,
+ level,
+ 0,
+ 0,
+ width,
+ height,
+ format.PixelFormat,
+ mipSize,
+ data);
+ }
+ else
+ {
+ GL.TexSubImage2D(
+ target,
+ level,
+ 0,
+ 0,
+ width,
+ height,
+ format.PixelFormat,
+ format.PixelType,
+ data);
+ }
+ break;
+
+ case Target.Texture2DArray:
+ case Target.Texture3D:
+ case Target.CubemapArray:
+ if (format.IsCompressed)
+ {
+ GL.CompressedTexSubImage3D(
+ target,
+ level,
+ 0,
+ 0,
+ 0,
+ width,
+ height,
+ depth,
+ format.PixelFormat,
+ mipSize,
+ data);
+ }
+ else
+ {
+ GL.TexSubImage3D(
+ target,
+ level,
+ 0,
+ 0,
+ 0,
+ width,
+ height,
+ depth,
+ format.PixelFormat,
+ format.PixelType,
+ data);
+ }
+ break;
+
+ case Target.Cubemap:
+ int faceOffset = 0;
+
+ for (int face = 0; face < 6; face++, faceOffset += mipSize / 6)
+ {
+ if (format.IsCompressed)
+ {
+ GL.CompressedTexSubImage2D(
+ TextureTarget.TextureCubeMapPositiveX + face,
+ level,
+ 0,
+ 0,
+ width,
+ height,
+ format.PixelFormat,
+ mipSize / 6,
+ data + faceOffset);
+ }
+ else
+ {
+ GL.TexSubImage2D(
+ TextureTarget.TextureCubeMapPositiveX + face,
+ level,
+ 0,
+ 0,
+ width,
+ height,
+ format.PixelFormat,
+ format.PixelType,
+ data + faceOffset);
+ }
+ }
+ break;
+ }
+
+ data += mipSize;
+ offset += mipSize;
+
+ width = Math.Max(1, width >> 1);
+ height = Math.Max(1, height >> 1);
+
+ if (Target == Target.Texture3D)
+ {
+ depth = Math.Max(1, depth >> 1);
+ }
+ }
+ }
+
+ public void Bind(int unit)
+ {
+ Bind(Target.Convert(), unit);
+ }
+
+ private void Bind(TextureTarget target, int unit)
+ {
+ GL.ActiveTexture(TextureUnit.Texture0 + unit);
+
+ GL.BindTexture(target, Handle);
+ }
+
+ public void Acquire()
+ {
+ _acquired = true;
+ }
+
+ public void Release()
+ {
+ _acquired = false;
+
+ if (_pendingDelete)
+ {
+ _pendingDelete = false;
+
+ Dispose();
+ }
+ }
+
+ public void Dispose()
+ {
+ if (_acquired)
+ {
+ _pendingDelete = true;
+
+ return;
+ }
+
+ if (Handle != 0)
+ {
+ GL.DeleteTexture(Handle);
+
+ _parent.DecrementViewsCount();
+
+ Handle = 0;
+ }
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/VertexArray.cs b/Ryujinx.Graphics.OpenGL/VertexArray.cs
new file mode 100644
index 000000000..cf87c9530
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/VertexArray.cs
@@ -0,0 +1,135 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL.InputAssembler;
+using Ryujinx.Graphics.OpenGL.Formats;
+using System;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class VertexArray : IDisposable
+ {
+ public int Handle { get; }
+
+ private bool _needsAttribsUpdate;
+
+ private VertexBufferDescriptor[] _vertexBuffers;
+ private VertexAttribDescriptor[] _vertexAttribs;
+
+ public VertexArray()
+ {
+ Handle = GL.GenVertexArray();
+ }
+
+ public void Bind()
+ {
+ GL.BindVertexArray(Handle);
+ }
+
+ public void SetVertexBuffers(VertexBufferDescriptor[] vertexBuffers)
+ {
+ int bindingIndex = 0;
+
+ foreach (VertexBufferDescriptor vb in vertexBuffers)
+ {
+ if (vb.Buffer.Buffer != null)
+ {
+ int bufferHandle = ((Buffer)vb.Buffer.Buffer).Handle;
+
+ GL.BindVertexBuffer(bindingIndex, bufferHandle, (IntPtr)vb.Buffer.Offset, vb.Stride);
+
+ GL.VertexBindingDivisor(bindingIndex, vb.Divisor);
+ }
+ else
+ {
+ GL.BindVertexBuffer(bindingIndex, 0, IntPtr.Zero, 0);
+ }
+
+ bindingIndex++;
+ }
+
+ _vertexBuffers = vertexBuffers;
+
+ _needsAttribsUpdate = true;
+ }
+
+ public void SetVertexAttributes(VertexAttribDescriptor[] vertexAttribs)
+ {
+ int attribIndex = 0;
+
+ foreach (VertexAttribDescriptor attrib in vertexAttribs)
+ {
+ FormatInfo fmtInfo = FormatTable.GetFormatInfo(attrib.Format);
+
+ GL.EnableVertexAttribArray(attribIndex);
+
+ int offset = attrib.Offset;
+ int size = fmtInfo.Components;
+
+ bool isFloat = fmtInfo.PixelType == PixelType.Float ||
+ fmtInfo.PixelType == PixelType.HalfFloat;
+
+ if (isFloat || fmtInfo.Normalized || fmtInfo.Scaled)
+ {
+ VertexAttribType type = (VertexAttribType)fmtInfo.PixelType;
+
+ GL.VertexAttribFormat(attribIndex, size, type, fmtInfo.Normalized, offset);
+ }
+ else
+ {
+ VertexAttribIntegerType type = (VertexAttribIntegerType)fmtInfo.PixelType;
+
+ GL.VertexAttribIFormat(attribIndex, size, type, offset);
+ }
+
+ GL.VertexAttribBinding(attribIndex, attrib.BufferIndex);
+
+ attribIndex++;
+ }
+
+ for (; attribIndex < 16; attribIndex++)
+ {
+ GL.DisableVertexAttribArray(attribIndex);
+ }
+
+ _vertexAttribs = vertexAttribs;
+ }
+
+ public void SetIndexBuffer(Buffer indexBuffer)
+ {
+ GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBuffer?.Handle ?? 0);
+ }
+
+ public void Validate()
+ {
+ for (int attribIndex = 0; attribIndex < _vertexAttribs.Length; attribIndex++)
+ {
+ VertexAttribDescriptor attrib = _vertexAttribs[attribIndex];
+
+ if ((uint)attrib.BufferIndex >= _vertexBuffers.Length)
+ {
+ GL.DisableVertexAttribArray(attribIndex);
+
+ continue;
+ }
+
+ if (_vertexBuffers[attrib.BufferIndex].Buffer.Buffer == null)
+ {
+ GL.DisableVertexAttribArray(attribIndex);
+
+ continue;
+ }
+
+ if (_needsAttribsUpdate)
+ {
+ GL.EnableVertexAttribArray(attribIndex);
+ }
+ }
+
+ _needsAttribsUpdate = false;
+ }
+
+ public void Dispose()
+ {
+ GL.DeleteVertexArray(Handle);
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/VertexBuffer.cs b/Ryujinx.Graphics.OpenGL/VertexBuffer.cs
new file mode 100644
index 000000000..19a58053c
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/VertexBuffer.cs
@@ -0,0 +1,19 @@
+using Ryujinx.Graphics.GAL;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ struct VertexBuffer
+ {
+ public BufferRange Range { get; }
+
+ public int Divisor { get; }
+ public int Stride { get; }
+
+ public VertexBuffer(BufferRange range, int divisor, int stride)
+ {
+ Range = range;
+ Divisor = divisor;
+ Stride = stride;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics.OpenGL/Window.cs b/Ryujinx.Graphics.OpenGL/Window.cs
new file mode 100644
index 000000000..a05eb1c0b
--- /dev/null
+++ b/Ryujinx.Graphics.OpenGL/Window.cs
@@ -0,0 +1,248 @@
+using OpenTK.Graphics.OpenGL;
+using Ryujinx.Graphics.GAL;
+using System;
+using System.Collections.Generic;
+
+namespace Ryujinx.Graphics.OpenGL
+{
+ class Window : IWindow
+ {
+ private const int NativeWidth = 1280;
+ private const int NativeHeight = 720;
+
+ private int _width = 1280;
+ private int _height = 720;
+
+ private int _blitFramebufferHandle;
+ private int _copyFramebufferHandle;
+
+ private int _screenTextureHandle;
+
+ private TextureReleaseCallback _release;
+
+ private struct PresentationTexture
+ {
+ public TextureView Texture { get; }
+
+ public ImageCrop Crop { get; }
+
+ public object Context { get; }
+
+ public PresentationTexture(TextureView texture, ImageCrop crop, object context)
+ {
+ Texture = texture;
+ Crop = crop;
+ Context = context;
+ }
+ }
+
+ private Queue _textures;
+
+ public Window()
+ {
+ _textures = new Queue();
+ }
+
+ public void Present()
+ {
+ GL.Disable(EnableCap.FramebufferSrgb);
+
+ CopyTextureFromQueue();
+
+ int oldReadFramebufferHandle = GL.GetInteger(GetPName.ReadFramebufferBinding);
+ int oldDrawFramebufferHandle = GL.GetInteger(GetPName.DrawFramebufferBinding);
+
+ GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, 0);
+ GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, GetCopyFramebufferHandleLazy());
+
+ GL.ReadBuffer(ReadBufferMode.ColorAttachment0);
+
+ GL.Clear(ClearBufferMask.ColorBufferBit);
+
+ GL.BlitFramebuffer(
+ 0,
+ 0,
+ 1280,
+ 720,
+ 0,
+ 0,
+ 1280,
+ 720,
+ ClearBufferMask.ColorBufferBit,
+ BlitFramebufferFilter.Linear);
+
+ GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, oldReadFramebufferHandle);
+ GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, oldDrawFramebufferHandle);
+
+ GL.Enable(EnableCap.FramebufferSrgb);
+ }
+
+ private void CopyTextureFromQueue()
+ {
+ if (!_textures.TryDequeue(out PresentationTexture presentationTexture))
+ {
+ return;
+ }
+
+ TextureView texture = presentationTexture.Texture;
+ ImageCrop crop = presentationTexture.Crop;
+ object context = presentationTexture.Context;
+
+ int oldReadFramebufferHandle = GL.GetInteger(GetPName.ReadFramebufferBinding);
+ int oldDrawFramebufferHandle = GL.GetInteger(GetPName.DrawFramebufferBinding);
+
+ GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, GetCopyFramebufferHandleLazy());
+ GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, GetBlitFramebufferHandleLazy());
+
+ GL.FramebufferTexture(
+ FramebufferTarget.ReadFramebuffer,
+ FramebufferAttachment.ColorAttachment0,
+ texture.Handle,
+ 0);
+
+ GL.ReadBuffer(ReadBufferMode.ColorAttachment0);
+
+ GL.Clear(ClearBufferMask.ColorBufferBit);
+
+ int srcX0, srcX1, srcY0, srcY1;
+
+ if (crop.Left == 0 && crop.Right == 0)
+ {
+ srcX0 = 0;
+ srcX1 = texture.Width;
+ }
+ else
+ {
+ srcX0 = crop.Left;
+ srcX1 = crop.Right;
+ }
+
+ if (crop.Top == 0 && crop.Bottom == 0)
+ {
+ srcY0 = 0;
+ srcY1 = texture.Height;
+ }
+ else
+ {
+ srcY0 = crop.Top;
+ srcY1 = crop.Bottom;
+ }
+
+ float ratioX = MathF.Min(1f, (_height * (float)NativeWidth) / ((float)NativeHeight * _width));
+ float ratioY = MathF.Min(1f, (_width * (float)NativeHeight) / ((float)NativeWidth * _height));
+
+ int dstWidth = (int)(_width * ratioX);
+ int dstHeight = (int)(_height * ratioY);
+
+ int dstPaddingX = (_width - dstWidth) / 2;
+ int dstPaddingY = (_height - dstHeight) / 2;
+
+ int dstX0 = crop.FlipX ? _width - dstPaddingX : dstPaddingX;
+ int dstX1 = crop.FlipX ? dstPaddingX : _width - dstPaddingX;
+
+ int dstY0 = crop.FlipY ? dstPaddingY : _height - dstPaddingY;
+ int dstY1 = crop.FlipY ? _height - dstPaddingY : dstPaddingY;
+
+ GL.BlitFramebuffer(
+ srcX0,
+ srcY0,
+ srcX1,
+ srcY1,
+ dstX0,
+ dstY0,
+ dstX1,
+ dstY1,
+ ClearBufferMask.ColorBufferBit,
+ BlitFramebufferFilter.Linear);
+
+ GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, oldReadFramebufferHandle);
+ GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, oldDrawFramebufferHandle);
+
+ texture.Release();
+
+ Release(context);
+ }
+
+ public void QueueTexture(ITexture texture, ImageCrop crop, object context)
+ {
+ if (texture == null)
+ {
+ Release(context);
+
+ return;
+ }
+
+ TextureView textureView = (TextureView)texture;
+
+ textureView.Acquire();
+
+ _textures.Enqueue(new PresentationTexture(textureView, crop, context));
+ }
+
+ public void RegisterTextureReleaseCallback(TextureReleaseCallback callback)
+ {
+ _release = callback;
+ }
+
+ private void Release(object context)
+ {
+ if (_release != null)
+ {
+ _release(context);
+ }
+ }
+
+ private int GetBlitFramebufferHandleLazy()
+ {
+ int handle = _blitFramebufferHandle;
+
+ if (handle == 0)
+ {
+ handle = GL.GenFramebuffer();
+
+ _blitFramebufferHandle = handle;
+ }
+
+ return handle;
+ }
+
+ private int GetCopyFramebufferHandleLazy()
+ {
+ int handle = _copyFramebufferHandle;
+
+ if (handle == 0)
+ {
+ int textureHandle = GL.GenTexture();
+
+ GL.BindTexture(TextureTarget.Texture2D, textureHandle);
+
+ GL.TexImage2D(
+ TextureTarget.Texture2D,
+ 0,
+ PixelInternalFormat.Rgba8,
+ 1280,
+ 720,
+ 0,
+ PixelFormat.Rgba,
+ PixelType.UnsignedByte,
+ IntPtr.Zero);
+
+ handle = GL.GenFramebuffer();
+
+ GL.BindFramebuffer(FramebufferTarget.Framebuffer, handle);
+
+ GL.FramebufferTexture(
+ FramebufferTarget.Framebuffer,
+ FramebufferAttachment.ColorAttachment0,
+ textureHandle,
+ 0);
+
+ _screenTextureHandle = textureHandle;
+
+ _copyFramebufferHandle = handle;
+ }
+
+ return handle;
+ }
+ }
+}
diff --git a/Ryujinx.Graphics/Shader/CBufferDescriptor.cs b/Ryujinx.Graphics.Shader/BufferDescriptor.cs
similarity index 67%
rename from Ryujinx.Graphics/Shader/CBufferDescriptor.cs
rename to Ryujinx.Graphics.Shader/BufferDescriptor.cs
index f99665e16..4cc999989 100644
--- a/Ryujinx.Graphics/Shader/CBufferDescriptor.cs
+++ b/Ryujinx.Graphics.Shader/BufferDescriptor.cs
@@ -1,12 +1,12 @@
namespace Ryujinx.Graphics.Shader
{
- public struct CBufferDescriptor
+ public struct BufferDescriptor
{
public string Name { get; }
public int Slot { get; }
- public CBufferDescriptor(string name, int slot)
+ public BufferDescriptor(string name, int slot)
{
Name = name;
Slot = slot;
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/CodeGenContext.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/CodeGenContext.cs
similarity index 87%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/CodeGenContext.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/CodeGenContext.cs
index dcbdc3097..322bfbf56 100644
--- a/Ryujinx.Graphics/Shader/CodeGen/Glsl/CodeGenContext.cs
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/CodeGenContext.cs
@@ -9,7 +9,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
public ShaderConfig Config { get; }
- public List CBufferDescriptors { get; }
+ public List CBufferDescriptors { get; }
+ public List SBufferDescriptors { get; }
public List TextureDescriptors { get; }
public OperandManager OperandManager { get; }
@@ -24,7 +25,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
Config = config;
- CBufferDescriptors = new List();
+ CBufferDescriptors = new List();
+ SBufferDescriptors = new List();
TextureDescriptors = new List();
OperandManager = new OperandManager();
diff --git a/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs
new file mode 100644
index 000000000..3644b21a6
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Declarations.cs
@@ -0,0 +1,319 @@
+using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using Ryujinx.Graphics.Shader.StructuredIr;
+using Ryujinx.Graphics.Shader.Translation;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
+{
+ static class Declarations
+ {
+ // At least 16 attributes are guaranteed by the spec.
+ public const int MaxAttributes = 16;
+
+ public static void Declare(CodeGenContext context, StructuredProgramInfo info)
+ {
+ context.AppendLine("#version 420 core");
+ context.AppendLine("#extension GL_ARB_shader_storage_buffer_object : enable");
+
+ if (context.Config.Stage == ShaderStage.Compute)
+ {
+ context.AppendLine("#extension GL_ARB_compute_shader : enable");
+ }
+
+ context.AppendLine();
+
+ context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
+ context.AppendLine();
+
+ if (context.Config.Stage == ShaderStage.Geometry)
+ {
+ string inPrimitive = "points";
+
+ if ((context.Config.Flags & TranslationFlags.Unspecialized) != 0)
+ {
+ inPrimitive = DefineNames.InputTopologyName;
+ }
+
+ context.AppendLine($"layout ({inPrimitive}) in;");
+
+ string outPrimitive = "triangle_strip";
+
+ switch (context.Config.OutputTopology)
+ {
+ case OutputTopology.LineStrip: outPrimitive = "line_strip"; break;
+ case OutputTopology.PointList: outPrimitive = "points"; break;
+ case OutputTopology.TriangleStrip: outPrimitive = "triangle_strip"; break;
+ }
+
+ int maxOutputVertices = context.Config.MaxOutputVertices;
+
+ context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
+ context.AppendLine();
+ }
+
+ context.AppendLine("layout (std140) uniform Extra");
+
+ context.EnterScope();
+
+ context.AppendLine("vec2 flip;");
+ context.AppendLine("int instance;");
+
+ context.LeaveScope(";");
+
+ context.AppendLine();
+
+ context.AppendLine($"precise float {DefaultNames.LocalMemoryName}[0x100];");
+ context.AppendLine();
+
+ if (info.CBuffers.Count != 0)
+ {
+ DeclareUniforms(context, info);
+
+ context.AppendLine();
+ }
+
+ if (info.SBuffers.Count != 0)
+ {
+ DeclareStorage(context, info);
+
+ context.AppendLine();
+ }
+
+ if (info.Samplers.Count != 0)
+ {
+ DeclareSamplers(context, info);
+
+ context.AppendLine();
+ }
+
+ if (context.Config.Stage != ShaderStage.Compute)
+ {
+ if (info.IAttributes.Count != 0)
+ {
+ DeclareInputAttributes(context, info);
+
+ context.AppendLine();
+ }
+
+ if (info.OAttributes.Count != 0 || context.Config.Stage != ShaderStage.Fragment)
+ {
+ DeclareOutputAttributes(context, info);
+
+ context.AppendLine();
+ }
+ }
+ else
+ {
+ string localSizeX = "1";
+ string localSizeY = "1";
+ string localSizeZ = "1";
+
+ if ((context.Config.Flags & TranslationFlags.Unspecialized) != 0)
+ {
+ localSizeX = DefineNames.LocalSizeX;
+ localSizeY = DefineNames.LocalSizeY;
+ localSizeZ = DefineNames.LocalSizeZ;
+ }
+
+ context.AppendLine(
+ $"layout (" +
+ $"local_size_x = {localSizeX}, " +
+ $"local_size_y = {localSizeY}, " +
+ $"local_size_z = {localSizeZ}) in;");
+ context.AppendLine();
+ }
+ }
+
+ public static void DeclareLocals(CodeGenContext context, StructuredProgramInfo info)
+ {
+ foreach (AstOperand decl in info.Locals)
+ {
+ string name = context.OperandManager.DeclareLocal(decl);
+
+ context.AppendLine(GetVarTypeName(decl.VarType) + " " + name + ";");
+ }
+ }
+
+ private static string GetVarTypeName(VariableType type)
+ {
+ switch (type)
+ {
+ case VariableType.Bool: return "bool";
+ case VariableType.F32: return "precise float";
+ case VariableType.S32: return "int";
+ case VariableType.U32: return "uint";
+ }
+
+ throw new ArgumentException($"Invalid variable type \"{type}\".");
+ }
+
+ private static void DeclareUniforms(CodeGenContext context, StructuredProgramInfo info)
+ {
+ foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
+ {
+ string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
+
+ ubName += "_" + DefaultNames.UniformNamePrefix + cbufSlot;
+
+ context.CBufferDescriptors.Add(new BufferDescriptor(ubName, cbufSlot));
+
+ context.AppendLine("layout (std140) uniform " + ubName);
+
+ context.EnterScope();
+
+ string ubSize = "[" + NumberFormatter.FormatInt(context.Config.MaxCBufferSize / 16) + "]";
+
+ context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, cbufSlot) + ubSize + ";");
+
+ context.LeaveScope(";");
+ }
+ }
+
+ private static void DeclareStorage(CodeGenContext context, StructuredProgramInfo info)
+ {
+ foreach (int sbufSlot in info.SBuffers.OrderBy(x => x))
+ {
+ string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
+
+ sbName += "_" + DefaultNames.StorageNamePrefix + sbufSlot;
+
+ context.SBufferDescriptors.Add(new BufferDescriptor(sbName, sbufSlot));
+
+ context.AppendLine("layout (std430) buffer " + sbName);
+
+ context.EnterScope();
+
+ context.AppendLine("precise float " + OperandManager.GetSbName(context.Config.Stage, sbufSlot) + "[];");
+
+ context.LeaveScope(";");
+ }
+ }
+
+ private static void DeclareSamplers(CodeGenContext context, StructuredProgramInfo info)
+ {
+ Dictionary samplers = new Dictionary();
+
+ foreach (AstTextureOperation texOp in info.Samplers.OrderBy(x => x.Handle))
+ {
+ string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp);
+
+ if (!samplers.TryAdd(samplerName, texOp))
+ {
+ continue;
+ }
+
+ string samplerTypeName = GetSamplerTypeName(texOp.Target);
+
+ context.AppendLine("uniform " + samplerTypeName + " " + samplerName + ";");
+ }
+
+ foreach (KeyValuePair kv in samplers)
+ {
+ string samplerName = kv.Key;
+
+ AstTextureOperation texOp = kv.Value;
+
+ TextureDescriptor desc;
+
+ if ((texOp.Flags & TextureFlags.Bindless) != 0)
+ {
+ AstOperand operand = texOp.GetSource(0) as AstOperand;
+
+ desc = new TextureDescriptor(samplerName, texOp.Target, operand.CbufSlot, operand.CbufOffset);
+ }
+ else
+ {
+ desc = new TextureDescriptor(samplerName, texOp.Target, texOp.Handle);
+ }
+
+ context.TextureDescriptors.Add(desc);
+ }
+ }
+
+ private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
+ {
+ string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
+
+ foreach (int attr in info.IAttributes.OrderBy(x => x))
+ {
+ string iq = info.InterpolationQualifiers[attr].ToGlslQualifier();
+
+ if (iq != string.Empty)
+ {
+ iq += " ";
+ }
+
+ context.AppendLine($"layout (location = {attr}) {iq}in vec4 {DefaultNames.IAttributePrefix}{attr}{suffix};");
+ }
+ }
+
+ private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
+ {
+ if (context.Config.Stage == ShaderStage.Fragment)
+ {
+ DeclareUsedOutputAttributes(context, info);
+ }
+ else
+ {
+ DeclareAllOutputAttributes(context, info);
+ }
+ }
+
+ private static void DeclareUsedOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
+ {
+ foreach (int attr in info.OAttributes.OrderBy(x => x))
+ {
+ context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
+ }
+ }
+
+ private static void DeclareAllOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
+ {
+ for (int attr = 0; attr < MaxAttributes; attr++)
+ {
+ string iq = $"{DefineNames.OutQualifierPrefixName}{attr} ";
+
+ context.AppendLine($"layout (location = {attr}) {iq}out vec4 {DefaultNames.OAttributePrefix}{attr};");
+ }
+
+ foreach (int attr in info.OAttributes.OrderBy(x => x).Where(x => x >= MaxAttributes))
+ {
+ context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
+ }
+ }
+
+ private static string GetSamplerTypeName(TextureTarget type)
+ {
+ string typeName;
+
+ switch (type & TextureTarget.Mask)
+ {
+ case TextureTarget.Texture1D: typeName = "sampler1D"; break;
+ case TextureTarget.Texture2D: typeName = "sampler2D"; break;
+ case TextureTarget.Texture3D: typeName = "sampler3D"; break;
+ case TextureTarget.TextureCube: typeName = "samplerCube"; break;
+
+ default: throw new ArgumentException($"Invalid sampler type \"{type}\".");
+ }
+
+ if ((type & TextureTarget.Multisample) != 0)
+ {
+ typeName += "MS";
+ }
+
+ if ((type & TextureTarget.Array) != 0)
+ {
+ typeName += "Array";
+ }
+
+ if ((type & TextureTarget.Shadow) != 0)
+ {
+ typeName += "Shadow";
+ }
+
+ return typeName;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/DefaultNames.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/DefaultNames.cs
similarity index 73%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/DefaultNames.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/DefaultNames.cs
index 1d3939fb7..67de3b438 100644
--- a/Ryujinx.Graphics/Shader/CodeGen/Glsl/DefaultNames.cs
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/DefaultNames.cs
@@ -9,9 +9,14 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
public const string IAttributePrefix = "in_attr";
public const string OAttributePrefix = "out_attr";
+ public const string StorageNamePrefix = "s";
+ public const string StorageNameSuffix = "data";
+
public const string UniformNamePrefix = "c";
public const string UniformNameSuffix = "data";
+ public const string LocalMemoryName = "local_mem";
+
public const string UndefinedName = "undef";
}
}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/GlslGenerator.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/GlslGenerator.cs
similarity index 82%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/GlslGenerator.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/GlslGenerator.cs
index 4edbda8b9..65246d975 100644
--- a/Ryujinx.Graphics/Shader/CodeGen/Glsl/GlslGenerator.cs
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/GlslGenerator.cs
@@ -1,4 +1,3 @@
-using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
@@ -20,6 +19,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
return new GlslProgram(
context.CBufferDescriptors.ToArray(),
+ context.SBufferDescriptors.ToArray(),
context.TextureDescriptors.ToArray(),
context.GetCode());
}
@@ -32,6 +32,23 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
Declarations.DeclareLocals(context, info);
+ // Ensure that unused attributes are set, otherwise the downstream
+ // compiler may eliminate them.
+ // (Not needed for fragment shader as it is the last stage).
+ if (context.Config.Stage != ShaderStage.Compute &&
+ context.Config.Stage != ShaderStage.Fragment)
+ {
+ for (int attr = 0; attr < Declarations.MaxAttributes; attr++)
+ {
+ if (info.OAttributes.Contains(attr))
+ {
+ continue;
+ }
+
+ context.AppendLine($"{DefaultNames.OAttributePrefix}{attr} = vec4(0);");
+ }
+ }
+
PrintBlock(context, info.MainBlock);
context.LeaveScope();
@@ -81,11 +98,6 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
if (node is AstOperation operation)
{
- if (operation.Inst == Instruction.Return)
- {
- PrepareForReturn(context);
- }
-
context.AppendLine(InstGen.GetExpression(context, operation) + ";");
}
else if (node is AstAssignment assignment)
@@ -97,7 +109,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
if (assignment.Destination is AstOperand operand && operand.Type == OperandType.Attribute)
{
- dest = OperandManager.GetOutAttributeName(operand, context.Config.Type);
+ dest = OperandManager.GetOutAttributeName(operand, context.Config.Stage);
}
else
{
@@ -108,6 +120,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
context.AppendLine(dest + " = " + src + ";");
}
+ else if (node is AstComment comment)
+ {
+ context.AppendLine("// " + comment.Comment);
+ }
else
{
throw new InvalidOperationException($"Found unexpected node type \"{node?.GetType().Name ?? "null"}\".");
@@ -121,13 +137,5 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
return ReinterpretCast(context, cond, srcType, VariableType.Bool);
}
-
- private static void PrepareForReturn(CodeGenContext context)
- {
- if (context.Config.Type == GalShaderType.Vertex)
- {
- context.AppendLine("gl_Position.xy *= flip;");
- }
- }
}
}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/CodeGen/Glsl/GlslProgram.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/GlslProgram.cs
new file mode 100644
index 000000000..7807cb495
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/GlslProgram.cs
@@ -0,0 +1,23 @@
+namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
+{
+ class GlslProgram
+ {
+ public BufferDescriptor[] CBufferDescriptors { get; }
+ public BufferDescriptor[] SBufferDescriptors { get; }
+ public TextureDescriptor[] TextureDescriptors { get; }
+
+ public string Code { get; }
+
+ public GlslProgram(
+ BufferDescriptor[] cBufferDescriptors,
+ BufferDescriptor[] sBufferDescriptors,
+ TextureDescriptor[] textureDescriptors,
+ string code)
+ {
+ CBufferDescriptors = cBufferDescriptors;
+ SBufferDescriptors = sBufferDescriptors;
+ TextureDescriptors = textureDescriptors;
+ Code = code;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGen.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGen.cs
similarity index 83%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGen.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGen.cs
index b0b2ec1a9..350de3480 100644
--- a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGen.cs
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGen.cs
@@ -17,7 +17,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
}
else if (node is AstOperand operand)
{
- return context.OperandManager.GetExpression(operand, context.Config.Type);
+ return context.OperandManager.GetExpression(operand, context.Config.Stage);
}
throw new ArgumentException($"Invalid node type \"{node?.GetType().Name ?? "null"}\".");
@@ -87,12 +87,27 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
switch (inst)
{
+ case Instruction.LoadAttribute:
+ return InstGenMemory.LoadAttribute(context, operation);
+
case Instruction.LoadConstant:
return InstGenMemory.LoadConstant(context, operation);
+ case Instruction.LoadLocal:
+ return InstGenMemory.LoadLocal(context, operation);
+
+ case Instruction.LoadStorage:
+ return InstGenMemory.LoadStorage(context, operation);
+
case Instruction.PackHalf2x16:
return InstGenPacking.PackHalf2x16(context, operation);
+ case Instruction.StoreLocal:
+ return InstGenMemory.StoreLocal(context, operation);
+
+ case Instruction.StoreStorage:
+ return InstGenMemory.StoreStorage(context, operation);
+
case Instruction.TextureSample:
return InstGenMemory.TextureSample(context, operation);
@@ -104,6 +119,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
}
}
+ return "0";
+
throw new InvalidOperationException($"Unexpected instruction type \"{info.Type}\".");
}
}
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenHelper.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenHelper.cs
similarity index 96%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenHelper.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenHelper.cs
index 9855cd913..6989e9974 100644
--- a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenHelper.cs
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenHelper.cs
@@ -49,7 +49,10 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
Add(Instruction.Floor, InstType.CallUnary, "floor");
Add(Instruction.FusedMultiplyAdd, InstType.CallTernary, "fma");
Add(Instruction.IsNan, InstType.CallUnary, "isnan");
+ Add(Instruction.LoadAttribute, InstType.Special);
Add(Instruction.LoadConstant, InstType.Special);
+ Add(Instruction.LoadLocal, InstType.Special);
+ Add(Instruction.LoadStorage, InstType.Special);
Add(Instruction.LogarithmB2, InstType.CallUnary, "log2");
Add(Instruction.LogicalAnd, InstType.OpBinaryCom, "&&", 9);
Add(Instruction.LogicalExclusiveOr, InstType.OpBinaryCom, "^^", 10);
@@ -71,6 +74,8 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
Add(Instruction.Return, InstType.OpNullary, "return");
Add(Instruction.Sine, InstType.CallUnary, "sin");
Add(Instruction.SquareRoot, InstType.CallUnary, "sqrt");
+ Add(Instruction.StoreLocal, InstType.Special);
+ Add(Instruction.StoreStorage, InstType.Special);
Add(Instruction.Subtract, InstType.OpBinary, "-", 2);
Add(Instruction.TextureSample, InstType.Special);
Add(Instruction.TextureSize, InstType.Special);
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs
similarity index 61%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs
index 8b5257fcb..5c9ec830c 100644
--- a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenMemory.cs
@@ -1,5 +1,6 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
+using System;
using static Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions.InstGenHelper;
using static Ryujinx.Graphics.Shader.StructuredIr.InstructionInfo;
@@ -8,31 +9,106 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
static class InstGenMemory
{
+ public static string LoadAttribute(CodeGenContext context, AstOperation operation)
+ {
+ IAstNode src1 = operation.GetSource(0);
+ IAstNode src2 = operation.GetSource(1);
+
+ if (!(src1 is AstOperand attr) || attr.Type != OperandType.Attribute)
+ {
+ throw new InvalidOperationException("First source of LoadAttribute must be a attribute.");
+ }
+
+ string indexExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
+
+ return OperandManager.GetAttributeName(attr, context.Config.Stage, isOutAttr: false, indexExpr);
+ }
+
public static string LoadConstant(CodeGenContext context, AstOperation operation)
{
- IAstNode src1 = operation.GetSource(1);
+ IAstNode src1 = operation.GetSource(0);
+ IAstNode src2 = operation.GetSource(1);
- string offsetExpr = GetSoureExpr(context, src1, GetSrcVarType(operation.Inst, 1));
+ string offsetExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
- offsetExpr = Enclose(offsetExpr, src1, Instruction.ShiftRightS32, isLhs: true);
+ offsetExpr = Enclose(offsetExpr, src2, Instruction.ShiftRightS32, isLhs: true);
- return OperandManager.GetConstantBufferName(operation.GetSource(0), offsetExpr, context.Config.Type);
+ return OperandManager.GetConstantBufferName(src1, offsetExpr, context.Config.Stage);
+ }
+
+ public static string LoadLocal(CodeGenContext context, AstOperation operation)
+ {
+ IAstNode src1 = operation.GetSource(0);
+
+ string offsetExpr = GetSoureExpr(context, src1, GetSrcVarType(operation.Inst, 0));
+
+ return $"{DefaultNames.LocalMemoryName}[{offsetExpr}]";
+ }
+
+ public static string LoadStorage(CodeGenContext context, AstOperation operation)
+ {
+ IAstNode src1 = operation.GetSource(0);
+ IAstNode src2 = operation.GetSource(1);
+
+ string offsetExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
+
+ return OperandManager.GetStorageBufferName(src1, offsetExpr, context.Config.Stage);
+ }
+
+ public static string StoreLocal(CodeGenContext context, AstOperation operation)
+ {
+ IAstNode src1 = operation.GetSource(0);
+ IAstNode src2 = operation.GetSource(1);
+
+ string offsetExpr = GetSoureExpr(context, src1, GetSrcVarType(operation.Inst, 0));
+
+ VariableType srcType = OperandManager.GetNodeDestType(src2);
+
+ string src = TypeConversion.ReinterpretCast(context, src2, srcType, VariableType.F32);
+
+ return $"{DefaultNames.LocalMemoryName}[{offsetExpr}] = {src}";
+ }
+
+ public static string StoreStorage(CodeGenContext context, AstOperation operation)
+ {
+ IAstNode src1 = operation.GetSource(0);
+ IAstNode src2 = operation.GetSource(1);
+ IAstNode src3 = operation.GetSource(2);
+
+ string offsetExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
+
+ VariableType srcType = OperandManager.GetNodeDestType(src3);
+
+ string src = TypeConversion.ReinterpretCast(context, src3, srcType, VariableType.F32);
+
+ string sbName = OperandManager.GetStorageBufferName(src1, offsetExpr, context.Config.Stage);
+
+ return $"{sbName} = {src}";
}
public static string TextureSample(CodeGenContext context, AstOperation operation)
{
AstTextureOperation texOp = (AstTextureOperation)operation;
- bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
- bool isGather = (texOp.Flags & TextureFlags.Gather) != 0;
- bool intCoords = (texOp.Flags & TextureFlags.IntCoords) != 0;
- bool hasLodBias = (texOp.Flags & TextureFlags.LodBias) != 0;
- bool hasLodLevel = (texOp.Flags & TextureFlags.LodLevel) != 0;
- bool hasOffset = (texOp.Flags & TextureFlags.Offset) != 0;
- bool hasOffsets = (texOp.Flags & TextureFlags.Offsets) != 0;
- bool isArray = (texOp.Type & TextureType.Array) != 0;
- bool isMultisample = (texOp.Type & TextureType.Multisample) != 0;
- bool isShadow = (texOp.Type & TextureType.Shadow) != 0;
+ bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
+ bool isGather = (texOp.Flags & TextureFlags.Gather) != 0;
+ bool intCoords = (texOp.Flags & TextureFlags.IntCoords) != 0;
+ bool hasLodBias = (texOp.Flags & TextureFlags.LodBias) != 0;
+ bool hasLodLevel = (texOp.Flags & TextureFlags.LodLevel) != 0;
+ bool hasOffset = (texOp.Flags & TextureFlags.Offset) != 0;
+ bool hasOffsets = (texOp.Flags & TextureFlags.Offsets) != 0;
+
+ bool isArray = (texOp.Target & TextureTarget.Array) != 0;
+ bool isMultisample = (texOp.Target & TextureTarget.Multisample) != 0;
+ bool isShadow = (texOp.Target & TextureTarget.Shadow) != 0;
+
+ // This combination is valid, but not available on GLSL.
+ // For now, ignore the LOD level and do a normal sample.
+ // TODO: How to implement it properly?
+ if (hasLodLevel && isArray && isShadow)
+ {
+ hasLodLevel = false;
+ }
string texCall = intCoords ? "texelFetch" : "texture";
@@ -54,11 +130,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
texCall += "Offsets";
}
- string samplerName = OperandManager.GetSamplerName(context.Config.Type, texOp);
+ string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp);
texCall += "(" + samplerName;
- int coordsCount = texOp.Type.GetCoordsCount();
+ int coordsCount = texOp.Target.GetDimensions();
int pCount = coordsCount;
@@ -71,7 +147,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
// The sampler 1D shadow overload expects a
// dummy value on the middle of the vector, who knows why...
- bool hasDummy1DShadowElem = texOp.Type == (TextureType.Texture1D | TextureType.Shadow);
+ bool hasDummy1DShadowElem = texOp.Target == (TextureTarget.Texture1D | TextureTarget.Shadow);
if (hasDummy1DShadowElem)
{
@@ -217,7 +293,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
- string samplerName = OperandManager.GetSamplerName(context.Config.Type, texOp);
+ string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp);
IAstNode src0 = operation.GetSource(isBindless ? 1 : 0);
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenPacking.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenPacking.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstGenPacking.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstGenPacking.cs
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstInfo.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstInfo.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstInfo.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstInfo.cs
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstType.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstType.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/Instructions/InstType.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/Instructions/InstType.cs
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/NumberFormatter.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/NumberFormatter.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/NumberFormatter.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/NumberFormatter.cs
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/OperandManager.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/OperandManager.cs
similarity index 66%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/OperandManager.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/OperandManager.cs
index 19f7185e9..880959208 100644
--- a/Ryujinx.Graphics/Shader/CodeGen/Glsl/OperandManager.cs
+++ b/Ryujinx.Graphics.Shader/CodeGen/Glsl/OperandManager.cs
@@ -1,6 +1,6 @@
-using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
+using Ryujinx.Graphics.Shader.Translation;
using System;
using System.Collections.Generic;
@@ -10,7 +10,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
class OperandManager
{
- private static string[] _stagePrefixes = new string[] { "vp", "tcp", "tep", "gp", "fp" };
+ private static string[] _stagePrefixes = new string[] { "cp", "vp", "tcp", "tep", "gp", "fp" };
private struct BuiltInAttribute
{
@@ -46,10 +46,18 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{ AttributeConsts.PointCoordY, new BuiltInAttribute("gl_PointCoord.y", VariableType.F32) },
{ AttributeConsts.TessCoordX, new BuiltInAttribute("gl_TessCoord.x", VariableType.F32) },
{ AttributeConsts.TessCoordY, new BuiltInAttribute("gl_TessCoord.y", VariableType.F32) },
- { AttributeConsts.InstanceId, new BuiltInAttribute("instance", VariableType.S32) },
+ { AttributeConsts.InstanceId, new BuiltInAttribute("gl_InstanceID", VariableType.S32) },
{ AttributeConsts.VertexId, new BuiltInAttribute("gl_VertexID", VariableType.S32) },
{ AttributeConsts.FrontFacing, new BuiltInAttribute("gl_FrontFacing", VariableType.Bool) },
- { AttributeConsts.FragmentOutputDepth, new BuiltInAttribute("gl_FragDepth", VariableType.F32) }
+
+ // Special.
+ { AttributeConsts.FragmentOutputDepth, new BuiltInAttribute("gl_FragDepth", VariableType.F32) },
+ { AttributeConsts.ThreadIdX, new BuiltInAttribute("gl_LocalInvocationID.x", VariableType.U32) },
+ { AttributeConsts.ThreadIdY, new BuiltInAttribute("gl_LocalInvocationID.y", VariableType.U32) },
+ { AttributeConsts.ThreadIdZ, new BuiltInAttribute("gl_LocalInvocationID.z", VariableType.U32) },
+ { AttributeConsts.CtaIdX, new BuiltInAttribute("gl_WorkGroupID.x", VariableType.U32) },
+ { AttributeConsts.CtaIdY, new BuiltInAttribute("gl_WorkGroupID.y", VariableType.U32) },
+ { AttributeConsts.CtaIdZ, new BuiltInAttribute("gl_WorkGroupID.z", VariableType.U32) },
};
private Dictionary _locals;
@@ -68,18 +76,18 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
return name;
}
- public string GetExpression(AstOperand operand, GalShaderType shaderType)
+ public string GetExpression(AstOperand operand, ShaderStage stage)
{
switch (operand.Type)
{
case OperandType.Attribute:
- return GetAttributeName(operand, shaderType);
+ return GetAttributeName(operand, stage);
case OperandType.Constant:
return NumberFormatter.FormatInt(operand.Value);
case OperandType.ConstantBuffer:
- return GetConstantBufferName(operand, shaderType);
+ return GetConstantBufferName(operand, stage);
case OperandType.LocalVariable:
return _locals[operand];
@@ -91,36 +99,48 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
throw new ArgumentException($"Invalid operand type \"{operand.Type}\".");
}
- public static string GetConstantBufferName(AstOperand cbuf, GalShaderType shaderType)
+ public static string GetConstantBufferName(AstOperand cbuf, ShaderStage stage)
{
- string ubName = GetUbName(shaderType, cbuf.CbufSlot);
+ string ubName = GetUbName(stage, cbuf.CbufSlot);
ubName += "[" + (cbuf.CbufOffset >> 2) + "]";
return ubName + "." + GetSwizzleMask(cbuf.CbufOffset & 3);
}
- public static string GetConstantBufferName(IAstNode slot, string offsetExpr, GalShaderType shaderType)
+ public static string GetStorageBufferName(IAstNode slot, string offsetExpr, ShaderStage stage)
{
// Non-constant slots are not supported.
// It is expected that upstream stages are never going to generate non-constant
// slot access.
AstOperand operand = (AstOperand)slot;
- string ubName = GetUbName(shaderType, operand.Value);
+ string sbName = GetSbName(stage, operand.Value);
- string index0 = "[" + offsetExpr + " >> 4]";
- string index1 = "[" + offsetExpr + " >> 2 & 3]";
+ return $"{sbName}[{offsetExpr}]";
+ }
+
+ public static string GetConstantBufferName(IAstNode slot, string offsetExpr, ShaderStage stage)
+ {
+ // Non-constant slots are not supported.
+ // It is expected that upstream stages are never going to generate non-constant
+ // slot access.
+ AstOperand operand = (AstOperand)slot;
+
+ string ubName = GetUbName(stage, operand.Value);
+
+ string index0 = "[" + offsetExpr + " >> 2]";
+ string index1 = "[" + offsetExpr + " & 3]";
return ubName + index0 + index1;
}
- public static string GetOutAttributeName(AstOperand attr, GalShaderType shaderType)
+ public static string GetOutAttributeName(AstOperand attr, ShaderStage stage)
{
- return GetAttributeName(attr, shaderType, isOutAttr: true);
+ return GetAttributeName(attr, stage, isOutAttr: true);
}
- private static string GetAttributeName(AstOperand attr, GalShaderType shaderType, bool isOutAttr = false)
+ public static string GetAttributeName(AstOperand attr, ShaderStage stage, bool isOutAttr = false, string indexExpr = "0")
{
int value = attr.Value;
@@ -137,9 +157,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
string name = $"{prefix}{(value >> 4)}";
- if (shaderType == GalShaderType.Geometry && !isOutAttr)
+ if (stage == ShaderStage.Geometry && !isOutAttr)
{
- name += "[0]";
+ name += $"[{indexExpr}]";
}
name += "." + swzMask;
@@ -158,7 +178,7 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
else if (_builtInAttributes.TryGetValue(value & ~3, out BuiltInAttribute builtInAttr))
{
// TODO: There must be a better way to handle this...
- if (shaderType == GalShaderType.Fragment)
+ if (stage == ShaderStage.Fragment)
{
switch (value & ~3)
{
@@ -171,9 +191,9 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
string name = builtInAttr.Name;
- if (shaderType == GalShaderType.Geometry && !isOutAttr)
+ if (stage == ShaderStage.Geometry && !isOutAttr)
{
- name = "gl_in[0]." + name;
+ name = $"gl_in[{indexExpr}].{name}";
}
return name;
@@ -185,16 +205,25 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
return isOutAttr ? "// bad_attr0x" + value.ToString("X") : "0.0";
}
- public static string GetUbName(GalShaderType shaderType, int slot)
+ public static string GetSbName(ShaderStage stage, int slot)
{
- string ubName = GetShaderStagePrefix(shaderType);
+ string sbName = GetShaderStagePrefix(stage);
+
+ sbName += "_" + DefaultNames.StorageNamePrefix + slot;
+
+ return sbName + "_" + DefaultNames.StorageNameSuffix;
+ }
+
+ public static string GetUbName(ShaderStage stage, int slot)
+ {
+ string ubName = GetShaderStagePrefix(stage);
ubName += "_" + DefaultNames.UniformNamePrefix + slot;
return ubName + "_" + DefaultNames.UniformNameSuffix;
}
- public static string GetSamplerName(GalShaderType shaderType, AstTextureOperation texOp)
+ public static string GetSamplerName(ShaderStage stage, AstTextureOperation texOp)
{
string suffix;
@@ -209,12 +238,19 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
suffix = (texOp.Handle - 8).ToString();
}
- return GetShaderStagePrefix(shaderType) + "_" + DefaultNames.SamplerNamePrefix + suffix;
+ return GetShaderStagePrefix(stage) + "_" + DefaultNames.SamplerNamePrefix + suffix;
}
- public static string GetShaderStagePrefix(GalShaderType shaderType)
+ public static string GetShaderStagePrefix(ShaderStage stage)
{
- return _stagePrefixes[(int)shaderType];
+ int index = (int)stage;
+
+ if ((uint)index >= _stagePrefixes.Length)
+ {
+ return "invalid";
+ }
+
+ return _stagePrefixes[index];
}
private static string GetSwizzleMask(int value)
@@ -226,24 +262,37 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
if (node is AstOperation operation)
{
+ // Load attribute basically just returns the attribute value.
+ // Some built-in attributes may have different types, so we need
+ // to return the type based on the attribute that is being read.
+ if (operation.Inst == Instruction.LoadAttribute)
+ {
+ return GetOperandVarType((AstOperand)operation.GetSource(0));
+ }
+
return GetDestVarType(operation.Inst);
}
else if (node is AstOperand operand)
{
- if (operand.Type == OperandType.Attribute)
- {
- if (_builtInAttributes.TryGetValue(operand.Value & ~3, out BuiltInAttribute builtInAttr))
- {
- return builtInAttr.Type;
- }
- }
-
- return OperandInfo.GetVarType(operand);
+ return GetOperandVarType(operand);
}
else
{
throw new ArgumentException($"Invalid node type \"{node?.GetType().Name ?? "null"}\".");
}
}
+
+ private static VariableType GetOperandVarType(AstOperand operand)
+ {
+ if (operand.Type == OperandType.Attribute)
+ {
+ if (_builtInAttributes.TryGetValue(operand.Value & ~3, out BuiltInAttribute builtInAttr))
+ {
+ return builtInAttr.Type;
+ }
+ }
+
+ return OperandInfo.GetVarType(operand);
+ }
}
}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/CodeGen/Glsl/TypeConversion.cs b/Ryujinx.Graphics.Shader/CodeGen/Glsl/TypeConversion.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/CodeGen/Glsl/TypeConversion.cs
rename to Ryujinx.Graphics.Shader/CodeGen/Glsl/TypeConversion.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/BitfieldExtensions.cs b/Ryujinx.Graphics.Shader/Decoders/BitfieldExtensions.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/BitfieldExtensions.cs
rename to Ryujinx.Graphics.Shader/Decoders/BitfieldExtensions.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/Block.cs b/Ryujinx.Graphics.Shader/Decoders/Block.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/Block.cs
rename to Ryujinx.Graphics.Shader/Decoders/Block.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/Condition.cs b/Ryujinx.Graphics.Shader/Decoders/Condition.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/Condition.cs
rename to Ryujinx.Graphics.Shader/Decoders/Condition.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/ConditionalOperation.cs b/Ryujinx.Graphics.Shader/Decoders/ConditionalOperation.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/ConditionalOperation.cs
rename to Ryujinx.Graphics.Shader/Decoders/ConditionalOperation.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/Decoder.cs b/Ryujinx.Graphics.Shader/Decoders/Decoder.cs
similarity index 95%
rename from Ryujinx.Graphics/Shader/Decoders/Decoder.cs
rename to Ryujinx.Graphics.Shader/Decoders/Decoder.cs
index 754e03885..dd5347d9e 100644
--- a/Ryujinx.Graphics/Shader/Decoders/Decoder.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/Decoder.cs
@@ -1,6 +1,6 @@
-using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Shader.Instructions;
using System;
+using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
@@ -12,8 +12,6 @@ namespace Ryujinx.Graphics.Shader.Decoders
{
static class Decoder
{
- private const long HeaderSize = 0x50;
-
private delegate object OpActivator(InstEmitter emitter, ulong address, long opCode);
private static ConcurrentDictionary _opActivators;
@@ -23,7 +21,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
_opActivators = new ConcurrentDictionary();
}
- public static Block[] Decode(IGalMemory memory, ulong address)
+ public static Block[] Decode(Span code, ulong headerSize)
{
List blocks = new List();
@@ -45,7 +43,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
return block;
}
- ulong startAddress = address + HeaderSize;
+ ulong startAddress = headerSize;
GetBlock(startAddress);
@@ -69,7 +67,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
}
// If we have a block after the current one, set the limit address.
- ulong limitAddress = ulong.MaxValue;
+ ulong limitAddress = (ulong)code.Length;
if (nBlkIndex != blocks.Count)
{
@@ -87,7 +85,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
}
}
- FillBlock(memory, currBlock, limitAddress, startAddress);
+ FillBlock(code, currBlock, limitAddress, startAddress);
if (currBlock.OpCodes.Count != 0)
{
@@ -173,7 +171,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
}
private static void FillBlock(
- IGalMemory memory,
+ Span code,
Block block,
ulong limitAddress,
ulong startAddress)
@@ -195,8 +193,8 @@ namespace Ryujinx.Graphics.Shader.Decoders
continue;
}
- uint word0 = (uint)memory.ReadInt32((long)(address + 0));
- uint word1 = (uint)memory.ReadInt32((long)(address + 4));
+ uint word0 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)address));
+ uint word1 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)address + 4));
ulong opAddress = address;
@@ -209,6 +207,9 @@ namespace Ryujinx.Graphics.Shader.Decoders
if (emitter == null)
{
// TODO: Warning, illegal encoding.
+
+ block.OpCodes.Add(new OpCode(null, opAddress, opCode));
+
continue;
}
diff --git a/Ryujinx.Graphics/Shader/Decoders/DecoderHelper.cs b/Ryujinx.Graphics.Shader/Decoders/DecoderHelper.cs
similarity index 91%
rename from Ryujinx.Graphics/Shader/Decoders/DecoderHelper.cs
rename to Ryujinx.Graphics.Shader/Decoders/DecoderHelper.cs
index fd0a45e82..77cd1bf72 100644
--- a/Ryujinx.Graphics/Shader/Decoders/DecoderHelper.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/DecoderHelper.cs
@@ -8,11 +8,11 @@ namespace Ryujinx.Graphics.Shader.Decoders
{
int imm = opCode.Extract(20, 19);
- bool negate = opCode.Extract(56);
+ bool sign = opCode.Extract(56);
- if (negate)
+ if (sign)
{
- imm = -imm;
+ imm = (imm << 13) >> 13;
}
return imm;
diff --git a/Ryujinx.Graphics/Shader/Decoders/FPHalfSwizzle.cs b/Ryujinx.Graphics.Shader/Decoders/FPHalfSwizzle.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/FPHalfSwizzle.cs
rename to Ryujinx.Graphics.Shader/Decoders/FPHalfSwizzle.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/FPType.cs b/Ryujinx.Graphics.Shader/Decoders/FPType.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/FPType.cs
rename to Ryujinx.Graphics.Shader/Decoders/FPType.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/FmulScale.cs b/Ryujinx.Graphics.Shader/Decoders/FmulScale.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/FmulScale.cs
rename to Ryujinx.Graphics.Shader/Decoders/FmulScale.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCode.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCode.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCode.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeAlu.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeAlu.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeAlu.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeAlu.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeFArith.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeFArith.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeFArith.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeFArith.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeHfma.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeHfma.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeHfma.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeHfma.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeImm.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeImm.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeImm.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeImm.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeImmF.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeImmF.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeImmF.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeImmF.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeLop.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeLop.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeLop.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeLop.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeRa.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeRa.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeRa.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeRa.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeRc.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeRc.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeRc.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeRc.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeRd.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeRd.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeRd.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeRd.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeReg.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeReg.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeReg.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeReg.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IOpCodeRegCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/IOpCodeRegCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IOpCodeRegCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/IOpCodeRegCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IntegerCondition.cs b/Ryujinx.Graphics.Shader/Decoders/IntegerCondition.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IntegerCondition.cs
rename to Ryujinx.Graphics.Shader/Decoders/IntegerCondition.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IntegerHalfPart.cs b/Ryujinx.Graphics.Shader/Decoders/IntegerHalfPart.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IntegerHalfPart.cs
rename to Ryujinx.Graphics.Shader/Decoders/IntegerHalfPart.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/IntegerShift.cs b/Ryujinx.Graphics.Shader/Decoders/IntegerShift.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IntegerShift.cs
rename to Ryujinx.Graphics.Shader/Decoders/IntegerShift.cs
diff --git a/Ryujinx.Graphics.Shader/Decoders/IntegerSize.cs b/Ryujinx.Graphics.Shader/Decoders/IntegerSize.cs
new file mode 100644
index 000000000..3ff8e1b26
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Decoders/IntegerSize.cs
@@ -0,0 +1,13 @@
+namespace Ryujinx.Graphics.Shader.Decoders
+{
+ enum IntegerSize
+ {
+ U8 = 0,
+ S8 = 1,
+ U16 = 2,
+ S16 = 3,
+ B32 = 4,
+ B64 = 5,
+ B128 = 6
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/IntegerType.cs b/Ryujinx.Graphics.Shader/Decoders/IntegerType.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/IntegerType.cs
rename to Ryujinx.Graphics.Shader/Decoders/IntegerType.cs
diff --git a/Ryujinx.Graphics.Shader/Decoders/InterpolationMode.cs b/Ryujinx.Graphics.Shader/Decoders/InterpolationMode.cs
new file mode 100644
index 000000000..98ee3b970
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Decoders/InterpolationMode.cs
@@ -0,0 +1,10 @@
+namespace Ryujinx.Graphics.Shader.Decoders
+{
+ enum InterpolationMode
+ {
+ Pass,
+ Default,
+ Constant,
+ Sc
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/LogicalOperation.cs b/Ryujinx.Graphics.Shader/Decoders/LogicalOperation.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/LogicalOperation.cs
rename to Ryujinx.Graphics.Shader/Decoders/LogicalOperation.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/MufuOperation.cs b/Ryujinx.Graphics.Shader/Decoders/MufuOperation.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/MufuOperation.cs
rename to Ryujinx.Graphics.Shader/Decoders/MufuOperation.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCode.cs b/Ryujinx.Graphics.Shader/Decoders/OpCode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCode.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCode.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAlu.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAlu.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAlu.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAlu.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAluCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAluCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAluCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAluCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAluImm.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAluImm.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAluImm.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAluImm.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAluImm2x10.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAluImm2x10.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAluImm2x10.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAluImm2x10.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAluImm32.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAluImm32.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAluImm32.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAluImm32.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAluReg.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAluReg.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAluReg.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAluReg.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAluRegCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAluRegCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAluRegCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAluRegCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeAttribute.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeAttribute.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeAttribute.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeAttribute.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeBranch.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeBranch.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeBranch.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeBranch.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeExit.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeExit.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeExit.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeExit.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeFArith.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeFArith.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeFArith.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeFArith.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeFArithCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeFArithCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeFArithCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeFArithCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeFArithImm.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeFArithImm.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeFArithImm.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeFArithImm.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeFArithImm32.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeFArithImm32.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeFArithImm32.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeFArithImm32.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeFArithReg.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeFArithReg.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeFArithReg.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeFArithReg.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeFArithRegCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeFArithRegCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeFArithRegCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeFArithRegCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeFsetImm.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeFsetImm.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeFsetImm.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeFsetImm.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeHfma.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeHfma.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeHfma.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeHfma.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaImm2x10.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaImm2x10.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaImm2x10.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaImm2x10.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaImm32.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaImm32.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaImm32.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaImm32.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaReg.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaReg.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaReg.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaReg.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaRegCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaRegCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeHfmaRegCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeHfmaRegCbuf.cs
diff --git a/Ryujinx.Graphics.Shader/Decoders/OpCodeHsetImm2x10.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeHsetImm2x10.cs
new file mode 100644
index 000000000..03e1e44ce
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeHsetImm2x10.cs
@@ -0,0 +1,14 @@
+using Ryujinx.Graphics.Shader.Instructions;
+
+namespace Ryujinx.Graphics.Shader.Decoders
+{
+ class OpCodeHsetImm2x10 : OpCodeSet, IOpCodeImm
+ {
+ public int Immediate { get; }
+
+ public OpCodeHsetImm2x10(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
+ {
+ Immediate = DecoderHelper.Decode2xF10Immediate(opCode);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeIpa.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeIpa.cs
similarity index 70%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeIpa.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeIpa.cs
index e21095a32..b475b6a16 100644
--- a/Ryujinx.Graphics/Shader/Decoders/OpCodeIpa.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeIpa.cs
@@ -6,9 +6,15 @@ namespace Ryujinx.Graphics.Shader.Decoders
{
public int AttributeOffset { get; }
+ public InterpolationMode Mode { get; }
+
public OpCodeIpa(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
AttributeOffset = opCode.Extract(28, 10);
+
+ Saturate = opCode.Extract(51);
+
+ Mode = (InterpolationMode)opCode.Extract(54, 2);
}
}
}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeLdc.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeLdc.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeLdc.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeLdc.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeLop.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeLop.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeLop.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeLop.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeLopCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeLopCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeLopCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeLopCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeLopImm.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeLopImm.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeLopImm.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeLopImm.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeLopImm32.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeLopImm32.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeLopImm32.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeLopImm32.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeLopReg.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeLopReg.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeLopReg.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeLopReg.cs
diff --git a/Ryujinx.Graphics.Shader/Decoders/OpCodeMemory.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeMemory.cs
new file mode 100644
index 000000000..bece45622
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeMemory.cs
@@ -0,0 +1,28 @@
+using Ryujinx.Graphics.Shader.Instructions;
+
+namespace Ryujinx.Graphics.Shader.Decoders
+{
+ class OpCodeMemory : OpCode, IOpCodeRd, IOpCodeRa
+ {
+ public Register Rd { get; }
+ public Register Ra { get; }
+
+ public int Offset { get; }
+
+ public bool Extended { get; }
+
+ public IntegerSize Size { get; }
+
+ public OpCodeMemory(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
+ {
+ Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
+ Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
+
+ Offset = opCode.Extract(20, 24);
+
+ Extended = opCode.Extract(45);
+
+ Size = (IntegerSize)opCode.Extract(48, 3);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodePsetp.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodePsetp.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodePsetp.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodePsetp.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeSet.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeSet.cs
similarity index 77%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeSet.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeSet.cs
index cd6773a13..b4ee10fb3 100644
--- a/Ryujinx.Graphics/Shader/Decoders/OpCodeSet.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeSet.cs
@@ -15,8 +15,8 @@ namespace Ryujinx.Graphics.Shader.Decoders
public OpCodeSet(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
- Predicate0 = new Register(opCode.Extract(0, 3), RegisterType.Predicate);
- Predicate3 = new Register(opCode.Extract(3, 3), RegisterType.Predicate);
+ Predicate0 = new Register(opCode.Extract(0, 3), RegisterType.Predicate);
+ Predicate3 = new Register(opCode.Extract(3, 3), RegisterType.Predicate);
LogicalOp = (LogicalOperation)opCode.Extract(45, 2);
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeSetCbuf.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeSetCbuf.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeSetCbuf.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeSetCbuf.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeSetImm.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeSetImm.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeSetImm.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeSetImm.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeSetReg.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeSetReg.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeSetReg.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeSetReg.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeSsy.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeSsy.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeSsy.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeSsy.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeSync.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeSync.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeSync.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeSync.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTable.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTable.cs
similarity index 89%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTable.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTable.cs
index d588ce8ee..3fd1de865 100644
--- a/Ryujinx.Graphics/Shader/Decoders/OpCodeTable.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeTable.cs
@@ -36,6 +36,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
Set("0011100x00000x", InstEmit.Bfe, typeof(OpCodeAluImm));
Set("0101110000000x", InstEmit.Bfe, typeof(OpCodeAluReg));
Set("111000100100xx", InstEmit.Bra, typeof(OpCodeBranch));
+ Set("0101000010100x", InstEmit.Csetp, typeof(OpCodePsetp));
Set("111000110000xx", InstEmit.Exit, typeof(OpCodeExit));
Set("0100110010101x", InstEmit.F2F, typeof(OpCodeFArithCbuf));
Set("0011100x10101x", InstEmit.F2F, typeof(OpCodeFArithImm));
@@ -77,6 +78,9 @@ namespace Ryujinx.Graphics.Shader.Decoders
Set("0111100x0xxxxx", InstEmit.Hmul2, typeof(OpCodeAluImm2x10));
Set("0010101xxxxxxx", InstEmit.Hmul2, typeof(OpCodeAluImm32));
Set("0101110100001x", InstEmit.Hmul2, typeof(OpCodeAluReg));
+ Set("0111111x1xxxxx", InstEmit.Hsetp2, typeof(OpCodeSetCbuf));
+ Set("0111111x0xxxxx", InstEmit.Hsetp2, typeof(OpCodeHsetImm2x10));
+ Set("0101110100100x", InstEmit.Hsetp2, typeof(OpCodeSetReg));
Set("0100110010111x", InstEmit.I2F, typeof(OpCodeAluCbuf));
Set("0011100x10111x", InstEmit.I2F, typeof(OpCodeAluImm));
Set("0101110010111x", InstEmit.I2F, typeof(OpCodeAluReg));
@@ -94,6 +98,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
Set("0011100x00100x", InstEmit.Imnmx, typeof(OpCodeAluImm));
Set("0101110000100x", InstEmit.Imnmx, typeof(OpCodeAluReg));
Set("11100000xxxxxx", InstEmit.Ipa, typeof(OpCodeIpa));
+ Set("1110111111010x", InstEmit.Isberd, typeof(OpCodeAlu));
Set("0100110000011x", InstEmit.Iscadd, typeof(OpCodeAluCbuf));
Set("0011100x00011x", InstEmit.Iscadd, typeof(OpCodeAluImm));
Set("000101xxxxxxxx", InstEmit.Iscadd, typeof(OpCodeAluImm32));
@@ -105,7 +110,9 @@ namespace Ryujinx.Graphics.Shader.Decoders
Set("0011011x0110xx", InstEmit.Isetp, typeof(OpCodeSetImm));
Set("010110110110xx", InstEmit.Isetp, typeof(OpCodeSetReg));
Set("111000110011xx", InstEmit.Kil, typeof(OpCodeExit));
+ Set("1110111101000x", InstEmit.Ld, typeof(OpCodeMemory));
Set("1110111110010x", InstEmit.Ldc, typeof(OpCodeLdc));
+ Set("1110111011010x", InstEmit.Ldg, typeof(OpCodeMemory));
Set("0100110001000x", InstEmit.Lop, typeof(OpCodeLopCbuf));
Set("0011100001000x", InstEmit.Lop, typeof(OpCodeLopImm));
Set("000001xxxxxxxx", InstEmit.Lop, typeof(OpCodeLopImm32));
@@ -123,8 +130,9 @@ namespace Ryujinx.Graphics.Shader.Decoders
Set("0100110010010x", InstEmit.Rro, typeof(OpCodeFArithCbuf));
Set("0011100x10010x", InstEmit.Rro, typeof(OpCodeFArithImm));
Set("0101110010010x", InstEmit.Rro, typeof(OpCodeFArithReg));
+ Set("1111000011001x", InstEmit.S2r, typeof(OpCodeAlu));
Set("0100110010100x", InstEmit.Sel, typeof(OpCodeAluCbuf));
- Set("0011100010100x", InstEmit.Sel, typeof(OpCodeAluImm));
+ Set("0011100x10100x", InstEmit.Sel, typeof(OpCodeAluImm));
Set("0101110010100x", InstEmit.Sel, typeof(OpCodeAluReg));
Set("0100110001001x", InstEmit.Shl, typeof(OpCodeAluCbuf));
Set("0011100x01001x", InstEmit.Shl, typeof(OpCodeAluImm));
@@ -133,17 +141,20 @@ namespace Ryujinx.Graphics.Shader.Decoders
Set("0011100x00101x", InstEmit.Shr, typeof(OpCodeAluImm));
Set("0101110000101x", InstEmit.Shr, typeof(OpCodeAluReg));
Set("111000101001xx", InstEmit.Ssy, typeof(OpCodeSsy));
+ Set("1110111101010x", InstEmit.St, typeof(OpCodeMemory));
+ Set("1110111011011x", InstEmit.Stg, typeof(OpCodeMemory));
Set("1111000011111x", InstEmit.Sync, typeof(OpCodeSync));
Set("110000xxxx111x", InstEmit.Tex, typeof(OpCodeTex));
- Set("1101111010111x", InstEmit.Tex_B, typeof(OpCodeTex));
+ Set("1101111010111x", InstEmit.TexB, typeof(OpCodeTexB));
Set("1101x00xxxxxxx", InstEmit.Texs, typeof(OpCodeTexs));
Set("1101x01xxxxxxx", InstEmit.Texs, typeof(OpCodeTlds));
Set("1101x11100xxxx", InstEmit.Texs, typeof(OpCodeTld4s));
Set("11011100xx111x", InstEmit.Tld, typeof(OpCodeTld));
- Set("11011101xx111x", InstEmit.Tld_B, typeof(OpCodeTld));
+ Set("11011101xx111x", InstEmit.TldB, typeof(OpCodeTld));
Set("110010xxxx111x", InstEmit.Tld4, typeof(OpCodeTld4));
Set("1101111101001x", InstEmit.Txq, typeof(OpCodeTex));
- Set("1101111101010x", InstEmit.Txq_B, typeof(OpCodeTex));
+ Set("1101111101010x", InstEmit.TxqB, typeof(OpCodeTex));
+ Set("01011111xxxxxx", InstEmit.Vmad, typeof(OpCodeVideo));
Set("0100111xxxxxxx", InstEmit.Xmad, typeof(OpCodeAluCbuf));
Set("0011011x00xxxx", InstEmit.Xmad, typeof(OpCodeAluImm));
Set("010100010xxxxx", InstEmit.Xmad, typeof(OpCodeAluRegCbuf));
@@ -189,9 +200,9 @@ namespace Ryujinx.Graphics.Shader.Decoders
{
value &= xMask;
- for (int X = 0; X < xBits; X++)
+ for (int x = 0; x < xBits; x++)
{
- value |= ((index >> X) & 1) << xPos[X];
+ value |= ((index >> x) & 1) << xPos[x];
}
if (_opCodes[value] == null || _opCodes[value].XBits > xBits)
@@ -201,9 +212,9 @@ namespace Ryujinx.Graphics.Shader.Decoders
}
}
- public static (InstEmitter emitter, Type opCodeType) GetEmitter(long OpCode)
+ public static (InstEmitter emitter, Type opCodeType) GetEmitter(long opCode)
{
- TableEntry entry = _opCodes[(ulong)OpCode >> (64 - EncodingBits)];
+ TableEntry entry = _opCodes[(ulong)opCode >> (64 - EncodingBits)];
if (entry != null)
{
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTex.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTex.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTex.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTex.cs
diff --git a/Ryujinx.Graphics.Shader/Decoders/OpCodeTexB.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTexB.cs
new file mode 100644
index 000000000..b18bf3bef
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeTexB.cs
@@ -0,0 +1,20 @@
+using Ryujinx.Graphics.Shader.Instructions;
+
+namespace Ryujinx.Graphics.Shader.Decoders
+{
+ class OpCodeTexB : OpCodeTex
+ {
+ public OpCodeTexB(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
+ {
+ switch (opCode.Extract(37, 3))
+ {
+ case 0: LodMode = TextureLodMode.None; break;
+ case 1: LodMode = TextureLodMode.LodZero; break;
+ case 2: LodMode = TextureLodMode.LodBias; break;
+ case 3: LodMode = TextureLodMode.LodLevel; break;
+ case 6: LodMode = TextureLodMode.LodBiasA; break;
+ case 7: LodMode = TextureLodMode.LodLevelA; break;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTexs.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTexs.cs
similarity index 78%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTexs.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTexs.cs
index 0822c4c07..fb90ccf60 100644
--- a/Ryujinx.Graphics/Shader/Decoders/OpCodeTexs.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeTexs.cs
@@ -4,7 +4,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTexs : OpCodeTextureScalar
{
- public TextureScalarType Type => (TextureScalarType)RawType;
+ public TextureTarget Target => (TextureTarget)RawType;
public OpCodeTexs(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode) { }
}
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTexture.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTexture.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTexture.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTexture.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTextureScalar.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTextureScalar.cs
similarity index 97%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTextureScalar.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTextureScalar.cs
index 470b81f5c..1c175e30b 100644
--- a/Ryujinx.Graphics/Shader/Decoders/OpCodeTextureScalar.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeTextureScalar.cs
@@ -35,7 +35,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
public int Immediate { get; }
- public int ComponentMask { get; }
+ public int ComponentMask { get; protected set; }
protected int RawType;
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTld.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTld.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTld.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTld.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTld4.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTld4.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTld4.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTld4.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTld4s.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTld4s.cs
similarity index 91%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTld4s.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTld4s.cs
index 0d7b84606..7e51a9e50 100644
--- a/Ryujinx.Graphics/Shader/Decoders/OpCodeTld4s.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeTld4s.cs
@@ -15,6 +15,8 @@ namespace Ryujinx.Graphics.Shader.Decoders
HasOffset = opCode.Extract(51);
GatherCompIndex = opCode.Extract(52, 2);
+
+ ComponentMask = Rd1.IsRZ ? 3 : 0xf;
}
}
}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/OpCodeTlds.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeTlds.cs
similarity index 77%
rename from Ryujinx.Graphics/Shader/Decoders/OpCodeTlds.cs
rename to Ryujinx.Graphics.Shader/Decoders/OpCodeTlds.cs
index e117721e9..1e4e943ff 100644
--- a/Ryujinx.Graphics/Shader/Decoders/OpCodeTlds.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeTlds.cs
@@ -4,7 +4,7 @@ namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTlds : OpCodeTextureScalar
{
- public TexelLoadScalarType Type => (TexelLoadScalarType)RawType;
+ public TexelLoadTarget Target => (TexelLoadTarget)RawType;
public OpCodeTlds(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode) { }
}
diff --git a/Ryujinx.Graphics.Shader/Decoders/OpCodeVideo.cs b/Ryujinx.Graphics.Shader/Decoders/OpCodeVideo.cs
new file mode 100644
index 000000000..15dcfa981
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Decoders/OpCodeVideo.cs
@@ -0,0 +1,24 @@
+using Ryujinx.Graphics.Shader.Instructions;
+
+namespace Ryujinx.Graphics.Shader.Decoders
+{
+ class OpCodeVideo : OpCode, IOpCodeRd, IOpCodeRa, IOpCodeRc
+ {
+ public Register Rd { get; }
+ public Register Ra { get; }
+ public Register Rc { get; }
+
+ public bool SetCondCode { get; protected set; }
+ public bool Saturate { get; protected set; }
+
+ public OpCodeVideo(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
+ {
+ Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
+ Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
+ Rc = new Register(opCode.Extract(39, 8), RegisterType.Gpr);
+
+ SetCondCode = opCode.Extract(47);
+ Saturate = opCode.Extract(55);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/Register.cs b/Ryujinx.Graphics.Shader/Decoders/Register.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/Register.cs
rename to Ryujinx.Graphics.Shader/Decoders/Register.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/RegisterConsts.cs b/Ryujinx.Graphics.Shader/Decoders/RegisterConsts.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/RegisterConsts.cs
rename to Ryujinx.Graphics.Shader/Decoders/RegisterConsts.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/RegisterType.cs b/Ryujinx.Graphics.Shader/Decoders/RegisterType.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/RegisterType.cs
rename to Ryujinx.Graphics.Shader/Decoders/RegisterType.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/RoundingMode.cs b/Ryujinx.Graphics.Shader/Decoders/RoundingMode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/RoundingMode.cs
rename to Ryujinx.Graphics.Shader/Decoders/RoundingMode.cs
diff --git a/Ryujinx.Graphics.Shader/Decoders/SystemRegister.cs b/Ryujinx.Graphics.Shader/Decoders/SystemRegister.cs
new file mode 100644
index 000000000..3948c899f
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Decoders/SystemRegister.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Shader.Decoders
+{
+ enum SystemRegister
+ {
+ ThreadIdX = 0x21,
+ ThreadIdY = 0x22,
+ ThreadIdZ = 0x23,
+ CtaIdX = 0x25,
+ CtaIdY = 0x26,
+ CtaIdZ = 0x27
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Decoders/TexelLoadScalarType.cs b/Ryujinx.Graphics.Shader/Decoders/TexelLoadTarget.cs
similarity index 93%
rename from Ryujinx.Graphics/Shader/Decoders/TexelLoadScalarType.cs
rename to Ryujinx.Graphics.Shader/Decoders/TexelLoadTarget.cs
index cef5778a5..478cac44e 100644
--- a/Ryujinx.Graphics/Shader/Decoders/TexelLoadScalarType.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/TexelLoadTarget.cs
@@ -1,6 +1,6 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
- enum TexelLoadScalarType
+ enum TexelLoadTarget
{
Texture1DLodZero = 0x0,
Texture1DLodLevel = 0x1,
diff --git a/Ryujinx.Graphics/Shader/Decoders/TextureDimensions.cs b/Ryujinx.Graphics.Shader/Decoders/TextureDimensions.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/TextureDimensions.cs
rename to Ryujinx.Graphics.Shader/Decoders/TextureDimensions.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/TextureGatherOffset.cs b/Ryujinx.Graphics.Shader/Decoders/TextureGatherOffset.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/TextureGatherOffset.cs
rename to Ryujinx.Graphics.Shader/Decoders/TextureGatherOffset.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/TextureLodMode.cs b/Ryujinx.Graphics.Shader/Decoders/TextureLodMode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/TextureLodMode.cs
rename to Ryujinx.Graphics.Shader/Decoders/TextureLodMode.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/TextureProperty.cs b/Ryujinx.Graphics.Shader/Decoders/TextureProperty.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/TextureProperty.cs
rename to Ryujinx.Graphics.Shader/Decoders/TextureProperty.cs
diff --git a/Ryujinx.Graphics/Shader/Decoders/TextureScalarType.cs b/Ryujinx.Graphics.Shader/Decoders/TextureTarget.cs
similarity index 96%
rename from Ryujinx.Graphics/Shader/Decoders/TextureScalarType.cs
rename to Ryujinx.Graphics.Shader/Decoders/TextureTarget.cs
index 0055174b4..181a0a0d6 100644
--- a/Ryujinx.Graphics/Shader/Decoders/TextureScalarType.cs
+++ b/Ryujinx.Graphics.Shader/Decoders/TextureTarget.cs
@@ -1,6 +1,6 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
- enum TextureScalarType
+ enum TextureTarget
{
Texture1DLodZero = 0x0,
Texture2D = 0x1,
diff --git a/Ryujinx.Graphics/Shader/Decoders/XmadCMode.cs b/Ryujinx.Graphics.Shader/Decoders/XmadCMode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Decoders/XmadCMode.cs
rename to Ryujinx.Graphics.Shader/Decoders/XmadCMode.cs
diff --git a/Ryujinx.Graphics.Shader/DefineNames.cs b/Ryujinx.Graphics.Shader/DefineNames.cs
new file mode 100644
index 000000000..f55cbd0cc
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/DefineNames.cs
@@ -0,0 +1,13 @@
+namespace Ryujinx.Graphics.Shader
+{
+ public static class DefineNames
+ {
+ public const string InputTopologyName = "S_INPUT_TOPOLOGY";
+
+ public const string OutQualifierPrefixName = "S_OUT_QUALIFIER";
+
+ public const string LocalSizeX = "S_LOCAL_SIZE_X";
+ public const string LocalSizeY = "S_LOCAL_SIZE_Y";
+ public const string LocalSizeZ = "S_LOCAL_SIZE_Z";
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitAlu.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitAlu.cs
similarity index 96%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitAlu.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitAlu.cs
index 8e2b39bfe..5cbb3b732 100644
--- a/Ryujinx.Graphics/Shader/Instructions/InstEmitAlu.cs
+++ b/Ryujinx.Graphics.Shader/Instructions/InstEmitAlu.cs
@@ -39,6 +39,25 @@ namespace Ryujinx.Graphics.Shader.Instructions
// TODO: CC, X, corner cases
}
+ public static void Csetp(EmitterContext context)
+ {
+ OpCodePsetp op = (OpCodePsetp)context.CurrOp;
+
+ // TODO: Implement that properly
+
+ Operand p0Res = Const(IrConsts.True);
+
+ Operand p1Res = context.BitwiseNot(p0Res);
+
+ Operand pred = GetPredicate39(context);
+
+ p0Res = GetPredLogicalOp(context, op.LogicalOp, p0Res, pred);
+ p1Res = GetPredLogicalOp(context, op.LogicalOp, p1Res, pred);
+
+ context.Copy(Register(op.Predicate3), p0Res);
+ context.Copy(Register(op.Predicate0), p1Res);
+ }
+
public static void Iadd(EmitterContext context)
{
OpCodeAlu op = (OpCodeAlu)context.CurrOp;
@@ -50,6 +69,11 @@ namespace Ryujinx.Graphics.Shader.Instructions
negateB = op.RawOpCode.Extract(48);
negateA = op.RawOpCode.Extract(49);
}
+ else
+ {
+ // TODO: Other IADD32I variant without the negate.
+ negateA = op.RawOpCode.Extract(56);
+ }
Operand srcA = context.INegate(GetSrcA(context), negateA);
Operand srcB = context.INegate(GetSrcB(context), negateB);
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitAluHelper.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitAluHelper.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitAluHelper.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitAluHelper.cs
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitConversion.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitConversion.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitConversion.cs
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitFArith.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitFArith.cs
similarity index 90%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitFArith.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitFArith.cs
index b22639de9..2ecdee274 100644
--- a/Ryujinx.Graphics/Shader/Instructions/InstEmitFArith.cs
+++ b/Ryujinx.Graphics.Shader/Instructions/InstEmitFArith.cs
@@ -155,10 +155,10 @@ namespace Ryujinx.Graphics.Shader.Instructions
Condition cmpOp = (Condition)op.RawOpCode.Extract(48, 4);
+ bool negateB = op.RawOpCode.Extract(6);
bool absoluteA = op.RawOpCode.Extract(7);
bool negateA = op.RawOpCode.Extract(43);
bool absoluteB = op.RawOpCode.Extract(44);
- bool negateB = op.RawOpCode.Extract(6);
Operand srcA = context.FPAbsNeg(GetSrcA(context), absoluteA, negateA);
Operand srcB = context.FPAbsNeg(GetSrcB(context), absoluteB, negateB);
@@ -234,6 +234,39 @@ namespace Ryujinx.Graphics.Shader.Instructions
context.Copy(GetDest(context), GetHalfPacked(context, res));
}
+ public static void Hsetp2(EmitterContext context)
+ {
+ OpCodeSet op = (OpCodeSet)context.CurrOp;
+
+ bool hAnd = op.RawOpCode.Extract(53);
+
+ Condition cmpOp = op is IOpCodeReg
+ ? (Condition)op.RawOpCode.Extract(35, 4)
+ : (Condition)op.RawOpCode.Extract(49, 4);
+
+ Operand[] srcA = GetHalfSrcA(context);
+ Operand[] srcB = GetHalfSrcB(context);
+
+ Operand[] res = new Operand[2];
+
+ Operand pred = GetPredicate39(context);
+
+ Operand p0Res = GetFPComparison(context, cmpOp, srcA[0], srcB[0]);
+ Operand p1Res = GetFPComparison(context, cmpOp, srcA[1], srcB[1]);
+
+ if (hAnd)
+ {
+ p0Res = context.BitwiseAnd(p0Res, p1Res);
+ p1Res = context.BitwiseNot(p0Res);
+ }
+
+ p0Res = GetPredLogicalOp(context, op.LogicalOp, p0Res, pred);
+ p1Res = GetPredLogicalOp(context, op.LogicalOp, p1Res, pred);
+
+ context.Copy(Register(op.Predicate3), p0Res);
+ context.Copy(Register(op.Predicate0), p1Res);
+ }
+
public static void Mufu(EmitterContext context)
{
IOpCodeFArith op = (IOpCodeFArith)context.CurrOp;
@@ -346,14 +379,14 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
IOpCodeHfma op = (IOpCodeHfma)context.CurrOp;
- return GetHalfSources(context, GetSrcA(context), op.SwizzleA);
+ return GetHalfUnpacked(context, GetSrcA(context), op.SwizzleA);
}
private static Operand[] GetHfmaSrcB(EmitterContext context)
{
IOpCodeHfma op = (IOpCodeHfma)context.CurrOp;
- Operand[] operands = GetHalfSources(context, GetSrcB(context), op.SwizzleB);
+ Operand[] operands = GetHalfUnpacked(context, GetSrcB(context), op.SwizzleB);
return FPAbsNeg(context, operands, false, op.NegateB);
}
@@ -362,7 +395,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
IOpCodeHfma op = (IOpCodeHfma)context.CurrOp;
- Operand[] operands = GetHalfSources(context, GetSrcC(context), op.SwizzleC);
+ Operand[] operands = GetHalfUnpacked(context, GetSrcC(context), op.SwizzleC);
return FPAbsNeg(context, operands, false, op.NegateC);
}
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitFlow.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitFlow.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitFlow.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitFlow.cs
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitHelper.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitHelper.cs
similarity index 95%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitHelper.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitHelper.cs
index c87e1789d..c0a3012a8 100644
--- a/Ryujinx.Graphics/Shader/Instructions/InstEmitHelper.cs
+++ b/Ryujinx.Graphics.Shader/Instructions/InstEmitHelper.cs
@@ -49,7 +49,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
int h = context.CurrOp.RawOpCode.Extract(41, 1);
- return GetHalfSources(context, GetSrcB(context), FPHalfSwizzle.FP16)[h];
+ return GetHalfUnpacked(context, GetSrcB(context), FPHalfSwizzle.FP16)[h];
}
else if (floatType == FPType.FP64)
{
@@ -118,7 +118,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
FPHalfSwizzle swizzle = (FPHalfSwizzle)op.RawOpCode.Extract(47, 2);
- Operand[] operands = GetHalfSources(context, GetSrcA(context), swizzle);
+ Operand[] operands = GetHalfUnpacked(context, GetSrcA(context), swizzle);
return FPAbsNeg(context, operands, absoluteA, negateA);
}
@@ -145,7 +145,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
absoluteB = op.RawOpCode.Extract(54);
}
- Operand[] operands = GetHalfSources(context, GetSrcB(context), swizzle);
+ Operand[] operands = GetHalfUnpacked(context, GetSrcB(context), swizzle);
return FPAbsNeg(context, operands, absoluteB, negateB);
}
@@ -160,7 +160,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
return operands;
}
- public static Operand[] GetHalfSources(EmitterContext context, Operand src, FPHalfSwizzle swizzle)
+ public static Operand[] GetHalfUnpacked(EmitterContext context, Operand src, FPHalfSwizzle swizzle)
{
switch (swizzle)
{
diff --git a/Ryujinx.Graphics.Shader/Instructions/InstEmitMemory.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitMemory.cs
new file mode 100644
index 000000000..ee210f22e
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Instructions/InstEmitMemory.cs
@@ -0,0 +1,325 @@
+using Ryujinx.Graphics.Shader.Decoders;
+using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using Ryujinx.Graphics.Shader.Translation;
+
+using static Ryujinx.Graphics.Shader.Instructions.InstEmitHelper;
+using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
+
+namespace Ryujinx.Graphics.Shader.Instructions
+{
+ static partial class InstEmit
+ {
+ public static void Ald(EmitterContext context)
+ {
+ OpCodeAttribute op = (OpCodeAttribute)context.CurrOp;
+
+ Operand primVertex = context.Copy(GetSrcC(context));
+
+ for (int index = 0; index < op.Count; index++)
+ {
+ Register rd = new Register(op.Rd.Index + index, RegisterType.Gpr);
+
+ if (rd.IsRZ)
+ {
+ break;
+ }
+
+ Operand src = Attribute(op.AttributeOffset + index * 4);
+
+ context.Copy(Register(rd), context.LoadAttribute(src, primVertex));
+ }
+ }
+
+ public static void Ast(EmitterContext context)
+ {
+ OpCodeAttribute op = (OpCodeAttribute)context.CurrOp;
+
+ for (int index = 0; index < op.Count; index++)
+ {
+ if (op.Rd.Index + index > RegisterConsts.RegisterZeroIndex)
+ {
+ break;
+ }
+
+ Register rd = new Register(op.Rd.Index + index, RegisterType.Gpr);
+
+ Operand dest = Attribute(op.AttributeOffset + index * 4);
+
+ context.Copy(dest, Register(rd));
+ }
+ }
+
+ public static void Ipa(EmitterContext context)
+ {
+ OpCodeIpa op = (OpCodeIpa)context.CurrOp;
+
+ InterpolationQualifier iq = InterpolationQualifier.None;
+
+ switch (op.Mode)
+ {
+ case InterpolationMode.Pass: iq = InterpolationQualifier.NoPerspective; break;
+ }
+
+ Operand srcA = Attribute(op.AttributeOffset, iq);
+
+ Operand srcB = GetSrcB(context);
+
+ Operand res = context.FPSaturate(srcA, op.Saturate);
+
+ context.Copy(GetDest(context), res);
+ }
+
+ public static void Isberd(EmitterContext context)
+ {
+ // This instruction performs a load from ISBE memory,
+ // however it seems to be only used to get some vertex
+ // input data, so we instead propagate the offset so that
+ // it can be used on the attribute load.
+ context.Copy(GetDest(context), GetSrcA(context));
+ }
+
+ public static void Ld(EmitterContext context)
+ {
+ LoadLocalOrGlobal(context, isGlobal: false);
+ }
+
+ public static void Ldc(EmitterContext context)
+ {
+ OpCodeLdc op = (OpCodeLdc)context.CurrOp;
+
+ if (op.Size > IntegerSize.B64)
+ {
+ // TODO: Warning.
+ }
+
+ bool isSmallInt = op.Size < IntegerSize.B32;
+
+ int count = op.Size == IntegerSize.B64 ? 2 : 1;
+
+ Operand wordOffset = context.ShiftRightU32(GetSrcA(context), Const(2));
+
+ wordOffset = context.IAdd(wordOffset, Const(op.Offset));
+
+ Operand bitOffset = GetBitOffset(context, GetSrcA(context));
+
+ for (int index = 0; index < count; index++)
+ {
+ Register rd = new Register(op.Rd.Index + index, RegisterType.Gpr);
+
+ if (rd.IsRZ)
+ {
+ break;
+ }
+
+ Operand offset = context.IAdd(wordOffset, Const(index));
+
+ Operand value = context.LoadConstant(Const(op.Slot), offset);
+
+ if (isSmallInt)
+ {
+ value = ExtractSmallInt(context, op.Size, wordOffset, value);
+ }
+
+ context.Copy(Register(rd), value);
+ }
+ }
+
+ public static void Ldg(EmitterContext context)
+ {
+ LoadLocalOrGlobal(context, isGlobal: true);
+ }
+
+ public static void Out(EmitterContext context)
+ {
+ OpCode op = context.CurrOp;
+
+ bool emit = op.RawOpCode.Extract(39);
+ bool cut = op.RawOpCode.Extract(40);
+
+ if (!(emit || cut))
+ {
+ // TODO: Warning.
+ }
+
+ if (emit)
+ {
+ context.EmitVertex();
+ }
+
+ if (cut)
+ {
+ context.EndPrimitive();
+ }
+ }
+
+ public static void St(EmitterContext context)
+ {
+ StoreLocalOrGlobal(context, isGlobal: false);
+ }
+
+ public static void Stg(EmitterContext context)
+ {
+ StoreLocalOrGlobal(context, isGlobal: true);
+ }
+
+ private static void LoadLocalOrGlobal(EmitterContext context, bool isGlobal)
+ {
+ OpCodeMemory op = (OpCodeMemory)context.CurrOp;
+
+ if (op.Size > IntegerSize.B128)
+ {
+ // TODO: Warning.
+ }
+
+ bool isSmallInt = op.Size < IntegerSize.B32;
+
+ int count = 1;
+
+ switch (op.Size)
+ {
+ case IntegerSize.B64: count = 2; break;
+ case IntegerSize.B128: count = 4; break;
+ }
+
+ Operand baseOffset = context.IAdd(GetSrcA(context), Const(op.Offset));
+
+ // Word offset = byte offset / 4 (one word = 4 bytes).
+ Operand wordOffset = context.ShiftRightU32(baseOffset, Const(2));
+
+ Operand bitOffset = GetBitOffset(context, baseOffset);
+
+ for (int index = 0; index < count; index++)
+ {
+ Register rd = new Register(op.Rd.Index + index, RegisterType.Gpr);
+
+ if (rd.IsRZ)
+ {
+ break;
+ }
+
+ Operand offset = context.IAdd(wordOffset, Const(index));
+
+ Operand value = isGlobal
+ ? context.LoadGlobal(offset)
+ : context.LoadLocal (offset);
+
+ if (isSmallInt)
+ {
+ value = ExtractSmallInt(context, op.Size, bitOffset, value);
+ }
+
+ context.Copy(Register(rd), value);
+ }
+ }
+
+ private static void StoreLocalOrGlobal(EmitterContext context, bool isGlobal)
+ {
+ OpCodeMemory op = (OpCodeMemory)context.CurrOp;
+
+ if (op.Size > IntegerSize.B128)
+ {
+ // TODO: Warning.
+ }
+
+ bool isSmallInt = op.Size < IntegerSize.B32;
+
+ int count = 1;
+
+ switch (op.Size)
+ {
+ case IntegerSize.B64: count = 2; break;
+ case IntegerSize.B128: count = 4; break;
+ }
+
+ Operand baseOffset = context.IAdd(GetSrcA(context), Const(op.Offset));
+
+ Operand wordOffset = context.ShiftRightU32(baseOffset, Const(2));
+
+ Operand bitOffset = GetBitOffset(context, baseOffset);
+
+ for (int index = 0; index < count; index++)
+ {
+ Register rd = new Register(op.Rd.Index + index, RegisterType.Gpr);
+
+ if (rd.IsRZ)
+ {
+ break;
+ }
+
+ Operand value = Register(rd);
+
+ Operand offset = context.IAdd(wordOffset, Const(index));
+
+ if (isSmallInt)
+ {
+ Operand word = isGlobal
+ ? context.LoadGlobal(offset)
+ : context.LoadLocal (offset);
+
+ value = InsertSmallInt(context, op.Size, bitOffset, word, value);
+ }
+
+ if (isGlobal)
+ {
+ context.StoreGlobal(offset, value);
+ }
+ else
+ {
+ context.StoreLocal(offset, value);
+ }
+ }
+ }
+
+ private static Operand GetBitOffset(EmitterContext context, Operand baseOffset)
+ {
+ // Note: byte offset = (baseOffset & 0b11) * 8.
+ // Addresses should be always aligned to the integer type,
+ // so we don't need to take unaligned addresses into account.
+ return context.ShiftLeft(context.BitwiseAnd(baseOffset, Const(3)), Const(3));
+ }
+
+ private static Operand ExtractSmallInt(
+ EmitterContext context,
+ IntegerSize size,
+ Operand bitOffset,
+ Operand value)
+ {
+ value = context.ShiftRightU32(value, bitOffset);
+
+ switch (size)
+ {
+ case IntegerSize.U8: value = ZeroExtendTo32(context, value, 8); break;
+ case IntegerSize.U16: value = ZeroExtendTo32(context, value, 16); break;
+ case IntegerSize.S8: value = SignExtendTo32(context, value, 8); break;
+ case IntegerSize.S16: value = SignExtendTo32(context, value, 16); break;
+ }
+
+ return value;
+ }
+
+ private static Operand InsertSmallInt(
+ EmitterContext context,
+ IntegerSize size,
+ Operand bitOffset,
+ Operand word,
+ Operand value)
+ {
+ switch (size)
+ {
+ case IntegerSize.U8:
+ case IntegerSize.S8:
+ value = context.BitwiseAnd(value, Const(0xff));
+ value = context.BitfieldInsert(word, value, bitOffset, Const(8));
+ break;
+
+ case IntegerSize.U16:
+ case IntegerSize.S16:
+ value = context.BitwiseAnd(value, Const(0xffff));
+ value = context.BitfieldInsert(word, value, bitOffset, Const(16));
+ break;
+ }
+
+ return value;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/Instructions/InstEmitMove.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitMove.cs
new file mode 100644
index 000000000..f66ebc9fa
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Instructions/InstEmitMove.cs
@@ -0,0 +1,57 @@
+using Ryujinx.Graphics.Shader.Decoders;
+using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using Ryujinx.Graphics.Shader.Translation;
+
+using static Ryujinx.Graphics.Shader.Instructions.InstEmitHelper;
+using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
+
+namespace Ryujinx.Graphics.Shader.Instructions
+{
+ static partial class InstEmit
+ {
+ public static void Mov(EmitterContext context)
+ {
+ OpCodeAlu op = (OpCodeAlu)context.CurrOp;
+
+ context.Copy(GetDest(context), GetSrcB(context));
+ }
+
+ public static void S2r(EmitterContext context)
+ {
+ // TODO: Better impl.
+ OpCodeAlu op = (OpCodeAlu)context.CurrOp;
+
+ SystemRegister sysReg = (SystemRegister)op.RawOpCode.Extract(20, 8);
+
+ Operand src;
+
+ switch (sysReg)
+ {
+ case SystemRegister.ThreadIdX: src = Attribute(AttributeConsts.ThreadIdX); break;
+ case SystemRegister.ThreadIdY: src = Attribute(AttributeConsts.ThreadIdY); break;
+ case SystemRegister.ThreadIdZ: src = Attribute(AttributeConsts.ThreadIdZ); break;
+ case SystemRegister.CtaIdX: src = Attribute(AttributeConsts.CtaIdX); break;
+ case SystemRegister.CtaIdY: src = Attribute(AttributeConsts.CtaIdY); break;
+ case SystemRegister.CtaIdZ: src = Attribute(AttributeConsts.CtaIdZ); break;
+
+ default: src = Const(0); break;
+ }
+
+ context.Copy(GetDest(context), src);
+ }
+
+ public static void Sel(EmitterContext context)
+ {
+ OpCodeAlu op = (OpCodeAlu)context.CurrOp;
+
+ Operand pred = GetPredicate39(context);
+
+ Operand srcA = GetSrcA(context);
+ Operand srcB = GetSrcB(context);
+
+ Operand res = context.ConditionalSelect(pred, srcA, srcB);
+
+ context.Copy(GetDest(context), res);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitTexture.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs
similarity index 73%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitTexture.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs
index a9b29f40e..554deb7ba 100644
--- a/Ryujinx.Graphics/Shader/Instructions/InstEmitTexture.cs
+++ b/Ryujinx.Graphics.Shader/Instructions/InstEmitTexture.cs
@@ -15,7 +15,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
Tex(context, TextureFlags.None);
}
- public static void Tex_B(EmitterContext context)
+ public static void TexB(EmitterContext context)
{
Tex(context, TextureFlags.Bindless);
}
@@ -25,7 +25,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
Tex(context, TextureFlags.IntCoords);
}
- public static void Tld_B(EmitterContext context)
+ public static void TldB(EmitterContext context)
{
Tex(context, TextureFlags.IntCoords | TextureFlags.Bindless);
}
@@ -74,15 +74,15 @@ namespace Ryujinx.Graphics.Shader.Instructions
}
}
- TextureType type;
+ TextureTarget type;
TextureFlags flags;
if (op is OpCodeTexs texsOp)
{
- type = GetTextureType (texsOp.Type);
- flags = GetTextureFlags(texsOp.Type);
+ type = GetTextureType (texsOp.Target);
+ flags = GetTextureFlags(texsOp.Target);
- if ((type & TextureType.Array) != 0)
+ if ((type & TextureTarget.Array) != 0)
{
Operand arrayIndex = Ra();
@@ -91,7 +91,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
sourcesList.Add(arrayIndex);
- if ((type & TextureType.Shadow) != 0)
+ if ((type & TextureTarget.Shadow) != 0)
{
sourcesList.Add(Rb());
}
@@ -103,42 +103,42 @@ namespace Ryujinx.Graphics.Shader.Instructions
}
else
{
- switch (texsOp.Type)
+ switch (texsOp.Target)
{
- case TextureScalarType.Texture1DLodZero:
+ case Decoders.TextureTarget.Texture1DLodZero:
sourcesList.Add(Ra());
break;
- case TextureScalarType.Texture2D:
+ case Decoders.TextureTarget.Texture2D:
sourcesList.Add(Ra());
sourcesList.Add(Rb());
break;
- case TextureScalarType.Texture2DLodZero:
+ case Decoders.TextureTarget.Texture2DLodZero:
sourcesList.Add(Ra());
sourcesList.Add(Rb());
sourcesList.Add(ConstF(0));
break;
- case TextureScalarType.Texture2DLodLevel:
- case TextureScalarType.Texture2DDepthCompare:
- case TextureScalarType.Texture3D:
- case TextureScalarType.TextureCube:
+ case Decoders.TextureTarget.Texture2DLodLevel:
+ case Decoders.TextureTarget.Texture2DDepthCompare:
+ case Decoders.TextureTarget.Texture3D:
+ case Decoders.TextureTarget.TextureCube:
sourcesList.Add(Ra());
sourcesList.Add(Ra());
sourcesList.Add(Rb());
break;
- case TextureScalarType.Texture2DLodZeroDepthCompare:
- case TextureScalarType.Texture3DLodZero:
+ case Decoders.TextureTarget.Texture2DLodZeroDepthCompare:
+ case Decoders.TextureTarget.Texture3DLodZero:
sourcesList.Add(Ra());
sourcesList.Add(Ra());
sourcesList.Add(Rb());
sourcesList.Add(ConstF(0));
break;
- case TextureScalarType.Texture2DLodLevelDepthCompare:
- case TextureScalarType.TextureCubeLodLevel:
+ case Decoders.TextureTarget.Texture2DLodLevelDepthCompare:
+ case Decoders.TextureTarget.TextureCubeLodLevel:
sourcesList.Add(Ra());
sourcesList.Add(Ra());
sourcesList.Add(Rb());
@@ -149,49 +149,49 @@ namespace Ryujinx.Graphics.Shader.Instructions
}
else if (op is OpCodeTlds tldsOp)
{
- type = GetTextureType (tldsOp.Type);
- flags = GetTextureFlags(tldsOp.Type) | TextureFlags.IntCoords;
+ type = GetTextureType (tldsOp.Target);
+ flags = GetTextureFlags(tldsOp.Target) | TextureFlags.IntCoords;
- switch (tldsOp.Type)
+ switch (tldsOp.Target)
{
- case TexelLoadScalarType.Texture1DLodZero:
+ case TexelLoadTarget.Texture1DLodZero:
sourcesList.Add(Ra());
sourcesList.Add(Const(0));
break;
- case TexelLoadScalarType.Texture1DLodLevel:
+ case TexelLoadTarget.Texture1DLodLevel:
sourcesList.Add(Ra());
sourcesList.Add(Rb());
break;
- case TexelLoadScalarType.Texture2DLodZero:
+ case TexelLoadTarget.Texture2DLodZero:
sourcesList.Add(Ra());
sourcesList.Add(Rb());
sourcesList.Add(Const(0));
break;
- case TexelLoadScalarType.Texture2DLodZeroOffset:
+ case TexelLoadTarget.Texture2DLodZeroOffset:
sourcesList.Add(Ra());
sourcesList.Add(Ra());
sourcesList.Add(Const(0));
break;
- case TexelLoadScalarType.Texture2DLodZeroMultisample:
- case TexelLoadScalarType.Texture2DLodLevel:
- case TexelLoadScalarType.Texture2DLodLevelOffset:
+ case TexelLoadTarget.Texture2DLodZeroMultisample:
+ case TexelLoadTarget.Texture2DLodLevel:
+ case TexelLoadTarget.Texture2DLodLevelOffset:
sourcesList.Add(Ra());
sourcesList.Add(Ra());
sourcesList.Add(Rb());
break;
- case TexelLoadScalarType.Texture3DLodZero:
+ case TexelLoadTarget.Texture3DLodZero:
sourcesList.Add(Ra());
sourcesList.Add(Ra());
sourcesList.Add(Rb());
sourcesList.Add(Const(0));
break;
- case TexelLoadScalarType.Texture2DArrayLodZero:
+ case TexelLoadTarget.Texture2DArrayLodZero:
sourcesList.Add(Rb());
sourcesList.Add(Rb());
sourcesList.Add(Ra());
@@ -201,7 +201,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
if ((flags & TextureFlags.Offset) != 0)
{
- AddTextureOffset(type.GetCoordsCount(), 4, 4);
+ AddTextureOffset(type.GetDimensions(), 4, 4);
}
}
else if (op is OpCodeTld4s tld4sOp)
@@ -217,19 +217,19 @@ namespace Ryujinx.Graphics.Shader.Instructions
sourcesList.Add(Ra());
}
- type = TextureType.Texture2D;
+ type = TextureTarget.Texture2D;
flags = TextureFlags.Gather;
if (tld4sOp.HasDepthCompare)
{
sourcesList.Add(Rb());
- type |= TextureType.Shadow;
+ type |= TextureTarget.Shadow;
}
if (tld4sOp.HasOffset)
{
- AddTextureOffset(type.GetCoordsCount(), 8, 6);
+ AddTextureOffset(type.GetDimensions(), 8, 6);
flags |= TextureFlags.Offset;
}
@@ -338,11 +338,11 @@ namespace Ryujinx.Graphics.Shader.Instructions
List sourcesList = new List();
- TextureType type = GetTextureType(op.Dimensions);
+ TextureTarget type = GetTextureType(op.Dimensions);
TextureFlags flags = TextureFlags.Gather;
- int coordsCount = type.GetCoordsCount();
+ int coordsCount = type.GetDimensions();
for (int index = 0; index < coordsCount; index++)
{
@@ -353,7 +353,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
sourcesList.Add(arrayIndex);
- type |= TextureType.Array;
+ type |= TextureTarget.Array;
}
Operand[] packedOffs = new Operand[2];
@@ -365,7 +365,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
sourcesList.Add(Rb());
- type |= TextureType.Shadow;
+ type |= TextureTarget.Shadow;
}
if (op.Offset != TextureGatherOffset.None)
@@ -427,7 +427,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
Txq(context, bindless: false);
}
- public static void Txq_B(EmitterContext context)
+ public static void TxqB(EmitterContext context)
{
Txq(context, bindless: true);
}
@@ -446,7 +446,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
// TODO: Validate and use property.
Instruction inst = Instruction.TextureSize;
- TextureType type = TextureType.Texture2D;
+ TextureTarget type = TextureTarget.Texture2D;
TextureFlags flags = bindless ? TextureFlags.Bindless : TextureFlags.None;
@@ -551,9 +551,9 @@ namespace Ryujinx.Graphics.Shader.Instructions
sourcesList.Add(Rb());
}
- TextureType type = GetTextureType(op.Dimensions);
+ TextureTarget type = GetTextureType(op.Dimensions);
- int coordsCount = type.GetCoordsCount();
+ int coordsCount = type.GetDimensions();
for (int index = 0; index < coordsCount; index++)
{
@@ -564,7 +564,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
sourcesList.Add(arrayIndex);
- type |= TextureType.Array;
+ type |= TextureTarget.Array;
}
bool hasLod = op.LodMode > TextureLodMode.LodZero;
@@ -577,7 +577,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
sourcesList.Add(Rb());
- type |= TextureType.Shadow;
+ type |= TextureTarget.Shadow;
}
if ((op.LodMode == TextureLodMode.LodZero ||
@@ -611,7 +611,7 @@ namespace Ryujinx.Graphics.Shader.Instructions
{
sourcesList.Add(Rb());
- type |= TextureType.Multisample;
+ type |= TextureTarget.Multisample;
}
Operand[] sources = sourcesList.ToArray();
@@ -650,123 +650,123 @@ namespace Ryujinx.Graphics.Shader.Instructions
}
}
- private static TextureType GetTextureType(TextureDimensions dimensions)
+ private static TextureTarget GetTextureType(TextureDimensions dimensions)
{
switch (dimensions)
{
- case TextureDimensions.Texture1D: return TextureType.Texture1D;
- case TextureDimensions.Texture2D: return TextureType.Texture2D;
- case TextureDimensions.Texture3D: return TextureType.Texture3D;
- case TextureDimensions.TextureCube: return TextureType.TextureCube;
+ case TextureDimensions.Texture1D: return TextureTarget.Texture1D;
+ case TextureDimensions.Texture2D: return TextureTarget.Texture2D;
+ case TextureDimensions.Texture3D: return TextureTarget.Texture3D;
+ case TextureDimensions.TextureCube: return TextureTarget.TextureCube;
}
throw new ArgumentException($"Invalid texture dimensions \"{dimensions}\".");
}
- private static TextureType GetTextureType(TextureScalarType type)
+ private static TextureTarget GetTextureType(Decoders.TextureTarget type)
{
switch (type)
{
- case TextureScalarType.Texture1DLodZero:
- return TextureType.Texture1D;
+ case Decoders.TextureTarget.Texture1DLodZero:
+ return TextureTarget.Texture1D;
- case TextureScalarType.Texture2D:
- case TextureScalarType.Texture2DLodZero:
- case TextureScalarType.Texture2DLodLevel:
- return TextureType.Texture2D;
+ case Decoders.TextureTarget.Texture2D:
+ case Decoders.TextureTarget.Texture2DLodZero:
+ case Decoders.TextureTarget.Texture2DLodLevel:
+ return TextureTarget.Texture2D;
- case TextureScalarType.Texture2DDepthCompare:
- case TextureScalarType.Texture2DLodLevelDepthCompare:
- case TextureScalarType.Texture2DLodZeroDepthCompare:
- return TextureType.Texture2D | TextureType.Shadow;
+ case Decoders.TextureTarget.Texture2DDepthCompare:
+ case Decoders.TextureTarget.Texture2DLodLevelDepthCompare:
+ case Decoders.TextureTarget.Texture2DLodZeroDepthCompare:
+ return TextureTarget.Texture2D | TextureTarget.Shadow;
- case TextureScalarType.Texture2DArray:
- case TextureScalarType.Texture2DArrayLodZero:
- return TextureType.Texture2D | TextureType.Array;
+ case Decoders.TextureTarget.Texture2DArray:
+ case Decoders.TextureTarget.Texture2DArrayLodZero:
+ return TextureTarget.Texture2D | TextureTarget.Array;
- case TextureScalarType.Texture2DArrayLodZeroDepthCompare:
- return TextureType.Texture2D | TextureType.Array | TextureType.Shadow;
+ case Decoders.TextureTarget.Texture2DArrayLodZeroDepthCompare:
+ return TextureTarget.Texture2D | TextureTarget.Array | TextureTarget.Shadow;
- case TextureScalarType.Texture3D:
- case TextureScalarType.Texture3DLodZero:
- return TextureType.Texture3D;
+ case Decoders.TextureTarget.Texture3D:
+ case Decoders.TextureTarget.Texture3DLodZero:
+ return TextureTarget.Texture3D;
- case TextureScalarType.TextureCube:
- case TextureScalarType.TextureCubeLodLevel:
- return TextureType.TextureCube;
+ case Decoders.TextureTarget.TextureCube:
+ case Decoders.TextureTarget.TextureCubeLodLevel:
+ return TextureTarget.TextureCube;
}
throw new ArgumentException($"Invalid texture type \"{type}\".");
}
- private static TextureType GetTextureType(TexelLoadScalarType type)
+ private static TextureTarget GetTextureType(TexelLoadTarget type)
{
switch (type)
{
- case TexelLoadScalarType.Texture1DLodZero:
- case TexelLoadScalarType.Texture1DLodLevel:
- return TextureType.Texture1D;
+ case TexelLoadTarget.Texture1DLodZero:
+ case TexelLoadTarget.Texture1DLodLevel:
+ return TextureTarget.Texture1D;
- case TexelLoadScalarType.Texture2DLodZero:
- case TexelLoadScalarType.Texture2DLodZeroOffset:
- case TexelLoadScalarType.Texture2DLodLevel:
- case TexelLoadScalarType.Texture2DLodLevelOffset:
- return TextureType.Texture2D;
+ case TexelLoadTarget.Texture2DLodZero:
+ case TexelLoadTarget.Texture2DLodZeroOffset:
+ case TexelLoadTarget.Texture2DLodLevel:
+ case TexelLoadTarget.Texture2DLodLevelOffset:
+ return TextureTarget.Texture2D;
- case TexelLoadScalarType.Texture2DLodZeroMultisample:
- return TextureType.Texture2D | TextureType.Multisample;
+ case TexelLoadTarget.Texture2DLodZeroMultisample:
+ return TextureTarget.Texture2D | TextureTarget.Multisample;
- case TexelLoadScalarType.Texture3DLodZero:
- return TextureType.Texture3D;
+ case TexelLoadTarget.Texture3DLodZero:
+ return TextureTarget.Texture3D;
- case TexelLoadScalarType.Texture2DArrayLodZero:
- return TextureType.Texture2D | TextureType.Array;
+ case TexelLoadTarget.Texture2DArrayLodZero:
+ return TextureTarget.Texture2D | TextureTarget.Array;
}
throw new ArgumentException($"Invalid texture type \"{type}\".");
}
- private static TextureFlags GetTextureFlags(TextureScalarType type)
+ private static TextureFlags GetTextureFlags(Decoders.TextureTarget type)
{
switch (type)
{
- case TextureScalarType.Texture1DLodZero:
- case TextureScalarType.Texture2DLodZero:
- case TextureScalarType.Texture2DLodLevel:
- case TextureScalarType.Texture2DLodLevelDepthCompare:
- case TextureScalarType.Texture2DLodZeroDepthCompare:
- case TextureScalarType.Texture2DArrayLodZero:
- case TextureScalarType.Texture2DArrayLodZeroDepthCompare:
- case TextureScalarType.Texture3DLodZero:
- case TextureScalarType.TextureCubeLodLevel:
+ case Decoders.TextureTarget.Texture1DLodZero:
+ case Decoders.TextureTarget.Texture2DLodZero:
+ case Decoders.TextureTarget.Texture2DLodLevel:
+ case Decoders.TextureTarget.Texture2DLodLevelDepthCompare:
+ case Decoders.TextureTarget.Texture2DLodZeroDepthCompare:
+ case Decoders.TextureTarget.Texture2DArrayLodZero:
+ case Decoders.TextureTarget.Texture2DArrayLodZeroDepthCompare:
+ case Decoders.TextureTarget.Texture3DLodZero:
+ case Decoders.TextureTarget.TextureCubeLodLevel:
return TextureFlags.LodLevel;
- case TextureScalarType.Texture2D:
- case TextureScalarType.Texture2DDepthCompare:
- case TextureScalarType.Texture2DArray:
- case TextureScalarType.Texture3D:
- case TextureScalarType.TextureCube:
+ case Decoders.TextureTarget.Texture2D:
+ case Decoders.TextureTarget.Texture2DDepthCompare:
+ case Decoders.TextureTarget.Texture2DArray:
+ case Decoders.TextureTarget.Texture3D:
+ case Decoders.TextureTarget.TextureCube:
return TextureFlags.None;
}
throw new ArgumentException($"Invalid texture type \"{type}\".");
}
- private static TextureFlags GetTextureFlags(TexelLoadScalarType type)
+ private static TextureFlags GetTextureFlags(TexelLoadTarget type)
{
switch (type)
{
- case TexelLoadScalarType.Texture1DLodZero:
- case TexelLoadScalarType.Texture1DLodLevel:
- case TexelLoadScalarType.Texture2DLodZero:
- case TexelLoadScalarType.Texture2DLodLevel:
- case TexelLoadScalarType.Texture2DLodZeroMultisample:
- case TexelLoadScalarType.Texture3DLodZero:
- case TexelLoadScalarType.Texture2DArrayLodZero:
+ case TexelLoadTarget.Texture1DLodZero:
+ case TexelLoadTarget.Texture1DLodLevel:
+ case TexelLoadTarget.Texture2DLodZero:
+ case TexelLoadTarget.Texture2DLodLevel:
+ case TexelLoadTarget.Texture2DLodZeroMultisample:
+ case TexelLoadTarget.Texture3DLodZero:
+ case TexelLoadTarget.Texture2DArrayLodZero:
return TextureFlags.LodLevel;
- case TexelLoadScalarType.Texture2DLodZeroOffset:
- case TexelLoadScalarType.Texture2DLodLevelOffset:
+ case TexelLoadTarget.Texture2DLodZeroOffset:
+ case TexelLoadTarget.Texture2DLodLevelOffset:
return TextureFlags.LodLevel | TextureFlags.Offset;
}
diff --git a/Ryujinx.Graphics.Shader/Instructions/InstEmitVideo.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitVideo.cs
new file mode 100644
index 000000000..b19e9fa13
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Instructions/InstEmitVideo.cs
@@ -0,0 +1,19 @@
+using Ryujinx.Graphics.Shader.Decoders;
+using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using Ryujinx.Graphics.Shader.Translation;
+
+using static Ryujinx.Graphics.Shader.Instructions.InstEmitHelper;
+using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
+
+namespace Ryujinx.Graphics.Shader.Instructions
+{
+ static partial class InstEmit
+ {
+ public static void Vmad(EmitterContext context)
+ {
+ OpCodeVideo op = (OpCodeVideo)context.CurrOp;
+
+ context.Copy(GetDest(context), GetSrcC(context));
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Instructions/InstEmitter.cs b/Ryujinx.Graphics.Shader/Instructions/InstEmitter.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Instructions/InstEmitter.cs
rename to Ryujinx.Graphics.Shader/Instructions/InstEmitter.cs
diff --git a/Ryujinx.Graphics/Shader/Instructions/Lop3Expression.cs b/Ryujinx.Graphics.Shader/Instructions/Lop3Expression.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Instructions/Lop3Expression.cs
rename to Ryujinx.Graphics.Shader/Instructions/Lop3Expression.cs
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/BasicBlock.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/BasicBlock.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/BasicBlock.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/BasicBlock.cs
diff --git a/Ryujinx.Graphics.Shader/IntermediateRepresentation/CommentNode.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/CommentNode.cs
new file mode 100644
index 000000000..d4d87b067
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/IntermediateRepresentation/CommentNode.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
+{
+ class CommentNode : Operation
+ {
+ public string Comment { get; }
+
+ public CommentNode(string comment) : base(Instruction.Comment, null)
+ {
+ Comment = comment;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/INode.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/INode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/INode.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/INode.cs
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/Instruction.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/Instruction.cs
similarity index 95%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/Instruction.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/Instruction.cs
index ac0ebc2b0..e580965e7 100644
--- a/Ryujinx.Graphics/Shader/IntermediateRepresentation/Instruction.cs
+++ b/Ryujinx.Graphics.Shader/IntermediateRepresentation/Instruction.cs
@@ -21,6 +21,7 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
Ceiling,
Clamp,
ClampU32,
+ Comment,
CompareEqual,
CompareGreater,
CompareGreaterOrEqual,
@@ -45,9 +46,11 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
Floor,
FusedMultiplyAdd,
IsNan,
+ LoadAttribute,
LoadConstant,
LoadGlobal,
LoadLocal,
+ LoadStorage,
LogarithmB2,
LogicalAnd,
LogicalExclusiveOr,
@@ -73,6 +76,7 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
SquareRoot,
StoreGlobal,
StoreLocal,
+ StoreStorage,
Subtract,
TextureSample,
TextureSize,
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/IrConsts.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/IrConsts.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/IrConsts.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/IrConsts.cs
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/Operand.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/Operand.cs
similarity index 86%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/Operand.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/Operand.cs
index 1df88a3d9..567277a75 100644
--- a/Ryujinx.Graphics/Shader/IntermediateRepresentation/Operand.cs
+++ b/Ryujinx.Graphics.Shader/IntermediateRepresentation/Operand.cs
@@ -14,6 +14,8 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
public int Value { get; }
+ public InterpolationQualifier Interpolation { get; }
+
public INode AsgOp { get; set; }
public HashSet UseOps { get; }
@@ -28,10 +30,11 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
Type = type;
}
- public Operand(OperandType type, int value) : this()
+ public Operand(OperandType type, int value, InterpolationQualifier iq = InterpolationQualifier.None) : this()
{
- Type = type;
- Value = value;
+ Type = type;
+ Value = value;
+ Interpolation = iq;
}
public Operand(Register reg) : this()
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/OperandHelper.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/OperandHelper.cs
similarity index 88%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/OperandHelper.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/OperandHelper.cs
index 6765f8a44..45c9ba1e5 100644
--- a/Ryujinx.Graphics/Shader/IntermediateRepresentation/OperandHelper.cs
+++ b/Ryujinx.Graphics.Shader/IntermediateRepresentation/OperandHelper.cs
@@ -5,9 +5,9 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
{
static class OperandHelper
{
- public static Operand Attribute(int value)
+ public static Operand Attribute(int value, InterpolationQualifier iq = InterpolationQualifier.None)
{
- return new Operand(OperandType.Attribute, value);
+ return new Operand(OperandType.Attribute, value, iq);
}
public static Operand Cbuf(int slot, int offset)
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/OperandType.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/OperandType.cs
similarity index 84%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/OperandType.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/OperandType.cs
index e0e2a6675..8f8df9e4f 100644
--- a/Ryujinx.Graphics/Shader/IntermediateRepresentation/OperandType.cs
+++ b/Ryujinx.Graphics.Shader/IntermediateRepresentation/OperandType.cs
@@ -5,9 +5,7 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
Attribute,
Constant,
ConstantBuffer,
- GlobalMemory,
Label,
- LocalMemory,
LocalVariable,
Register,
Undefined
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/Operation.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/Operation.cs
similarity index 93%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/Operation.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/Operation.cs
index c60f393e7..fc01d47ea 100644
--- a/Ryujinx.Graphics/Shader/IntermediateRepresentation/Operation.cs
+++ b/Ryujinx.Graphics.Shader/IntermediateRepresentation/Operation.cs
@@ -70,7 +70,7 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
oldSrc.UseOps.Remove(this);
}
- if (source.Type == OperandType.LocalVariable)
+ if (source != null && source.Type == OperandType.LocalVariable)
{
source.UseOps.Add(this);
}
@@ -84,7 +84,7 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
foreach (Operand oldSrc in _sources)
{
- if (oldSrc.Type == OperandType.LocalVariable)
+ if (oldSrc != null && oldSrc.Type == OperandType.LocalVariable)
{
oldSrc.UseOps.Remove(this);
}
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/PhiNode.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/PhiNode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/PhiNode.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/PhiNode.cs
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/TextureFlags.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/TextureFlags.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/TextureFlags.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/TextureFlags.cs
diff --git a/Ryujinx.Graphics/Shader/IntermediateRepresentation/TextureOperation.cs b/Ryujinx.Graphics.Shader/IntermediateRepresentation/TextureOperation.cs
similarity index 76%
rename from Ryujinx.Graphics/Shader/IntermediateRepresentation/TextureOperation.cs
rename to Ryujinx.Graphics.Shader/IntermediateRepresentation/TextureOperation.cs
index f5f2cc5c6..0c768345c 100644
--- a/Ryujinx.Graphics/Shader/IntermediateRepresentation/TextureOperation.cs
+++ b/Ryujinx.Graphics.Shader/IntermediateRepresentation/TextureOperation.cs
@@ -2,21 +2,21 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
{
class TextureOperation : Operation
{
- public TextureType Type { get; }
- public TextureFlags Flags { get; }
+ public TextureTarget Target { get; }
+ public TextureFlags Flags { get; }
public int Handle { get; }
public TextureOperation(
Instruction inst,
- TextureType type,
+ TextureTarget target,
TextureFlags flags,
int handle,
int compIndex,
Operand dest,
params Operand[] sources) : base(inst, compIndex, dest, sources)
{
- Type = type;
+ Target = target;
Flags = flags;
Handle = handle;
}
diff --git a/Ryujinx.Graphics.Shader/InterpolationQualifier.cs b/Ryujinx.Graphics.Shader/InterpolationQualifier.cs
new file mode 100644
index 000000000..e710427dd
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/InterpolationQualifier.cs
@@ -0,0 +1,45 @@
+using System;
+
+namespace Ryujinx.Graphics.Shader
+{
+ [Flags]
+ public enum InterpolationQualifier
+ {
+ None = 0,
+
+ Flat = 1,
+ NoPerspective = 2,
+ Smooth = 3,
+
+ Centroid = 1 << 16,
+ Sample = 1 << 17,
+
+ FlagsMask = Centroid | Sample
+ }
+
+ public static class InterpolationQualifierExtensions
+ {
+ public static string ToGlslQualifier(this InterpolationQualifier iq)
+ {
+ string output = string.Empty;
+
+ switch (iq & ~InterpolationQualifier.FlagsMask)
+ {
+ case InterpolationQualifier.Flat: output = "flat"; break;
+ case InterpolationQualifier.NoPerspective: output = "noperspective"; break;
+ case InterpolationQualifier.Smooth: output = "smooth"; break;
+ }
+
+ if ((iq & InterpolationQualifier.Centroid) != 0)
+ {
+ output = "centroid " + output;
+ }
+ else if ((iq & InterpolationQualifier.Sample) != 0)
+ {
+ output = "sample " + output;
+ }
+
+ return output;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/OutputTopology.cs b/Ryujinx.Graphics.Shader/OutputTopology.cs
new file mode 100644
index 000000000..e8336aa3f
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/OutputTopology.cs
@@ -0,0 +1,9 @@
+namespace Ryujinx.Graphics.Shader
+{
+ enum OutputTopology
+ {
+ PointList = 1,
+ LineStrip = 6,
+ TriangleStrip = 7
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/Ryujinx.Graphics.Shader.csproj b/Ryujinx.Graphics.Shader/Ryujinx.Graphics.Shader.csproj
new file mode 100644
index 000000000..ea83d2968
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Ryujinx.Graphics.Shader.csproj
@@ -0,0 +1,7 @@
+
+
+
+ netcoreapp3.0
+
+
+
diff --git a/Ryujinx.Graphics.Shader/ShaderConfig.cs b/Ryujinx.Graphics.Shader/ShaderConfig.cs
new file mode 100644
index 000000000..6ab4689a6
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/ShaderConfig.cs
@@ -0,0 +1,30 @@
+using Ryujinx.Graphics.Shader.Translation;
+
+namespace Ryujinx.Graphics.Shader
+{
+ struct ShaderConfig
+ {
+ public ShaderStage Stage { get; }
+
+ public TranslationFlags Flags { get; }
+
+ public int MaxCBufferSize { get; }
+ public int MaxOutputVertices { get; }
+
+ public OutputTopology OutputTopology { get; }
+
+ public ShaderConfig(
+ ShaderStage stage,
+ TranslationFlags flags,
+ int maxCBufferSize,
+ int maxOutputVertices,
+ OutputTopology outputTopology)
+ {
+ Stage = stage;
+ Flags = flags;
+ MaxCBufferSize = maxCBufferSize;
+ MaxOutputVertices = maxOutputVertices;
+ OutputTopology = outputTopology;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/ShaderHeader.cs b/Ryujinx.Graphics.Shader/ShaderHeader.cs
similarity index 80%
rename from Ryujinx.Graphics/Shader/ShaderHeader.cs
rename to Ryujinx.Graphics.Shader/ShaderHeader.cs
index 379f3f35d..94c574359 100644
--- a/Ryujinx.Graphics/Shader/ShaderHeader.cs
+++ b/Ryujinx.Graphics.Shader/ShaderHeader.cs
@@ -1,6 +1,6 @@
-using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Shader.Decoders;
using System;
+using System.Runtime.InteropServices;
namespace Ryujinx.Graphics.Shader
{
@@ -38,10 +38,9 @@ namespace Ryujinx.Graphics.Shader
class ShaderHeader
{
public int SphType { get; }
-
public int Version { get; }
- public int ShaderType { get; }
+ public ShaderStage Stage { get; }
public bool MrtEnable { get; }
@@ -52,10 +51,9 @@ namespace Ryujinx.Graphics.Shader
public int SassVersion { get; }
public bool DoesLoadOrStore { get; }
+ public bool DoesFp64 { get; }
- public bool DoesFp64 { get; }
-
- public int StreamOutMask{ get; }
+ public int StreamOutMask { get; }
public int ShaderLocalMemoryLowSize { get; }
@@ -67,7 +65,7 @@ namespace Ryujinx.Graphics.Shader
public int ShaderLocalMemoryCrsSize { get; }
- public int OutputTopology { get; }
+ public OutputTopology OutputTopology { get; }
public int MaxOutputVertexCount { get; }
@@ -78,69 +76,6 @@ namespace Ryujinx.Graphics.Shader
public bool OmapSampleMask { get; }
public bool OmapDepth { get; }
- public ShaderHeader(IGalMemory memory, ulong address)
- {
- int commonWord0 = memory.ReadInt32((long)address + 0);
- int commonWord1 = memory.ReadInt32((long)address + 4);
- int commonWord2 = memory.ReadInt32((long)address + 8);
- int commonWord3 = memory.ReadInt32((long)address + 12);
- int commonWord4 = memory.ReadInt32((long)address + 16);
-
- SphType = commonWord0.Extract(0, 5);
-
- Version = commonWord0.Extract(5, 5);
-
- ShaderType = commonWord0.Extract(10, 4);
-
- MrtEnable = commonWord0.Extract(14);
-
- KillsPixels = commonWord0.Extract(15);
-
- DoesGlobalStore = commonWord0.Extract(16);
-
- SassVersion = commonWord0.Extract(17, 4);
-
- DoesLoadOrStore = commonWord0.Extract(26);
-
- DoesFp64 = commonWord0.Extract(27);
-
- StreamOutMask = commonWord0.Extract(28, 4);
-
- ShaderLocalMemoryLowSize = commonWord1.Extract(0, 24);
-
- PerPatchAttributeCount = commonWord1.Extract(24, 8);
-
- ShaderLocalMemoryHighSize = commonWord2.Extract(0, 24);
-
- ThreadsPerInputPrimitive = commonWord2.Extract(24, 8);
-
- ShaderLocalMemoryCrsSize = commonWord3.Extract(0, 24);
-
- OutputTopology = commonWord3.Extract(24, 4);
-
- MaxOutputVertexCount = commonWord4.Extract(0, 12);
-
- StoreReqStart = commonWord4.Extract(12, 8);
- StoreReqEnd = commonWord4.Extract(24, 8);
-
- int type2OmapTarget = memory.ReadInt32((long)address + 72);
- int type2Omap = memory.ReadInt32((long)address + 76);
-
- OmapTargets = new OutputMapTarget[8];
-
- for (int offset = 0; offset < OmapTargets.Length * 4; offset += 4)
- {
- OmapTargets[offset >> 2] = new OutputMapTarget(
- type2OmapTarget.Extract(offset + 0),
- type2OmapTarget.Extract(offset + 1),
- type2OmapTarget.Extract(offset + 2),
- type2OmapTarget.Extract(offset + 3));
- }
-
- OmapSampleMask = type2Omap.Extract(0);
- OmapDepth = type2Omap.Extract(1);
- }
-
public int DepthRegister
{
get
@@ -162,5 +97,74 @@ namespace Ryujinx.Graphics.Shader
return count + 1;
}
}
+
+ public ShaderHeader(Span code)
+ {
+ Span header = MemoryMarshal.Cast(code);
+
+ int commonWord0 = header[0];
+ int commonWord1 = header[1];
+ int commonWord2 = header[2];
+ int commonWord3 = header[3];
+ int commonWord4 = header[4];
+
+ SphType = commonWord0.Extract(0, 5);
+ Version = commonWord0.Extract(5, 5);
+
+ Stage = (ShaderStage)commonWord0.Extract(10, 4);
+
+ // Invalid.
+ if (Stage == ShaderStage.Compute)
+ {
+ Stage = ShaderStage.Vertex;
+ }
+
+ MrtEnable = commonWord0.Extract(14);
+
+ KillsPixels = commonWord0.Extract(15);
+
+ DoesGlobalStore = commonWord0.Extract(16);
+
+ SassVersion = commonWord0.Extract(17, 4);
+
+ DoesLoadOrStore = commonWord0.Extract(26);
+ DoesFp64 = commonWord0.Extract(27);
+
+ StreamOutMask = commonWord0.Extract(28, 4);
+
+ ShaderLocalMemoryLowSize = commonWord1.Extract(0, 24);
+
+ PerPatchAttributeCount = commonWord1.Extract(24, 8);
+
+ ShaderLocalMemoryHighSize = commonWord2.Extract(0, 24);
+
+ ThreadsPerInputPrimitive = commonWord2.Extract(24, 8);
+
+ ShaderLocalMemoryCrsSize = commonWord3.Extract(0, 24);
+
+ OutputTopology = (OutputTopology)commonWord3.Extract(24, 4);
+
+ MaxOutputVertexCount = commonWord4.Extract(0, 12);
+
+ StoreReqStart = commonWord4.Extract(12, 8);
+ StoreReqEnd = commonWord4.Extract(24, 8);
+
+ int type2OmapTarget = header[18];
+ int type2Omap = header[19];
+
+ OmapTargets = new OutputMapTarget[8];
+
+ for (int offset = 0; offset < OmapTargets.Length * 4; offset += 4)
+ {
+ OmapTargets[offset >> 2] = new OutputMapTarget(
+ type2OmapTarget.Extract(offset + 0),
+ type2OmapTarget.Extract(offset + 1),
+ type2OmapTarget.Extract(offset + 2),
+ type2OmapTarget.Extract(offset + 3));
+ }
+
+ OmapSampleMask = type2Omap.Extract(0);
+ OmapDepth = type2Omap.Extract(1);
+ }
}
}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/ShaderProgram.cs b/Ryujinx.Graphics.Shader/ShaderProgram.cs
new file mode 100644
index 000000000..52c2d55b8
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/ShaderProgram.cs
@@ -0,0 +1,23 @@
+namespace Ryujinx.Graphics.Shader
+{
+ public class ShaderProgram
+ {
+ public ShaderProgramInfo Info { get; }
+
+ public ShaderStage Stage { get; }
+
+ public string Code { get; private set; }
+
+ internal ShaderProgram(ShaderProgramInfo info, ShaderStage stage, string code)
+ {
+ Info = info;
+ Stage = stage;
+ Code = code;
+ }
+
+ public void Replace(string name, string value)
+ {
+ Code = Code.Replace(name, value);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/ShaderProgramInfo.cs b/Ryujinx.Graphics.Shader/ShaderProgramInfo.cs
new file mode 100644
index 000000000..841e636dd
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/ShaderProgramInfo.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Collections.ObjectModel;
+
+namespace Ryujinx.Graphics.Shader
+{
+ public class ShaderProgramInfo
+ {
+ public ReadOnlyCollection CBuffers { get; }
+ public ReadOnlyCollection SBuffers { get; }
+ public ReadOnlyCollection Textures { get; }
+
+ public ReadOnlyCollection InterpolationQualifiers { get; }
+
+ public bool UsesInstanceId { get; }
+
+ internal ShaderProgramInfo(
+ BufferDescriptor[] cBuffers,
+ BufferDescriptor[] sBuffers,
+ TextureDescriptor[] textures,
+ InterpolationQualifier[] interpolationQualifiers,
+ bool usesInstanceId)
+ {
+ CBuffers = Array.AsReadOnly(cBuffers);
+ SBuffers = Array.AsReadOnly(sBuffers);
+ Textures = Array.AsReadOnly(textures);
+
+ InterpolationQualifiers = Array.AsReadOnly(interpolationQualifiers);
+
+ UsesInstanceId = usesInstanceId;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/ShaderStage.cs b/Ryujinx.Graphics.Shader/ShaderStage.cs
new file mode 100644
index 000000000..30b65348e
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/ShaderStage.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Shader
+{
+ public enum ShaderStage
+ {
+ Compute,
+ Vertex,
+ TessellationControl,
+ TessellationEvaluation,
+ Geometry,
+ Fragment
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstAssignment.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstAssignment.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstAssignment.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstAssignment.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstBlock.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstBlock.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstBlock.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstBlock.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstBlockType.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstBlockType.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstBlockType.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstBlockType.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstBlockVisitor.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstBlockVisitor.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstBlockVisitor.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstBlockVisitor.cs
diff --git a/Ryujinx.Graphics.Shader/StructuredIr/AstComment.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstComment.cs
new file mode 100644
index 000000000..dabe623fd
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/StructuredIr/AstComment.cs
@@ -0,0 +1,12 @@
+namespace Ryujinx.Graphics.Shader.StructuredIr
+{
+ class AstComment : AstNode
+ {
+ public string Comment { get; }
+
+ public AstComment(string comment)
+ {
+ Comment = comment;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstHelper.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstHelper.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstHelper.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstHelper.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstNode.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstNode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstNode.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstNode.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstOperand.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstOperand.cs
similarity index 88%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstOperand.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstOperand.cs
index 97ff3ca97..25b09636f 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/AstOperand.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/AstOperand.cs
@@ -12,6 +12,8 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
public VariableType VarType { get; set; }
+ public InterpolationQualifier Interpolation { get; }
+
public int Value { get; }
public int CbufSlot { get; }
@@ -27,7 +29,8 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
public AstOperand(Operand operand) : this()
{
- Type = operand.Type;
+ Type = operand.Type;
+ Interpolation = operand.Interpolation;
if (Type == OperandType.ConstantBuffer)
{
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstOperation.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstOperation.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstOperation.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstOperation.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstOptimizer.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
similarity index 75%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstOptimizer.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
index 0f5392b7d..a37e1a3e8 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/AstOptimizer.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/AstOptimizer.cs
@@ -1,4 +1,5 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using Ryujinx.Graphics.Shader.Translation;
using System.Collections.Generic;
using System.Linq;
@@ -8,28 +9,33 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
{
static class AstOptimizer
{
- public static void Optimize(StructuredProgramInfo info)
+ public static void Optimize(StructuredProgramContext context)
{
- AstBlock mainBlock = info.MainBlock;
+ AstBlock mainBlock = context.Info.MainBlock;
- AstBlockVisitor visitor = new AstBlockVisitor(mainBlock);
-
- foreach (IAstNode node in visitor.Visit())
+ // When debug mode is enabled, we disable expression propagation
+ // (this makes comparison with the disassembly easier).
+ if ((context.Config.Flags & TranslationFlags.DebugMode) == 0)
{
- if (node is AstAssignment assignment && assignment.Destination is AstOperand propVar)
+ AstBlockVisitor visitor = new AstBlockVisitor(mainBlock);
+
+ foreach (IAstNode node in visitor.Visit())
{
- bool isWorthPropagating = propVar.Uses.Count == 1 || IsWorthPropagating(assignment.Source);
-
- if (propVar.Defs.Count == 1 && isWorthPropagating)
+ if (node is AstAssignment assignment && assignment.Destination is AstOperand propVar)
{
- PropagateExpression(propVar, assignment.Source);
- }
+ bool isWorthPropagating = propVar.Uses.Count == 1 || IsWorthPropagating(assignment.Source);
- if (propVar.Type == OperandType.LocalVariable && propVar.Uses.Count == 0)
- {
- visitor.Block.Remove(assignment);
+ if (propVar.Defs.Count == 1 && isWorthPropagating)
+ {
+ PropagateExpression(propVar, assignment.Source);
+ }
- info.Locals.Remove(propVar);
+ if (propVar.Type == OperandType.LocalVariable && propVar.Uses.Count == 0)
+ {
+ visitor.Block.Remove(assignment);
+
+ context.Info.Locals.Remove(propVar);
+ }
}
}
}
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/AstTextureOperation.cs b/Ryujinx.Graphics.Shader/StructuredIr/AstTextureOperation.cs
similarity index 77%
rename from Ryujinx.Graphics/Shader/StructuredIr/AstTextureOperation.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/AstTextureOperation.cs
index e40f7b70e..c9bd57509 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/AstTextureOperation.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/AstTextureOperation.cs
@@ -4,20 +4,20 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
{
class AstTextureOperation : AstOperation
{
- public TextureType Type { get; }
- public TextureFlags Flags { get; }
+ public TextureTarget Target { get; }
+ public TextureFlags Flags { get; }
public int Handle { get; }
public AstTextureOperation(
Instruction inst,
- TextureType type,
+ TextureTarget target,
TextureFlags flags,
int handle,
int compMask,
params IAstNode[] sources) : base(inst, compMask, sources)
{
- Type = type;
+ Target = target;
Flags = flags;
Handle = handle;
}
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/GotoElimination.cs b/Ryujinx.Graphics.Shader/StructuredIr/GotoElimination.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/GotoElimination.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/GotoElimination.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/GotoStatement.cs b/Ryujinx.Graphics.Shader/StructuredIr/GotoStatement.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/GotoStatement.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/GotoStatement.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/IAstNode.cs b/Ryujinx.Graphics.Shader/StructuredIr/IAstNode.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/IAstNode.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/IAstNode.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/InstructionInfo.cs b/Ryujinx.Graphics.Shader/StructuredIr/InstructionInfo.cs
similarity index 90%
rename from Ryujinx.Graphics/Shader/StructuredIr/InstructionInfo.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/InstructionInfo.cs
index 46a61553b..cb08a213b 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/InstructionInfo.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/InstructionInfo.cs
@@ -24,6 +24,7 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
{
_infoTbl = new InstInfo[(int)Instruction.Count];
+ // Inst Destination type Source 1 type Source 2 type Source 3 type Source 4 type
Add(Instruction.Absolute, VariableType.Scalar, VariableType.Scalar);
Add(Instruction.Add, VariableType.Scalar, VariableType.Scalar, VariableType.Scalar);
Add(Instruction.BitfieldExtractS32, VariableType.S32, VariableType.S32, VariableType.S32, VariableType.S32);
@@ -59,7 +60,11 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
Add(Instruction.Floor, VariableType.F32, VariableType.F32);
Add(Instruction.FusedMultiplyAdd, VariableType.F32, VariableType.F32, VariableType.F32, VariableType.F32);
Add(Instruction.IsNan, VariableType.Bool, VariableType.F32);
+ Add(Instruction.LoadAttribute, VariableType.F32, VariableType.S32, VariableType.S32);
Add(Instruction.LoadConstant, VariableType.F32, VariableType.S32, VariableType.S32);
+ Add(Instruction.LoadGlobal, VariableType.F32, VariableType.S32, VariableType.S32);
+ Add(Instruction.LoadLocal, VariableType.F32, VariableType.S32);
+ Add(Instruction.LoadStorage, VariableType.F32, VariableType.S32, VariableType.S32);
Add(Instruction.LogarithmB2, VariableType.Scalar, VariableType.Scalar);
Add(Instruction.LogicalAnd, VariableType.Bool, VariableType.Bool, VariableType.Bool);
Add(Instruction.LogicalExclusiveOr, VariableType.Bool, VariableType.Bool, VariableType.Bool);
@@ -78,6 +83,9 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
Add(Instruction.ReciprocalSquareRoot, VariableType.Scalar, VariableType.Scalar);
Add(Instruction.Sine, VariableType.Scalar, VariableType.Scalar);
Add(Instruction.SquareRoot, VariableType.Scalar, VariableType.Scalar);
+ Add(Instruction.StoreGlobal, VariableType.None, VariableType.S32, VariableType.S32, VariableType.F32);
+ Add(Instruction.StoreLocal, VariableType.None, VariableType.S32, VariableType.F32);
+ Add(Instruction.StoreStorage, VariableType.None, VariableType.S32, VariableType.S32, VariableType.F32);
Add(Instruction.Subtract, VariableType.Scalar, VariableType.Scalar, VariableType.Scalar);
Add(Instruction.TextureSample, VariableType.F32);
Add(Instruction.TextureSize, VariableType.S32, VariableType.S32, VariableType.S32);
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/OperandInfo.cs b/Ryujinx.Graphics.Shader/StructuredIr/OperandInfo.cs
similarity index 92%
rename from Ryujinx.Graphics/Shader/StructuredIr/OperandInfo.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/OperandInfo.cs
index a3a8d1383..95c5731a9 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/OperandInfo.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/OperandInfo.cs
@@ -24,7 +24,6 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
case OperandType.Attribute: return VariableType.F32;
case OperandType.Constant: return VariableType.S32;
case OperandType.ConstantBuffer: return VariableType.F32;
- case OperandType.GlobalMemory: return VariableType.F32;
case OperandType.Undefined: return VariableType.S32;
}
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/PhiFunctions.cs b/Ryujinx.Graphics.Shader/StructuredIr/PhiFunctions.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/PhiFunctions.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/PhiFunctions.cs
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/StructuredProgram.cs b/Ryujinx.Graphics.Shader/StructuredIr/StructuredProgram.cs
similarity index 84%
rename from Ryujinx.Graphics/Shader/StructuredIr/StructuredProgram.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/StructuredProgram.cs
index 26faaf36f..dc8226213 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/StructuredProgram.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/StructuredProgram.cs
@@ -6,11 +6,11 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
{
static class StructuredProgram
{
- public static StructuredProgramInfo MakeStructuredProgram(BasicBlock[] blocks)
+ public static StructuredProgramInfo MakeStructuredProgram(BasicBlock[] blocks, ShaderConfig config)
{
PhiFunctions.Remove(blocks);
- StructuredProgramContext context = new StructuredProgramContext(blocks.Length);
+ StructuredProgramContext context = new StructuredProgramContext(blocks.Length, config);
for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
{
@@ -35,7 +35,7 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
GotoElimination.Eliminate(context.GetGotos());
- AstOptimizer.Optimize(context.Info);
+ AstOptimizer.Optimize(context);
return context.Info;
}
@@ -57,14 +57,25 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
if (inst == Instruction.LoadConstant)
{
- Operand ldcSource = operation.GetSource(0);
+ Operand slot = operation.GetSource(0);
- if (ldcSource.Type != OperandType.Constant)
+ if (slot.Type != OperandType.Constant)
{
- throw new InvalidOperationException("Found LDC with non-constant constant buffer slot.");
+ throw new InvalidOperationException("Found load with non-constant constant buffer slot.");
}
- context.Info.CBuffers.Add(ldcSource.Value);
+ context.Info.CBuffers.Add(slot.Value);
+ }
+ else if (inst == Instruction.LoadStorage)
+ {
+ Operand slot = operation.GetSource(0);
+
+ if (slot.Type != OperandType.Constant)
+ {
+ throw new InvalidOperationException("Found load or store with non-constant storage buffer slot.");
+ }
+
+ context.Info.SBuffers.Add(slot.Value);
}
AstAssignment assignment;
@@ -105,7 +116,7 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
{
AstTextureOperation astTexOp = new AstTextureOperation(
inst,
- texOp.Type,
+ texOp.Target,
texOp.Flags,
texOp.Handle,
componentMask,
@@ -128,8 +139,24 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
context.AddNode(assignment);
}
+ else if (operation.Inst == Instruction.Comment)
+ {
+ context.AddNode(new AstComment(((CommentNode)operation).Comment));
+ }
else
{
+ if (inst == Instruction.StoreStorage)
+ {
+ Operand slot = operation.GetSource(0);
+
+ if (slot.Type != OperandType.Constant)
+ {
+ throw new InvalidOperationException("Found load or store with non-constant storage buffer slot.");
+ }
+
+ context.Info.SBuffers.Add(slot.Value);
+ }
+
context.AddNode(new AstOperation(inst, sources));
}
}
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/StructuredProgramContext.cs b/Ryujinx.Graphics.Shader/StructuredIr/StructuredProgramContext.cs
similarity index 94%
rename from Ryujinx.Graphics/Shader/StructuredIr/StructuredProgramContext.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/StructuredProgramContext.cs
index 5d6ff8907..03ff88183 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/StructuredProgramContext.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/StructuredProgramContext.cs
@@ -1,4 +1,5 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using Ryujinx.Graphics.Shader.Translation;
using System.Collections.Generic;
using System.Linq;
@@ -24,7 +25,9 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
public StructuredProgramInfo Info { get; }
- public StructuredProgramContext(int blocksCount)
+ public ShaderConfig Config { get; }
+
+ public StructuredProgramContext(int blocksCount, ShaderConfig config)
{
_loopTails = new HashSet();
@@ -41,6 +44,8 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
_currEndIndex = blocksCount;
Info = new StructuredProgramInfo(_currBlock);
+
+ Config = config;
}
public void EnterBlock(BasicBlock block)
@@ -231,6 +236,12 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
if (TryGetUserAttributeIndex(operand, out int attrIndex))
{
Info.IAttributes.Add(attrIndex);
+
+ Info.InterpolationQualifiers[attrIndex] = operand.Interpolation;
+ }
+ else if (operand.Type == OperandType.Attribute && operand.Value == AttributeConsts.InstanceId)
+ {
+ Info.UsesInstanceId = true;
}
else if (operand.Type == OperandType.ConstantBuffer)
{
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/StructuredProgramInfo.cs b/Ryujinx.Graphics.Shader/StructuredIr/StructuredProgramInfo.cs
similarity index 73%
rename from Ryujinx.Graphics/Shader/StructuredIr/StructuredProgramInfo.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/StructuredProgramInfo.cs
index d368ef005..27fd1487a 100644
--- a/Ryujinx.Graphics/Shader/StructuredIr/StructuredProgramInfo.cs
+++ b/Ryujinx.Graphics.Shader/StructuredIr/StructuredProgramInfo.cs
@@ -9,10 +9,15 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
public HashSet Locals { get; }
public HashSet CBuffers { get; }
+ public HashSet SBuffers { get; }
public HashSet IAttributes { get; }
public HashSet OAttributes { get; }
+ public InterpolationQualifier[] InterpolationQualifiers { get; }
+
+ public bool UsesInstanceId { get; set; }
+
public HashSet Samplers { get; }
public StructuredProgramInfo(AstBlock mainBlock)
@@ -22,10 +27,13 @@ namespace Ryujinx.Graphics.Shader.StructuredIr
Locals = new HashSet();
CBuffers = new HashSet();
+ SBuffers = new HashSet();
IAttributes = new HashSet();
OAttributes = new HashSet();
+ InterpolationQualifiers = new InterpolationQualifier[32];
+
Samplers = new HashSet();
}
}
diff --git a/Ryujinx.Graphics/Shader/StructuredIr/VariableType.cs b/Ryujinx.Graphics.Shader/StructuredIr/VariableType.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/StructuredIr/VariableType.cs
rename to Ryujinx.Graphics.Shader/StructuredIr/VariableType.cs
diff --git a/Ryujinx.Graphics/Shader/TextureDescriptor.cs b/Ryujinx.Graphics.Shader/TextureDescriptor.cs
similarity index 68%
rename from Ryujinx.Graphics/Shader/TextureDescriptor.cs
rename to Ryujinx.Graphics.Shader/TextureDescriptor.cs
index 96f0f5b16..484fa1bcc 100644
--- a/Ryujinx.Graphics/Shader/TextureDescriptor.cs
+++ b/Ryujinx.Graphics.Shader/TextureDescriptor.cs
@@ -4,6 +4,8 @@ namespace Ryujinx.Graphics.Shader
{
public string Name { get; }
+ public TextureTarget Target { get; }
+
public int HandleIndex { get; }
public bool IsBindless { get; }
@@ -11,9 +13,10 @@ namespace Ryujinx.Graphics.Shader
public int CbufSlot { get; }
public int CbufOffset { get; }
- public TextureDescriptor(string name, int hIndex)
+ public TextureDescriptor(string name, TextureTarget target, int hIndex)
{
Name = name;
+ Target = target;
HandleIndex = hIndex;
IsBindless = false;
@@ -22,9 +25,10 @@ namespace Ryujinx.Graphics.Shader
CbufOffset = 0;
}
- public TextureDescriptor(string name, int cbufSlot, int cbufOffset)
+ public TextureDescriptor(string name, TextureTarget target, int cbufSlot, int cbufOffset)
{
Name = name;
+ Target = target;
HandleIndex = 0;
IsBindless = true;
diff --git a/Ryujinx.Graphics.Shader/TextureTarget.cs b/Ryujinx.Graphics.Shader/TextureTarget.cs
new file mode 100644
index 000000000..3642ef239
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/TextureTarget.cs
@@ -0,0 +1,35 @@
+using System;
+
+namespace Ryujinx.Graphics.Shader
+{
+ [Flags]
+ public enum TextureTarget
+ {
+ Texture1D,
+ Texture2D,
+ Texture3D,
+ TextureCube,
+
+ Mask = 0xff,
+
+ Array = 1 << 8,
+ Multisample = 1 << 9,
+ Shadow = 1 << 10
+ }
+
+ static class TextureTargetExtensions
+ {
+ public static int GetDimensions(this TextureTarget type)
+ {
+ switch (type & TextureTarget.Mask)
+ {
+ case TextureTarget.Texture1D: return 1;
+ case TextureTarget.Texture2D: return 2;
+ case TextureTarget.Texture3D: return 3;
+ case TextureTarget.TextureCube: return 3;
+ }
+
+ throw new ArgumentException($"Invalid texture type \"{type}\".");
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Translation/AttributeConsts.cs b/Ryujinx.Graphics.Shader/Translation/AttributeConsts.cs
similarity index 82%
rename from Ryujinx.Graphics/Shader/Translation/AttributeConsts.cs
rename to Ryujinx.Graphics.Shader/Translation/AttributeConsts.cs
index f21a6252a..08aac1cad 100644
--- a/Ryujinx.Graphics/Shader/Translation/AttributeConsts.cs
+++ b/Ryujinx.Graphics.Shader/Translation/AttributeConsts.cs
@@ -1,4 +1,4 @@
-namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
+namespace Ryujinx.Graphics.Shader.Translation
{
static class AttributeConsts
{
@@ -34,5 +34,13 @@ namespace Ryujinx.Graphics.Shader.IntermediateRepresentation
public const int FragmentOutputDepth = 0x1000000;
public const int FragmentOutputColorBase = 0x1000010;
public const int FragmentOutputColorEnd = FragmentOutputColorBase + 8 * 16;
+
+ public const int ThreadIdX = 0x2000000;
+ public const int ThreadIdY = 0x2000004;
+ public const int ThreadIdZ = 0x2000008;
+
+ public const int CtaIdX = 0x2000010;
+ public const int CtaIdY = 0x2000014;
+ public const int CtaIdZ = 0x2000018;
}
}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Translation/ControlFlowGraph.cs b/Ryujinx.Graphics.Shader/Translation/ControlFlowGraph.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Translation/ControlFlowGraph.cs
rename to Ryujinx.Graphics.Shader/Translation/ControlFlowGraph.cs
diff --git a/Ryujinx.Graphics/Shader/Translation/Dominance.cs b/Ryujinx.Graphics.Shader/Translation/Dominance.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Translation/Dominance.cs
rename to Ryujinx.Graphics.Shader/Translation/Dominance.cs
diff --git a/Ryujinx.Graphics/Shader/Translation/EmitterContext.cs b/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs
similarity index 90%
rename from Ryujinx.Graphics/Shader/Translation/EmitterContext.cs
rename to Ryujinx.Graphics.Shader/Translation/EmitterContext.cs
index 6c2bf6e47..3995d4306 100644
--- a/Ryujinx.Graphics/Shader/Translation/EmitterContext.cs
+++ b/Ryujinx.Graphics.Shader/Translation/EmitterContext.cs
@@ -1,4 +1,3 @@
-using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Shader.Decoders;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using System.Collections.Generic;
@@ -12,7 +11,7 @@ namespace Ryujinx.Graphics.Shader.Translation
public Block CurrBlock { get; set; }
public OpCode CurrOp { get; set; }
- private GalShaderType _shaderType;
+ private ShaderStage _stage;
private ShaderHeader _header;
@@ -20,10 +19,10 @@ namespace Ryujinx.Graphics.Shader.Translation
private Dictionary _labels;
- public EmitterContext(GalShaderType shaderType, ShaderHeader header)
+ public EmitterContext(ShaderStage stage, ShaderHeader header)
{
- _shaderType = shaderType;
- _header = header;
+ _stage = stage;
+ _header = header;
_operations = new List();
@@ -63,7 +62,7 @@ namespace Ryujinx.Graphics.Shader.Translation
public void PrepareForReturn()
{
- if (_shaderType == GalShaderType.Fragment)
+ if (_stage == ShaderStage.Fragment)
{
if (_header.OmapDepth)
{
diff --git a/Ryujinx.Graphics/Shader/Translation/EmitterContextInsts.cs b/Ryujinx.Graphics.Shader/Translation/EmitterContextInsts.cs
similarity index 94%
rename from Ryujinx.Graphics/Shader/Translation/EmitterContextInsts.cs
rename to Ryujinx.Graphics.Shader/Translation/EmitterContextInsts.cs
index 604aa67d3..f0bede186 100644
--- a/Ryujinx.Graphics/Shader/Translation/EmitterContextInsts.cs
+++ b/Ryujinx.Graphics.Shader/Translation/EmitterContextInsts.cs
@@ -366,11 +366,26 @@ namespace Ryujinx.Graphics.Shader.Translation
return context.Add(Instruction.IsNan, Local(), a);
}
+ public static Operand LoadAttribute(this EmitterContext context, Operand a, Operand b)
+ {
+ return context.Add(Instruction.LoadAttribute, Local(), a, b);
+ }
+
public static Operand LoadConstant(this EmitterContext context, Operand a, Operand b)
{
return context.Add(Instruction.LoadConstant, Local(), a, b);
}
+ public static Operand LoadGlobal(this EmitterContext context, Operand a)
+ {
+ return context.Add(Instruction.LoadGlobal, Local(), a);
+ }
+
+ public static Operand LoadLocal(this EmitterContext context, Operand a)
+ {
+ return context.Add(Instruction.LoadLocal, Local(), a);
+ }
+
public static Operand PackHalf2x16(this EmitterContext context, Operand a, Operand b)
{
return context.Add(Instruction.PackHalf2x16, Local(), a, b);
@@ -398,6 +413,16 @@ namespace Ryujinx.Graphics.Shader.Translation
return context.Add(Instruction.ShiftRightU32, Local(), a, b);
}
+ public static Operand StoreGlobal(this EmitterContext context, Operand a, Operand b)
+ {
+ return context.Add(Instruction.StoreGlobal, null, a, b);
+ }
+
+ public static Operand StoreLocal(this EmitterContext context, Operand a, Operand b)
+ {
+ return context.Add(Instruction.StoreLocal, null, a, b);
+ }
+
public static Operand UnpackHalf2x16High(this EmitterContext context, Operand a)
{
return UnpackHalf2x16(context, a, 1);
diff --git a/Ryujinx.Graphics/Shader/Translation/Optimizations/BranchElimination.cs b/Ryujinx.Graphics.Shader/Translation/Optimizations/BranchElimination.cs
similarity index 96%
rename from Ryujinx.Graphics/Shader/Translation/Optimizations/BranchElimination.cs
rename to Ryujinx.Graphics.Shader/Translation/Optimizations/BranchElimination.cs
index 070f07a47..c87d14748 100644
--- a/Ryujinx.Graphics/Shader/Translation/Optimizations/BranchElimination.cs
+++ b/Ryujinx.Graphics.Shader/Translation/Optimizations/BranchElimination.cs
@@ -5,7 +5,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
{
static class BranchElimination
{
- public static bool Eliminate(BasicBlock block)
+ public static bool RunPass(BasicBlock block)
{
if (block.HasBranch && IsRedundantBranch((Operation)block.GetLastOp(), Next(block)))
{
diff --git a/Ryujinx.Graphics/Shader/Translation/Optimizations/ConstantFolding.cs b/Ryujinx.Graphics.Shader/Translation/Optimizations/ConstantFolding.cs
similarity index 99%
rename from Ryujinx.Graphics/Shader/Translation/Optimizations/ConstantFolding.cs
rename to Ryujinx.Graphics.Shader/Translation/Optimizations/ConstantFolding.cs
index a2e05ef12..d64579b71 100644
--- a/Ryujinx.Graphics/Shader/Translation/Optimizations/ConstantFolding.cs
+++ b/Ryujinx.Graphics.Shader/Translation/Optimizations/ConstantFolding.cs
@@ -8,7 +8,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
{
static class ConstantFolding
{
- public static void Fold(Operation operation)
+ public static void RunPass(Operation operation)
{
if (!AreAllSourcesConstant(operation))
{
diff --git a/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs b/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs
new file mode 100644
index 000000000..06db2a804
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs
@@ -0,0 +1,145 @@
+using Ryujinx.Graphics.Shader.IntermediateRepresentation;
+using System.Collections.Generic;
+
+using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
+
+namespace Ryujinx.Graphics.Shader.Translation.Optimizations
+{
+ static class GlobalToStorage
+ {
+ private const int StorageDescsBaseOffset = 0x44; // In words.
+
+ private const int UbeStorageDescsBaseOffset = 0x84; // In words.
+ private const int UbeStorageMaxCount = 14;
+
+ private const int StorageDescSize = 4; // In words.
+ private const int StorageMaxCount = 16;
+
+ private const int StorageDescsSize = StorageDescSize * StorageMaxCount;
+
+ public static void RunPass(BasicBlock block, ShaderStage stage)
+ {
+ int sbStart = GetStorageBaseCbOffset(stage);
+
+ int sbEnd = sbStart + StorageDescsSize;
+
+ // This one is only used on compute shaders.
+ // Compute shaders uses two separate sets of storage.
+ int ubeSbStart = UbeStorageDescsBaseOffset;
+ int ubeSbEnd = UbeStorageDescsBaseOffset + StorageDescSize * UbeStorageMaxCount;
+
+ for (LinkedListNode node = block.Operations.First; node != null; node = node.Next)
+ {
+ if (!(node.Value is Operation operation))
+ {
+ continue;
+ }
+
+ if (operation.Inst == Instruction.LoadGlobal ||
+ operation.Inst == Instruction.StoreGlobal)
+ {
+ Operand source = operation.GetSource(0);
+
+ if (source.AsgOp is Operation asgOperation)
+ {
+ int storageIndex = SearchForStorageBase(asgOperation, sbStart, sbEnd);
+
+ /*if (storageIndex < 0 && stage == ShaderStage.Compute)
+ {
+ storageIndex = SearchForStorageBase(asgOperation, ubeSbStart, ubeSbEnd);
+ }*/
+
+ if (storageIndex >= 0)
+ {
+ node = ReplaceGlobalWithStorage(node, storageIndex);
+ }
+ }
+ }
+ }
+ }
+
+ private static LinkedListNode ReplaceGlobalWithStorage(LinkedListNode node, int storageIndex)
+ {
+ Operation operation = (Operation)node.Value;
+
+ Operation storageOp;
+
+ if (operation.Inst == Instruction.LoadGlobal)
+ {
+ Operand source = operation.GetSource(0);
+
+ storageOp = new Operation(Instruction.LoadStorage, operation.Dest, Const(storageIndex), source);
+ }
+ else
+ {
+ Operand src1 = operation.GetSource(0);
+ Operand src2 = operation.GetSource(1);
+
+ storageOp = new Operation(Instruction.StoreStorage, null, Const(storageIndex), src1, src2);
+ }
+
+ for (int index = 0; index < operation.SourcesCount; index++)
+ {
+ operation.SetSource(index, null);
+ }
+
+ LinkedListNode oldNode = node;
+
+ node = node.List.AddAfter(node, storageOp);
+
+ node.List.Remove(oldNode);
+
+ return node;
+ }
+
+ private static int SearchForStorageBase(Operation operation, int sbStart, int sbEnd)
+ {
+ Queue assignments = new Queue();
+
+ assignments.Enqueue(operation);
+
+ while (assignments.TryDequeue(out operation))
+ {
+ for (int index = 0; index < operation.SourcesCount; index++)
+ {
+ Operand source = operation.GetSource(index);
+
+ if (source.Type == OperandType.ConstantBuffer)
+ {
+ int slot = source.GetCbufSlot();
+ int offset = source.GetCbufOffset();
+
+ if (slot == 0 && offset >= sbStart && offset < sbEnd)
+ {
+ int storageIndex = (offset - sbStart) / StorageDescSize;
+
+ return storageIndex;
+ }
+ }
+
+ if (source.AsgOp is Operation asgOperation)
+ {
+ assignments.Enqueue(asgOperation);
+ }
+ }
+ }
+
+ return -1;
+ }
+
+ private static int GetStorageBaseCbOffset(ShaderStage stage)
+ {
+ switch (stage)
+ {
+ case ShaderStage.Compute: return StorageDescsBaseOffset + 2 * StorageDescsSize;
+ case ShaderStage.Vertex: return StorageDescsBaseOffset;
+ case ShaderStage.TessellationControl: return StorageDescsBaseOffset + 1 * StorageDescsSize;
+ case ShaderStage.TessellationEvaluation: return StorageDescsBaseOffset + 2 * StorageDescsSize;
+ case ShaderStage.Geometry: return StorageDescsBaseOffset + 3 * StorageDescsSize;
+ case ShaderStage.Fragment: return StorageDescsBaseOffset + 4 * StorageDescsSize;
+ }
+
+ return 0;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Translation/Optimizations/HalfConversion.cs b/Ryujinx.Graphics.Shader/Translation/Optimizations/HalfConversion.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Translation/Optimizations/HalfConversion.cs
rename to Ryujinx.Graphics.Shader/Translation/Optimizations/HalfConversion.cs
diff --git a/Ryujinx.Graphics/Shader/Translation/Optimizations/Optimizer.cs b/Ryujinx.Graphics.Shader/Translation/Optimizations/Optimizer.cs
similarity index 92%
rename from Ryujinx.Graphics/Shader/Translation/Optimizations/Optimizer.cs
rename to Ryujinx.Graphics.Shader/Translation/Optimizations/Optimizer.cs
index 8cce0e74e..d5e57546a 100644
--- a/Ryujinx.Graphics/Shader/Translation/Optimizations/Optimizer.cs
+++ b/Ryujinx.Graphics.Shader/Translation/Optimizations/Optimizer.cs
@@ -6,8 +6,13 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
{
static class Optimizer
{
- public static void Optimize(BasicBlock[] blocks)
+ public static void Optimize(BasicBlock[] blocks, ShaderStage stage)
{
+ for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
+ {
+ GlobalToStorage.RunPass(blocks[blkIndex], stage);
+ }
+
bool modified;
do
@@ -40,9 +45,9 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
continue;
}
- ConstantFolding.Fold(operation);
+ ConstantFolding.RunPass(operation);
- Simplification.Simplify(operation);
+ Simplification.RunPass(operation);
if (DestIsLocalVar(operation))
{
@@ -68,7 +73,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
node = nextNode;
}
- if (BranchElimination.Eliminate(block))
+ if (BranchElimination.RunPass(block))
{
RemoveNode(block, block.Operations.Last);
diff --git a/Ryujinx.Graphics/Shader/Translation/Optimizations/Simplification.cs b/Ryujinx.Graphics.Shader/Translation/Optimizations/Simplification.cs
similarity index 98%
rename from Ryujinx.Graphics/Shader/Translation/Optimizations/Simplification.cs
rename to Ryujinx.Graphics.Shader/Translation/Optimizations/Simplification.cs
index d6366dfe0..8d05f99af 100644
--- a/Ryujinx.Graphics/Shader/Translation/Optimizations/Simplification.cs
+++ b/Ryujinx.Graphics.Shader/Translation/Optimizations/Simplification.cs
@@ -8,7 +8,7 @@ namespace Ryujinx.Graphics.Shader.Translation.Optimizations
{
private const int AllOnes = ~0;
- public static void Simplify(Operation operation)
+ public static void RunPass(Operation operation)
{
switch (operation.Inst)
{
diff --git a/Ryujinx.Graphics/Shader/Translation/Ssa.cs b/Ryujinx.Graphics.Shader/Translation/Ssa.cs
similarity index 100%
rename from Ryujinx.Graphics/Shader/Translation/Ssa.cs
rename to Ryujinx.Graphics.Shader/Translation/Ssa.cs
diff --git a/Ryujinx.Graphics.Shader/Translation/TranslationConfig.cs b/Ryujinx.Graphics.Shader/Translation/TranslationConfig.cs
new file mode 100644
index 000000000..e5fa6d14d
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Translation/TranslationConfig.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Ryujinx.Graphics.Shader.Translation
+{
+ public struct TranslationConfig
+ {
+ public int MaxCBufferSize { get; }
+
+ public int Version { get; }
+
+ public TranslationFlags Flags { get; }
+
+ public TranslationConfig(int maxCBufferSize, int version, TranslationFlags flags)
+ {
+ if (maxCBufferSize <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(maxCBufferSize));
+ }
+
+ MaxCBufferSize = maxCBufferSize;
+ Version = version;
+ Flags = flags;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Shader/Translation/TranslationFlags.cs b/Ryujinx.Graphics.Shader/Translation/TranslationFlags.cs
new file mode 100644
index 000000000..99b6107a9
--- /dev/null
+++ b/Ryujinx.Graphics.Shader/Translation/TranslationFlags.cs
@@ -0,0 +1,11 @@
+namespace Ryujinx.Graphics.Shader.Translation
+{
+ public enum TranslationFlags
+ {
+ None = 0,
+
+ Compute = 1 << 0,
+ DebugMode = 1 << 1,
+ Unspecialized = 1 << 2
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Shader/Translation/Translator.cs b/Ryujinx.Graphics.Shader/Translation/Translator.cs
similarity index 64%
rename from Ryujinx.Graphics/Shader/Translation/Translator.cs
rename to Ryujinx.Graphics.Shader/Translation/Translator.cs
index fcebe913e..4838b1e29 100644
--- a/Ryujinx.Graphics/Shader/Translation/Translator.cs
+++ b/Ryujinx.Graphics.Shader/Translation/Translator.cs
@@ -1,10 +1,10 @@
-using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Shader.CodeGen.Glsl;
using Ryujinx.Graphics.Shader.Decoders;
using Ryujinx.Graphics.Shader.Instructions;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using Ryujinx.Graphics.Shader.Translation.Optimizations;
+using System;
using System.Collections.Generic;
using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
@@ -13,27 +13,56 @@ namespace Ryujinx.Graphics.Shader.Translation
{
public static class Translator
{
- public static ShaderProgram Translate(IGalMemory memory, ulong address, ShaderConfig config)
+ private const int HeaderSize = 0x50;
+
+ public static ShaderProgram Translate(Span code, TranslationConfig translationConfig)
{
- return Translate(memory, address, 0, config);
+ return Translate(code, Span.Empty, translationConfig);
}
- public static ShaderProgram Translate(
- IGalMemory memory,
- ulong address,
- ulong addressB,
- ShaderConfig config)
+ public static ShaderProgram Translate(Span code, Span code2, TranslationConfig translationConfig)
{
- Operation[] shaderOps = DecodeShader(memory, address, config.Type);
+ bool compute = (translationConfig.Flags & TranslationFlags.Compute) != 0;
+ bool debugMode = (translationConfig.Flags & TranslationFlags.DebugMode) != 0;
- if (addressB != 0)
+ Operation[] shaderOps = DecodeShader(code, compute, debugMode, out ShaderHeader header);
+
+ if (code2 != Span.Empty)
{
// Dual vertex shader.
- Operation[] shaderOpsB = DecodeShader(memory, addressB, config.Type);
+ Operation[] shaderOpsB = DecodeShader(code2, compute, debugMode, out header);
shaderOps = Combine(shaderOps, shaderOpsB);
}
+ ShaderStage stage;
+
+ if (compute)
+ {
+ stage = ShaderStage.Compute;
+ }
+ else
+ {
+ stage = header.Stage;
+ }
+
+ int maxOutputVertexCount = 0;
+
+ OutputTopology outputTopology = OutputTopology.LineStrip;
+
+ if (!compute)
+ {
+ maxOutputVertexCount = header.MaxOutputVertexCount;
+ outputTopology = header.OutputTopology;
+ }
+
+ ShaderConfig config = new ShaderConfig(
+ stage,
+ translationConfig.Flags,
+ translationConfig.MaxCBufferSize,
+ maxOutputVertexCount,
+ outputTopology);
+
BasicBlock[] irBlocks = ControlFlowGraph.MakeCfg(shaderOps);
Dominance.FindDominators(irBlocks[0], irBlocks.Length);
@@ -42,26 +71,57 @@ namespace Ryujinx.Graphics.Shader.Translation
Ssa.Rename(irBlocks);
- Optimizer.Optimize(irBlocks);
+ Optimizer.Optimize(irBlocks, stage);
- StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram(irBlocks);
+ StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram(irBlocks, config);
GlslProgram program = GlslGenerator.Generate(sInfo, config);
ShaderProgramInfo spInfo = new ShaderProgramInfo(
program.CBufferDescriptors,
- program.TextureDescriptors);
+ program.SBufferDescriptors,
+ program.TextureDescriptors,
+ sInfo.InterpolationQualifiers,
+ sInfo.UsesInstanceId);
- return new ShaderProgram(spInfo, program.Code);
+ string glslCode = program.Code;
+
+ if (translationConfig.Version != 0)
+ {
+ glslCode = "// " + translationConfig.Version + Environment.NewLine + glslCode;
+ }
+
+ return new ShaderProgram(spInfo, stage, glslCode);
}
- private static Operation[] DecodeShader(IGalMemory memory, ulong address, GalShaderType shaderType)
+ private static Operation[] DecodeShader(Span code, bool compute, bool debugMode, out ShaderHeader header)
{
- ShaderHeader header = new ShaderHeader(memory, address);
+ Block[] cfg;
- Block[] cfg = Decoder.Decode(memory, address);
+ EmitterContext context;
- EmitterContext context = new EmitterContext(shaderType, header);
+ ulong headerSize;
+
+ if (compute)
+ {
+ header = null;
+
+ cfg = Decoder.Decode(code, 0);
+
+ context = new EmitterContext(ShaderStage.Compute, header);
+
+ headerSize = 0;
+ }
+ else
+ {
+ header = new ShaderHeader(code);
+
+ cfg = Decoder.Decode(code, HeaderSize);
+
+ context = new EmitterContext(header.Stage, header);
+
+ headerSize = HeaderSize;
+ }
for (int blkIndex = 0; blkIndex < cfg.Length; blkIndex++)
{
@@ -75,6 +135,24 @@ namespace Ryujinx.Graphics.Shader.Translation
{
OpCode op = block.OpCodes[opIndex];
+ if (debugMode)
+ {
+ string instName;
+
+ if (op.Emitter != null)
+ {
+ instName = op.Emitter.Method.Name;
+ }
+ else
+ {
+ instName = "???";
+ }
+
+ string dbgComment = $"0x{(op.Address - headerSize):X6}: 0x{op.RawOpCode:X16} {instName}";
+
+ context.Add(new CommentNode(dbgComment));
+ }
+
if (op.NeverExecute)
{
continue;
@@ -122,7 +200,10 @@ namespace Ryujinx.Graphics.Shader.Translation
context.CurrOp = op;
- op.Emitter(context);
+ if (op.Emitter != null)
+ {
+ op.Emitter(context);
+ }
if (predSkipLbl != null)
{
diff --git a/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs b/Ryujinx.Graphics.Texture/Astc/AstcDecoder.cs
similarity index 95%
rename from Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs
rename to Ryujinx.Graphics.Texture/Astc/AstcDecoder.cs
index 3e68be7d8..c192a6a9e 100644
--- a/Ryujinx.Graphics/Graphics3d/Texture/AstcDecoder.cs
+++ b/Ryujinx.Graphics.Texture/Astc/AstcDecoder.cs
@@ -4,13 +4,8 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
-namespace Ryujinx.Graphics.Texture
+namespace Ryujinx.Graphics.Texture.Astc
{
- 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
{
@@ -52,54 +47,54 @@ namespace Ryujinx.Graphics.Texture
}
}
- public static byte[] DecodeToRgba8888(
- byte[] inputBuffer,
- int blockX,
- int blockY,
- int blockZ,
- int x,
- int y,
- int z)
+ public static Span DecodeToRgba8(
+ Span data,
+ int blockWidth,
+ int blockHeight,
+ int blockDepth,
+ int width,
+ int height,
+ int depth)
{
- using (MemoryStream inputStream = new MemoryStream(inputBuffer))
+ using (MemoryStream inputStream = new MemoryStream(data.ToArray()))
{
BinaryReader binReader = new BinaryReader(inputStream);
- if (blockX > 12 || blockY > 12)
+ if (blockWidth > 12 || blockHeight > 12)
{
- throw new AstcDecoderException("Block size unsupported!");
+ throw new AstcDecoderException("Invalid block size.");
}
- if (blockZ != 1 || z != 1)
+ if (blockDepth != 1 || depth != 1)
{
- // TODO: Support 3D textures?
- throw new AstcDecoderException("3D compressed textures unsupported!");
+ // TODO: Support 3D textures.
+ throw new NotImplementedException("3D compressed textures are not unsupported.");
}
using (MemoryStream outputStream = new MemoryStream())
{
int blockIndex = 0;
- for (int j = 0; j < y; j += blockY)
+ for (int j = 0; j < height; j += blockHeight)
{
- for (int i = 0; i < x; i += blockX)
+ for (int i = 0; i < width; i += blockWidth)
{
int[] decompressedData = new int[144];
- DecompressBlock(binReader.ReadBytes(0x10), decompressedData, blockX, blockY);
+ DecompressBlock(binReader.ReadBytes(0x10), decompressedData, blockWidth, blockHeight);
- int decompressedWidth = Math.Min(blockX, x - i);
- int decompressedHeight = Math.Min(blockY, y - j);
- int baseOffsets = (j * x + i) * 4;
+ int decompressedWidth = Math.Min(blockWidth, width - i);
+ int decompressedHeight = Math.Min(blockHeight, height - j);
+ int baseOffsets = (j * width + i) * 4;
for (int jj = 0; jj < decompressedHeight; jj++)
{
- outputStream.Seek(baseOffsets + jj * x * 4, SeekOrigin.Begin);
+ outputStream.Seek(baseOffsets + jj * width * 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);
+ outputStream.Write(outputBuffer, jj * blockWidth * 4, decompressedWidth * 4);
}
blockIndex++;
@@ -112,9 +107,9 @@ namespace Ryujinx.Graphics.Texture
}
public static bool DecompressBlock(
- byte[] inputBuffer,
- int[] outputBuffer,
- int blockWidth,
+ byte[] inputBuffer,
+ int[] outputBuffer,
+ int blockWidth,
int blockHeight)
{
BitArrayStream bitStream = new BitArrayStream(new BitArray(inputBuffer));
@@ -122,7 +117,7 @@ namespace Ryujinx.Graphics.Texture
if (texelParams.Error)
{
- throw new AstcDecoderException("Invalid block mode");
+ throw new AstcDecoderException("Invalid block mode.");
}
if (texelParams.VoidExtentLdr)
@@ -134,17 +129,17 @@ namespace Ryujinx.Graphics.Texture
if (texelParams.VoidExtentHdr)
{
- throw new AstcDecoderException("HDR void extent blocks are unsupported!");
+ throw new AstcDecoderException("HDR void extent blocks are not supported.");
}
if (texelParams.Width > blockWidth)
{
- throw new AstcDecoderException("Texel weight grid width should be smaller than block width");
+ 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");
+ throw new AstcDecoderException("Texel weight grid height should be smaller than block height.");
}
// Read num partitions
@@ -153,7 +148,7 @@ namespace Ryujinx.Graphics.Texture
if (numberPartitions == 4 && texelParams.DualPlane)
{
- throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks");
+ throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks.");
}
// Based on the number of partitions, read the color endpoint mode for
@@ -316,7 +311,7 @@ namespace Ryujinx.Graphics.Texture
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];
@@ -456,10 +451,10 @@ namespace Ryujinx.Graphics.Texture
}
static void UnquantizeTexelWeights(
- int[][] outputBuffer,
- List weights,
- TexelWeightParams texelParams,
- int blockWidth,
+ int[][] outputBuffer,
+ List weights,
+ TexelWeightParams texelParams,
+ int blockWidth,
int blockHeight)
{
int weightIndices = 0;
@@ -530,12 +525,12 @@ namespace Ryujinx.Graphics.Texture
{
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];
@@ -603,11 +598,11 @@ namespace Ryujinx.Graphics.Texture
}
default:
- throw new AstcDecoderException("Invalid trit encoding for texel weight");
+ throw new AstcDecoderException("Invalid trit encoding for texel weight.");
}
break;
- }
+ }
case IntegerEncoded.EIntegerEncoding.Quint:
{
@@ -639,13 +634,13 @@ namespace Ryujinx.Graphics.Texture
break;
}
-
+
default:
- throw new AstcDecoderException("Invalid quint encoding for texel weight");
+ throw new AstcDecoderException("Invalid quint encoding for texel weight.");
}
break;
- }
+ }
}
if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && bitLength > 0)
@@ -698,9 +693,9 @@ namespace Ryujinx.Graphics.Texture
}
static void ComputeEndpoints(
- AstcPixel[] endPoints,
- int[] colorValues,
- uint colorEndpointMode,
+ AstcPixel[] endPoints,
+ int[] colorValues,
+ uint colorEndpointMode,
ref int colorValuesPosition)
{
switch (colorEndpointMode)
@@ -714,7 +709,7 @@ namespace Ryujinx.Graphics.Texture
break;
}
-
+
case 1:
{
@@ -867,10 +862,10 @@ namespace Ryujinx.Graphics.Texture
}
static void DecodeColorValues(
- int[] outputValues,
- byte[] inputData,
- uint[] modes,
- int numberPartitions,
+ int[] outputValues,
+ byte[] inputData,
+ uint[] modes,
+ int numberPartitions,
int numberBitsForColorData)
{
// First figure out how many color values we have
@@ -950,7 +945,7 @@ namespace Ryujinx.Graphics.Texture
break;
}
-
+
case 2:
{
c = 93;
@@ -970,7 +965,7 @@ namespace Ryujinx.Graphics.Texture
break;
}
-
+
case 4:
{
@@ -1003,12 +998,12 @@ namespace Ryujinx.Graphics.Texture
}
default:
- throw new AstcDecoderException("Unsupported trit encoding for color values!");
+ throw new AstcDecoderException("Unsupported trit encoding for color values.");
}
break;
}
-
+
case IntegerEncoded.EIntegerEncoding.Quint:
{
d = intEncoded.QuintValue;
@@ -1021,7 +1016,7 @@ namespace Ryujinx.Graphics.Texture
break;
}
-
+
case 2:
{
c = 54;
@@ -1031,7 +1026,7 @@ namespace Ryujinx.Graphics.Texture
break;
}
-
+
case 3:
{
c = 26;
@@ -1051,7 +1046,7 @@ namespace Ryujinx.Graphics.Texture
break;
}
-
+
case 5:
{
c = 6;
@@ -1063,10 +1058,10 @@ namespace Ryujinx.Graphics.Texture
}
default:
- throw new AstcDecoderException("Unsupported quint encoding for color values!");
+ throw new AstcDecoderException("Unsupported quint encoding for color values.");
}
break;
- }
+ }
}
if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits)
diff --git a/Ryujinx.Graphics.Texture/Astc/AstcDecoderException.cs b/Ryujinx.Graphics.Texture/Astc/AstcDecoderException.cs
new file mode 100644
index 000000000..fdc482671
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/Astc/AstcDecoderException.cs
@@ -0,0 +1,9 @@
+using System;
+
+namespace Ryujinx.Graphics.Texture.Astc
+{
+ public class AstcDecoderException : Exception
+ {
+ public AstcDecoderException(string exMsg) : base(exMsg) { }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs b/Ryujinx.Graphics.Texture/Astc/AstcPixel.cs
similarity index 98%
rename from Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs
rename to Ryujinx.Graphics.Texture/Astc/AstcPixel.cs
index 2f73c62b0..7d1278782 100644
--- a/Ryujinx.Graphics/Graphics3d/Texture/AstcPixel.cs
+++ b/Ryujinx.Graphics.Texture/Astc/AstcPixel.cs
@@ -1,7 +1,7 @@
using System;
using System.Diagnostics;
-namespace Ryujinx.Graphics.Texture
+namespace Ryujinx.Graphics.Texture.Astc
{
class AstcPixel
{
diff --git a/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs b/Ryujinx.Graphics.Texture/Astc/BitArrayStream.cs
similarity index 98%
rename from Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs
rename to Ryujinx.Graphics.Texture/Astc/BitArrayStream.cs
index 24069d722..3c472a3c1 100644
--- a/Ryujinx.Graphics/Graphics3d/Texture/BitArrayStream.cs
+++ b/Ryujinx.Graphics.Texture/Astc/BitArrayStream.cs
@@ -1,7 +1,7 @@
using System;
using System.Collections;
-namespace Ryujinx.Graphics.Texture
+namespace Ryujinx.Graphics.Texture.Astc
{
public class BitArrayStream
{
diff --git a/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs b/Ryujinx.Graphics.Texture/Astc/IntegerEncoded.cs
similarity index 95%
rename from Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs
rename to Ryujinx.Graphics.Texture/Astc/IntegerEncoded.cs
index e6d67058e..5aa610e74 100644
--- a/Ryujinx.Graphics/Graphics3d/Texture/IntegerEncoded.cs
+++ b/Ryujinx.Graphics.Texture/Astc/IntegerEncoded.cs
@@ -1,7 +1,7 @@
using System.Collections;
using System.Collections.Generic;
-namespace Ryujinx.Graphics.Texture
+namespace Ryujinx.Graphics.Texture.Astc
{
public struct IntegerEncoded
{
@@ -84,8 +84,8 @@ namespace Ryujinx.Graphics.Texture
}
public static void DecodeTritBlock(
- BitArrayStream bitStream,
- List listIntegerEncoded,
+ BitArrayStream bitStream,
+ List listIntegerEncoded,
int numberBitsPerValue)
{
// Implement the algorithm in section C.2.12
@@ -161,8 +161,8 @@ namespace Ryujinx.Graphics.Texture
}
public static void DecodeQuintBlock(
- BitArrayStream bitStream,
- List listIntegerEncoded,
+ BitArrayStream bitStream,
+ List listIntegerEncoded,
int numberBitsPerValue)
{
// Implement the algorithm in section C.2.12
@@ -224,9 +224,9 @@ namespace Ryujinx.Graphics.Texture
}
public static void DecodeIntegerSequence(
- List decodeIntegerSequence,
- BitArrayStream bitStream,
- int maxRange,
+ List decodeIntegerSequence,
+ BitArrayStream bitStream,
+ int maxRange,
int numberValues)
{
// Determine encoding parameters
diff --git a/Ryujinx.Graphics.Texture/BlockLinearConstants.cs b/Ryujinx.Graphics.Texture/BlockLinearConstants.cs
new file mode 100644
index 000000000..d95691cf6
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/BlockLinearConstants.cs
@@ -0,0 +1,10 @@
+namespace Ryujinx.Graphics.Texture
+{
+ static class BlockLinearConstants
+ {
+ public const int GobStride = 64;
+ public const int GobHeight = 8;
+
+ public const int GobSize = GobStride * GobHeight;
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Texture/BlockLinearLayout.cs b/Ryujinx.Graphics.Texture/BlockLinearLayout.cs
new file mode 100644
index 000000000..3d3f13ba6
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/BlockLinearLayout.cs
@@ -0,0 +1,106 @@
+using Ryujinx.Common;
+using System;
+
+using static Ryujinx.Graphics.Texture.BlockLinearConstants;
+
+namespace Ryujinx.Graphics.Texture
+{
+ class BlockLinearLayout
+ {
+ private struct RobAndSliceSizes
+ {
+ public int RobSize;
+ public int SliceSize;
+
+ public RobAndSliceSizes(int robSize, int sliceSize)
+ {
+ RobSize = robSize;
+ SliceSize = sliceSize;
+ }
+ }
+
+ private int _texWidth;
+ private int _texHeight;
+ private int _texDepth;
+ private int _texGobBlocksInY;
+ private int _texGobBlocksInZ;
+ 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;
+
+ public BlockLinearLayout(
+ int width,
+ int height,
+ int depth,
+ int gobBlocksInY,
+ int gobBlocksInZ,
+ int bpp)
+ {
+ _texWidth = width;
+ _texHeight = height;
+ _texDepth = depth;
+ _texGobBlocksInY = gobBlocksInY;
+ _texGobBlocksInZ = gobBlocksInZ;
+ _texBpp = bpp;
+
+ _bppShift = BitUtils.CountTrailingZeros32(bpp);
+
+ _bhMask = gobBlocksInY - 1;
+ _bdMask = gobBlocksInZ - 1;
+
+ _bhShift = BitUtils.CountTrailingZeros32(gobBlocksInY);
+ _bdShift = BitUtils.CountTrailingZeros32(gobBlocksInZ);
+
+ _xShift = BitUtils.CountTrailingZeros32(GobSize * gobBlocksInY * gobBlocksInZ);
+
+ RobAndSliceSizes rsSizes = GetRobAndSliceSizes(width, height, gobBlocksInY, gobBlocksInZ);
+
+ _robSize = rsSizes.RobSize;
+ _sliceSize = rsSizes.SliceSize;
+ }
+
+ private RobAndSliceSizes GetRobAndSliceSizes(int width, int height, int gobBlocksInY, int gobBlocksInZ)
+ {
+ int widthInGobs = BitUtils.DivRoundUp(width * _texBpp, GobStride);
+
+ int robSize = GobSize * gobBlocksInY * gobBlocksInZ * widthInGobs;
+
+ int sliceSize = BitUtils.DivRoundUp(height, gobBlocksInY * GobHeight) * robSize;
+
+ return new RobAndSliceSizes(robSize, sliceSize);
+ }
+
+ public int GetOffset(int x, int y, int z)
+ {
+ x <<= _bppShift;
+
+ int yh = y / GobHeight;
+
+ int position = (z >> _bdShift) * _sliceSize + (yh >> _bhShift) * _robSize;
+
+ position += (x / GobStride) << _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 position;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Texture/LayoutConverter.cs b/Ryujinx.Graphics.Texture/LayoutConverter.cs
new file mode 100644
index 000000000..36ae522b5
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/LayoutConverter.cs
@@ -0,0 +1,167 @@
+using Ryujinx.Common;
+using System;
+
+using static Ryujinx.Graphics.Texture.BlockLinearConstants;
+
+namespace Ryujinx.Graphics.Texture
+{
+ public static class LayoutConverter
+ {
+ private const int AlignmentSize = 4;
+
+ public static Span ConvertBlockLinearToLinear(
+ int width,
+ int height,
+ int depth,
+ int levels,
+ int layers,
+ int blockWidth,
+ int blockHeight,
+ int bytesPerPixel,
+ int gobBlocksInY,
+ int gobBlocksInZ,
+ int gobBlocksInTileX,
+ SizeInfo sizeInfo,
+ Span data)
+ {
+ int outSize = GetTextureSize(
+ width,
+ height,
+ depth,
+ levels,
+ layers,
+ blockWidth,
+ blockHeight,
+ bytesPerPixel);
+
+ Span output = new byte[outSize];
+
+ int outOffs = 0;
+
+ int wAlignment = gobBlocksInTileX * (GobStride / bytesPerPixel);
+
+ int mipGobBlocksInY = gobBlocksInY;
+ int mipGobBlocksInZ = gobBlocksInZ;
+
+ for (int level = 0; level < levels; level++)
+ {
+ int w = Math.Max(1, width >> level);
+ int h = Math.Max(1, height >> level);
+ int d = Math.Max(1, depth >> level);
+
+ w = BitUtils.DivRoundUp(w, blockWidth);
+ h = BitUtils.DivRoundUp(h, blockHeight);
+
+ while (h <= (mipGobBlocksInY >> 1) * GobHeight && mipGobBlocksInY != 1)
+ {
+ mipGobBlocksInY >>= 1;
+ }
+
+ while (d <= (mipGobBlocksInZ >> 1) && mipGobBlocksInZ != 1)
+ {
+ mipGobBlocksInZ >>= 1;
+ }
+
+ int stride = BitUtils.AlignUp(w * bytesPerPixel, AlignmentSize);
+ int wAligned = BitUtils.AlignUp(w, wAlignment);
+
+ BlockLinearLayout layoutConverter = new BlockLinearLayout(
+ wAligned,
+ h,
+ d,
+ mipGobBlocksInY,
+ mipGobBlocksInZ,
+ bytesPerPixel);
+
+ for (int layer = 0; layer < layers; layer++)
+ {
+ int inBaseOffset = layer * sizeInfo.LayerSize + sizeInfo.GetMipOffset(level);
+
+ for (int z = 0; z < d; z++)
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ int offset = inBaseOffset + layoutConverter.GetOffset(x, y, z);
+
+ Span dest = output.Slice(outOffs + x * bytesPerPixel, bytesPerPixel);
+
+ data.Slice(offset, bytesPerPixel).CopyTo(dest);
+ }
+
+ outOffs += stride;
+ }
+ }
+ }
+
+ return output;
+ }
+
+ public static Span ConvertLinearStridedToLinear(
+ int width,
+ int height,
+ int blockWidth,
+ int blockHeight,
+ int stride,
+ int bytesPerPixel,
+ Span data)
+ {
+ int outOffs = 0;
+
+ int w = width;
+ int h = height;
+
+ w = BitUtils.DivRoundUp(w, blockWidth);
+ h = BitUtils.DivRoundUp(h, blockHeight);
+
+ int outStride = BitUtils.AlignUp(w * bytesPerPixel, AlignmentSize);
+
+ Span output = new byte[h * outStride];
+
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ int offset = y * stride + x * bytesPerPixel;
+
+ Span dest = output.Slice(outOffs + x * bytesPerPixel, bytesPerPixel);
+
+ data.Slice(offset, bytesPerPixel).CopyTo(dest);
+ }
+
+ outOffs += outStride;
+ }
+
+ return output;
+ }
+
+ private static int GetTextureSize(
+ int width,
+ int height,
+ int depth,
+ int levels,
+ int layers,
+ int blockWidth,
+ int blockHeight,
+ int bytesPerPixel)
+ {
+ int layerSize = 0;
+
+ for (int level = 0; level < levels; level++)
+ {
+ int w = Math.Max(1, width >> level);
+ int h = Math.Max(1, height >> level);
+ int d = Math.Max(1, depth >> level);
+
+ w = BitUtils.DivRoundUp(w, blockWidth);
+ h = BitUtils.DivRoundUp(h, blockHeight);
+
+ int stride = BitUtils.AlignUp(w * bytesPerPixel, AlignmentSize);
+
+ layerSize += stride * h * d;
+ }
+
+ return layerSize * layers;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Texture/OffsetCalculator.cs b/Ryujinx.Graphics.Texture/OffsetCalculator.cs
new file mode 100644
index 000000000..bb5d606ca
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/OffsetCalculator.cs
@@ -0,0 +1,55 @@
+using Ryujinx.Common;
+
+using static Ryujinx.Graphics.Texture.BlockLinearConstants;
+
+namespace Ryujinx.Graphics.Texture
+{
+ public class OffsetCalculator
+ {
+ private int _stride;
+ private bool _isLinear;
+ private int _bytesPerPixel;
+
+ private BlockLinearLayout _layoutConverter;
+
+ public OffsetCalculator(
+ int width,
+ int height,
+ int stride,
+ bool isLinear,
+ int gobBlocksInY,
+ int bytesPerPixel)
+ {
+ _stride = stride;
+ _isLinear = isLinear;
+ _bytesPerPixel = bytesPerPixel;
+
+ int wAlignment = GobStride / bytesPerPixel;
+
+ int wAligned = BitUtils.AlignUp(width, wAlignment);
+
+ if (!isLinear)
+ {
+ _layoutConverter = new BlockLinearLayout(
+ wAligned,
+ height,
+ 1,
+ gobBlocksInY,
+ 1,
+ bytesPerPixel);
+ }
+ }
+
+ public int GetOffset(int x, int y)
+ {
+ if (_isLinear)
+ {
+ return x * _bytesPerPixel + y * _stride;
+ }
+ else
+ {
+ return _layoutConverter.GetOffset(x, y, 0);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Texture/Ryujinx.Graphics.Texture.csproj b/Ryujinx.Graphics.Texture/Ryujinx.Graphics.Texture.csproj
new file mode 100644
index 000000000..f446f16cc
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/Ryujinx.Graphics.Texture.csproj
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+ netcoreapp3.0
+
+
+
diff --git a/Ryujinx.Graphics.Texture/Size.cs b/Ryujinx.Graphics.Texture/Size.cs
new file mode 100644
index 000000000..4e070c908
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/Size.cs
@@ -0,0 +1,19 @@
+using Ryujinx.Common;
+using System;
+
+namespace Ryujinx.Graphics.Texture
+{
+ public struct Size
+ {
+ public int Width { get; }
+ public int Height { get; }
+ public int Depth { get; }
+
+ public Size(int width, int height, int depth)
+ {
+ Width = width;
+ Height = height;
+ Depth = depth;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Texture/SizeCalculator.cs b/Ryujinx.Graphics.Texture/SizeCalculator.cs
new file mode 100644
index 000000000..873f41a32
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/SizeCalculator.cs
@@ -0,0 +1,195 @@
+using Ryujinx.Common;
+using System;
+
+using static Ryujinx.Graphics.Texture.BlockLinearConstants;
+
+namespace Ryujinx.Graphics.Texture
+{
+ public static class SizeCalculator
+ {
+ private const int StrideAlignment = 32;
+
+ public static SizeInfo GetBlockLinearTextureSize(
+ int width,
+ int height,
+ int depth,
+ int levels,
+ int layers,
+ int blockWidth,
+ int blockHeight,
+ int bytesPerPixel,
+ int gobBlocksInY,
+ int gobBlocksInZ,
+ int gobBlocksInTileX)
+ {
+ int layerSize = 0;
+
+ int[] mipOffsets = new int[levels];
+
+ int mipGobBlocksInY = gobBlocksInY;
+ int mipGobBlocksInZ = gobBlocksInZ;
+
+ for (int level = 0; level < levels; level++)
+ {
+ int w = Math.Max(1, width >> level);
+ int h = Math.Max(1, height >> level);
+ int d = Math.Max(1, depth >> level);
+
+ w = BitUtils.DivRoundUp(w, blockWidth);
+ h = BitUtils.DivRoundUp(h, blockHeight);
+
+ while (h <= (mipGobBlocksInY >> 1) * GobHeight && mipGobBlocksInY != 1)
+ {
+ mipGobBlocksInY >>= 1;
+ }
+
+ while (d <= (mipGobBlocksInZ >> 1) && mipGobBlocksInZ != 1)
+ {
+ mipGobBlocksInZ >>= 1;
+ }
+
+ int widthInGobs = BitUtils.AlignUp(BitUtils.DivRoundUp(w * bytesPerPixel, GobStride), gobBlocksInTileX);
+
+ int totalBlocksOfGobsInZ = BitUtils.DivRoundUp(d, mipGobBlocksInZ);
+ int totalBlocksOfGobsInY = BitUtils.DivRoundUp(BitUtils.DivRoundUp(h, GobHeight), mipGobBlocksInY);
+
+ int robSize = widthInGobs * mipGobBlocksInY * mipGobBlocksInZ * GobSize;
+
+ mipOffsets[level] = layerSize;
+
+ layerSize += totalBlocksOfGobsInZ * totalBlocksOfGobsInY * robSize;
+ }
+
+ layerSize = AlignLayerSize(
+ layerSize,
+ height,
+ depth,
+ blockHeight,
+ gobBlocksInY,
+ gobBlocksInZ);
+
+ int[] allOffsets = new int[levels * layers];
+
+ for (int layer = 0; layer < layers; layer++)
+ {
+ int baseIndex = layer * levels;
+ int baseOffset = layer * layerSize;
+
+ for (int level = 0; level < levels; level++)
+ {
+ allOffsets[baseIndex + level] = baseOffset + mipOffsets[level];
+ }
+ }
+
+ int totalSize = layerSize * layers;
+
+ return new SizeInfo(mipOffsets, allOffsets, levels, layerSize, totalSize);
+ }
+
+ public static SizeInfo GetLinearTextureSize(int stride, int height, int blockHeight)
+ {
+ // Non-2D or mipmapped linear textures are not supported by the Switch GPU,
+ // so we only need to handle a single case (2D textures without mipmaps).
+ int totalSize = stride * BitUtils.DivRoundUp(height, blockHeight);
+
+ return new SizeInfo(new int[] { 0 }, new int[] { 0 }, 1, totalSize, totalSize);
+ }
+
+ private static int AlignLayerSize(
+ int size,
+ int height,
+ int depth,
+ int blockHeight,
+ int gobBlocksInY,
+ int gobBlocksInZ)
+ {
+ height = BitUtils.DivRoundUp(height, blockHeight);
+
+ while (height <= (gobBlocksInY >> 1) * GobHeight && gobBlocksInY != 1)
+ {
+ gobBlocksInY >>= 1;
+ }
+
+ while (depth <= (gobBlocksInZ >> 1) && gobBlocksInZ != 1)
+ {
+ gobBlocksInZ >>= 1;
+ }
+
+ int blockOfGobsSize = gobBlocksInY * gobBlocksInZ * GobSize;
+
+ int sizeInBlockOfGobs = size / blockOfGobsSize;
+
+ if (size != sizeInBlockOfGobs * blockOfGobsSize)
+ {
+ size = (sizeInBlockOfGobs + 1) * blockOfGobsSize;
+ }
+
+ return size;
+ }
+
+ public static Size GetBlockLinearAlignedSize(
+ int width,
+ int height,
+ int depth,
+ int blockWidth,
+ int blockHeight,
+ int bytesPerPixel,
+ int gobBlocksInY,
+ int gobBlocksInZ,
+ int gobBlocksInTileX)
+ {
+ width = BitUtils.DivRoundUp(width, blockWidth);
+ height = BitUtils.DivRoundUp(height, blockHeight);
+
+ int gobWidth = gobBlocksInTileX * (GobStride / bytesPerPixel);
+
+ int blockOfGobsHeight = gobBlocksInY * GobHeight;
+ int blockOfGobsDepth = gobBlocksInZ;
+
+ width = BitUtils.AlignUp(width, gobWidth);
+ height = BitUtils.AlignUp(height, blockOfGobsHeight);
+ depth = BitUtils.AlignUp(depth, blockOfGobsDepth);
+
+ return new Size(width, height, depth);
+ }
+
+ public static Size GetLinearAlignedSize(
+ int width,
+ int height,
+ int blockWidth,
+ int blockHeight,
+ int bytesPerPixel)
+ {
+ width = BitUtils.DivRoundUp(width, blockWidth);
+ height = BitUtils.DivRoundUp(height, blockHeight);
+
+ int widthAlignment = StrideAlignment / bytesPerPixel;
+
+ width = BitUtils.AlignUp(width, widthAlignment);
+
+ return new Size(width, height, 1);
+ }
+
+ public static (int, int) GetMipGobBlockSizes(
+ int height,
+ int depth,
+ int blockHeight,
+ int gobBlocksInY,
+ int gobBlocksInZ)
+ {
+ height = BitUtils.DivRoundUp(height, blockHeight);
+
+ while (height <= (gobBlocksInY >> 1) * GobHeight && gobBlocksInY != 1)
+ {
+ gobBlocksInY >>= 1;
+ }
+
+ while (depth <= (gobBlocksInZ >> 1) && gobBlocksInZ != 1)
+ {
+ gobBlocksInZ >>= 1;
+ }
+
+ return (gobBlocksInY, gobBlocksInZ);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics.Texture/SizeInfo.cs b/Ryujinx.Graphics.Texture/SizeInfo.cs
new file mode 100644
index 000000000..37d824cc5
--- /dev/null
+++ b/Ryujinx.Graphics.Texture/SizeInfo.cs
@@ -0,0 +1,58 @@
+using Ryujinx.Common;
+using System;
+
+namespace Ryujinx.Graphics.Texture
+{
+ public struct SizeInfo
+ {
+ private int[] _mipOffsets;
+ private int[] _allOffsets;
+
+ private int _levels;
+
+ public int LayerSize { get; }
+ public int TotalSize { get; }
+
+ public SizeInfo(
+ int[] mipOffsets,
+ int[] allOffsets,
+ int levels,
+ int layerSize,
+ int totalSize)
+ {
+ _mipOffsets = mipOffsets;
+ _allOffsets = allOffsets;
+ _levels = levels;
+ LayerSize = layerSize;
+ TotalSize = totalSize;
+ }
+
+ public int GetMipOffset(int level)
+ {
+ if ((uint)level > _mipOffsets.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(level));
+ }
+
+ return _mipOffsets[level];
+ }
+
+ public bool FindView(int offset, int size, out int firstLayer, out int firstLevel)
+ {
+ int index = Array.BinarySearch(_allOffsets, offset);
+
+ if (index < 0)
+ {
+ firstLayer = 0;
+ firstLevel = 0;
+
+ return false;
+ }
+
+ firstLayer = index / _levels;
+ firstLevel = index - (firstLayer * _levels);
+
+ return true;
+ }
+ }
+}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/CdmaProcessor.cs b/Ryujinx.Graphics/CdmaProcessor.cs
deleted file mode 100644
index 4ff12fbf5..000000000
--- a/Ryujinx.Graphics/CdmaProcessor.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using Ryujinx.Graphics.Memory;
-using System.Collections.Generic;
-
-namespace Ryujinx.Graphics
-{
- public class CdmaProcessor
- {
- private const int MethSetMethod = 0x10;
- private const int MethSetData = 0x11;
-
- private NvGpu _gpu;
-
- public CdmaProcessor(NvGpu gpu)
- {
- _gpu = gpu;
- }
-
- public void PushCommands(NvGpuVmm vmm, int[] cmdBuffer)
- {
- List commands = new List();
-
- ChClassId currentClass = 0;
-
- for (int index = 0; index < cmdBuffer.Length; index++)
- {
- int cmd = cmdBuffer[index];
-
- int value = (cmd >> 0) & 0xffff;
- int methodOffset = (cmd >> 16) & 0xfff;
-
- ChSubmissionMode submissionMode = (ChSubmissionMode)((cmd >> 28) & 0xf);
-
- switch (submissionMode)
- {
- case ChSubmissionMode.SetClass: currentClass = (ChClassId)(value >> 6); break;
-
- case ChSubmissionMode.Incrementing:
- {
- int count = value;
-
- for (int argIdx = 0; argIdx < count; argIdx++)
- {
- int argument = cmdBuffer[++index];
-
- commands.Add(new ChCommand(currentClass, methodOffset + argIdx, argument));
- }
-
- break;
- }
-
- case ChSubmissionMode.NonIncrementing:
- {
- int count = value;
-
- int[] arguments = new int[count];
-
- for (int argIdx = 0; argIdx < count; argIdx++)
- {
- arguments[argIdx] = cmdBuffer[++index];
- }
-
- commands.Add(new ChCommand(currentClass, methodOffset, arguments));
-
- break;
- }
- }
- }
-
- ProcessCommands(vmm, commands.ToArray());
- }
-
- private void ProcessCommands(NvGpuVmm vmm, ChCommand[] commands)
- {
- int methodOffset = 0;
-
- foreach (ChCommand command in commands)
- {
- switch (command.MethodOffset)
- {
- case MethSetMethod: methodOffset = command.Arguments[0]; break;
-
- case MethSetData:
- {
- if (command.ClassId == ChClassId.NvDec)
- {
- _gpu.VideoDecoder.Process(vmm, methodOffset, command.Arguments);
- }
- else if (command.ClassId == ChClassId.GraphicsVic)
- {
- _gpu.VideoImageComposer.Process(vmm, methodOffset, command.Arguments);
- }
-
- break;
- }
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/ChClassId.cs b/Ryujinx.Graphics/ChClassId.cs
deleted file mode 100644
index 115f0b89c..000000000
--- a/Ryujinx.Graphics/ChClassId.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace Ryujinx.Graphics
-{
- enum ChClassId
- {
- Host1X = 0x1,
- VideoEncodeMpeg = 0x20,
- VideoEncodeNvEnc = 0x21,
- VideoStreamingVi = 0x30,
- VideoStreamingIsp = 0x32,
- VideoStreamingIspB = 0x34,
- VideoStreamingViI2c = 0x36,
- GraphicsVic = 0x5d,
- Graphics3D = 0x60,
- GraphicsGpu = 0x61,
- Tsec = 0xe0,
- TsecB = 0xe1,
- NvJpg = 0xc0,
- NvDec = 0xf0
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/ChCommandEntry.cs b/Ryujinx.Graphics/ChCommandEntry.cs
deleted file mode 100644
index b01b77eda..000000000
--- a/Ryujinx.Graphics/ChCommandEntry.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-namespace Ryujinx.Graphics
-{
- struct ChCommand
- {
- public ChClassId ClassId { get; private set; }
-
- public int MethodOffset { get; private set; }
-
- public int[] Arguments { get; private set; }
-
- public ChCommand(ChClassId classId, int methodOffset, params int[] arguments)
- {
- ClassId = classId;
- MethodOffset = methodOffset;
- Arguments = arguments;
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/ChSubmissionMode.cs b/Ryujinx.Graphics/ChSubmissionMode.cs
deleted file mode 100644
index 5c6530196..000000000
--- a/Ryujinx.Graphics/ChSubmissionMode.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace Ryujinx.Graphics
-{
- enum ChSubmissionMode
- {
- SetClass = 0,
- Incrementing = 1,
- NonIncrementing = 2,
- Mask = 3,
- Immediate = 4,
- Restart = 5,
- Gather = 6
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/DepthCompareFunc.cs b/Ryujinx.Graphics/DepthCompareFunc.cs
deleted file mode 100644
index 24c8854a4..000000000
--- a/Ryujinx.Graphics/DepthCompareFunc.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace Ryujinx.Graphics
-{
- public enum DepthCompareFunc
- {
- Never = 0,
- Less = 1,
- Equal = 2,
- LEqual = 3,
- Greater = 4,
- NotEqual = 5,
- GEqual = 6,
- Always = 7
- }
-}
diff --git a/Ryujinx.Graphics/Gal/EmbeddedResource.cs b/Ryujinx.Graphics/Gal/EmbeddedResource.cs
deleted file mode 100644
index ba6624991..000000000
--- a/Ryujinx.Graphics/Gal/EmbeddedResource.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-using System.IO;
-using System.Reflection;
-
-namespace Ryujinx.Graphics.Gal
-{
- static class EmbeddedResource
- {
- public static string GetString(string name)
- {
- Assembly asm = typeof(EmbeddedResource).Assembly;
-
- using (Stream resStream = asm.GetManifestResourceStream(name))
- {
- StreamReader reader = new StreamReader(resStream);
-
- return reader.ReadToEnd();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalBlendEquation.cs b/Ryujinx.Graphics/Gal/GalBlendEquation.cs
deleted file mode 100644
index 7757faae9..000000000
--- a/Ryujinx.Graphics/Gal/GalBlendEquation.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalBlendEquation
- {
- FuncAdd = 1,
- FuncSubtract = 2,
- FuncReverseSubtract = 3,
- Min = 4,
- Max = 5,
-
- FuncAddGl = 0x8006,
- FuncSubtractGl = 0x8007,
- FuncReverseSubtractGl = 0x8008,
- MinGl = 0x800a,
- MaxGl = 0x800b
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalBlendFactor.cs b/Ryujinx.Graphics/Gal/GalBlendFactor.cs
deleted file mode 100644
index f70b05011..000000000
--- a/Ryujinx.Graphics/Gal/GalBlendFactor.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalBlendFactor
- {
- Zero = 0x1,
- One = 0x2,
- SrcColor = 0x3,
- OneMinusSrcColor = 0x4,
- SrcAlpha = 0x5,
- OneMinusSrcAlpha = 0x6,
- DstAlpha = 0x7,
- OneMinusDstAlpha = 0x8,
- DstColor = 0x9,
- OneMinusDstColor = 0xa,
- SrcAlphaSaturate = 0xb,
- Src1Color = 0x10,
- OneMinusSrc1Color = 0x11,
- Src1Alpha = 0x12,
- OneMinusSrc1Alpha = 0x13,
- ConstantColor = 0x61,
- OneMinusConstantColor = 0x62,
- ConstantAlpha = 0x63,
- OneMinusConstantAlpha = 0x64,
-
- ZeroGl = 0x4000,
- OneGl = 0x4001,
- SrcColorGl = 0x4300,
- OneMinusSrcColorGl = 0x4301,
- SrcAlphaGl = 0x4302,
- OneMinusSrcAlphaGl = 0x4303,
- DstAlphaGl = 0x4304,
- OneMinusDstAlphaGl = 0x4305,
- DstColorGl = 0x4306,
- OneMinusDstColorGl = 0x4307,
- SrcAlphaSaturateGl = 0x4308,
- ConstantColorGl = 0xc001,
- OneMinusConstantColorGl = 0xc002,
- ConstantAlphaGl = 0xc003,
- OneMinusConstantAlphaGl = 0xc004,
- Src1ColorGl = 0xc900,
- OneMinusSrc1ColorGl = 0xc901,
- Src1AlphaGl = 0xc902,
- OneMinusSrc1AlphaGl = 0xc903
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalClearBufferFlags.cs b/Ryujinx.Graphics/Gal/GalClearBufferFlags.cs
deleted file mode 100644
index 8565051ca..000000000
--- a/Ryujinx.Graphics/Gal/GalClearBufferFlags.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System;
-
-namespace Ryujinx.Graphics.Gal
-{
- [Flags]
- public enum GalClearBufferFlags
- {
- Depth = 1 << 0,
- Stencil = 1 << 1,
- ColorRed = 1 << 2,
- ColorGreen = 1 << 3,
- ColorBlue = 1 << 4,
- ColorAlpha = 1 << 5
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalColorF.cs b/Ryujinx.Graphics/Gal/GalColorF.cs
deleted file mode 100644
index e915870c2..000000000
--- a/Ryujinx.Graphics/Gal/GalColorF.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public struct GalColorF
- {
- public float Red { get; private set; }
- public float Green { get; private set; }
- public float Blue { get; private set; }
- public float Alpha { get; private set; }
-
- public GalColorF(
- float red,
- float green,
- float blue,
- float alpha)
- {
- Red = red;
- Green = green;
- Blue = blue;
- Alpha = alpha;
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalComparisonOp.cs b/Ryujinx.Graphics/Gal/GalComparisonOp.cs
deleted file mode 100644
index f26a77533..000000000
--- a/Ryujinx.Graphics/Gal/GalComparisonOp.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalComparisonOp
- {
- Never = 0x1,
- Less = 0x2,
- Equal = 0x3,
- Lequal = 0x4,
- Greater = 0x5,
- NotEqual = 0x6,
- Gequal = 0x7,
- Always = 0x8
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalFrontFace.cs b/Ryujinx.Graphics/Gal/GalFrontFace.cs
deleted file mode 100644
index 6cc4a8024..000000000
--- a/Ryujinx.Graphics/Gal/GalFrontFace.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalFrontFace
- {
- Cw = 0x900,
- Ccw = 0x901
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalImage.cs b/Ryujinx.Graphics/Gal/GalImage.cs
deleted file mode 100644
index 1345704d2..000000000
--- a/Ryujinx.Graphics/Gal/GalImage.cs
+++ /dev/null
@@ -1,87 +0,0 @@
-using Ryujinx.Graphics.Texture;
-
-namespace Ryujinx.Graphics.Gal
-{
- public struct GalImage
- {
- public int Width;
- public int Height;
-
- // FIXME: separate layer and depth
- public int Depth;
- public int LayerCount;
- public int TileWidth;
- public int GobBlockHeight;
- public int GobBlockDepth;
- public int Pitch;
- public int MaxMipmapLevel;
-
- public GalImageFormat Format;
- public GalMemoryLayout Layout;
- public GalTextureSource XSource;
- public GalTextureSource YSource;
- public GalTextureSource ZSource;
- public GalTextureSource WSource;
- public GalTextureTarget TextureTarget;
-
- public GalImage(
- int width,
- int height,
- int depth,
- int layerCount,
- int tileWidth,
- int gobBlockHeight,
- int gobBlockDepth,
- GalMemoryLayout layout,
- GalImageFormat format,
- GalTextureTarget textureTarget,
- int maxMipmapLevel = 1,
- GalTextureSource xSource = GalTextureSource.Red,
- GalTextureSource ySource = GalTextureSource.Green,
- GalTextureSource zSource = GalTextureSource.Blue,
- GalTextureSource wSource = GalTextureSource.Alpha)
- {
- Width = width;
- Height = height;
- LayerCount = layerCount;
- Depth = depth;
- TileWidth = tileWidth;
- GobBlockHeight = gobBlockHeight;
- GobBlockDepth = gobBlockDepth;
- Layout = layout;
- Format = format;
- MaxMipmapLevel = maxMipmapLevel;
- XSource = xSource;
- YSource = ySource;
- ZSource = zSource;
- WSource = wSource;
- TextureTarget = textureTarget;
-
- Pitch = ImageUtils.GetPitch(format, width);
- }
-
- public bool SizeMatches(GalImage image, bool ignoreLayer = false)
- {
- if (ImageUtils.GetBytesPerPixel(Format) !=
- ImageUtils.GetBytesPerPixel(image.Format))
- {
- return false;
- }
-
- if (ImageUtils.GetAlignedWidth(this) !=
- ImageUtils.GetAlignedWidth(image))
- {
- return false;
- }
-
- bool result = Height == image.Height && Depth == image.Depth;
-
- if (!ignoreLayer)
- {
- result = result && LayerCount == image.LayerCount;
- }
-
- return result;
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalImageFormat.cs b/Ryujinx.Graphics/Gal/GalImageFormat.cs
deleted file mode 100644
index 19ce6cfc4..000000000
--- a/Ryujinx.Graphics/Gal/GalImageFormat.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-// ReSharper disable InconsistentNaming
-using System;
-
-namespace Ryujinx.Graphics.Gal
-{
- [Flags]
- public enum GalImageFormat
- {
- Astc2DStart,
- Astc2D4x4,
- Astc2D5x4,
- Astc2D5x5,
- Astc2D6x5,
- Astc2D6x6,
- Astc2D8x5,
- Astc2D8x6,
- Astc2D8x8,
- Astc2D10x5,
- Astc2D10x6,
- Astc2D10x8,
- Astc2D10x10,
- Astc2D12x10,
- Astc2D12x12,
- Astc2DEnd,
-
- Rgba4,
- Rgb565,
- Bgr565,
- Bgr5A1,
- Rgb5A1,
- R8,
- Rg8,
- Rgbx8,
- Rgba8,
- Bgra8,
- Rgb10A2,
- R16,
- Rg16,
- Rgba16,
- R32,
- Rg32,
- Rgba32,
- R11G11B10,
- D16,
- D24,
- D32,
- D24S8,
- D32S8,
- BC1,
- BC2,
- BC3,
- BC4,
- BC5,
- BptcSfloat,
- BptcUfloat,
- BptcUnorm,
-
- Snorm = 1 << 26,
- Unorm = 1 << 27,
- Sint = 1 << 28,
- Uint = 1 << 39,
- Float = 1 << 30,
- Srgb = 1 << 31,
-
- TypeMask = Snorm | Unorm | Sint | Uint | Float | Srgb,
-
- FormatMask = ~TypeMask
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalIndexFormat.cs b/Ryujinx.Graphics/Gal/GalIndexFormat.cs
deleted file mode 100644
index 71a50cdba..000000000
--- a/Ryujinx.Graphics/Gal/GalIndexFormat.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalIndexFormat
- {
- Byte = 0,
- Int16 = 1,
- Int32 = 2
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalMemoryLayout.cs b/Ryujinx.Graphics/Gal/GalMemoryLayout.cs
deleted file mode 100644
index 73fabf8c2..000000000
--- a/Ryujinx.Graphics/Gal/GalMemoryLayout.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalMemoryLayout
- {
- BlockLinear = 0,
- Pitch = 1
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalPipelineState.cs b/Ryujinx.Graphics/Gal/GalPipelineState.cs
deleted file mode 100644
index c044a55fc..000000000
--- a/Ryujinx.Graphics/Gal/GalPipelineState.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public struct ColorMaskState
- {
- private static readonly ColorMaskState DefaultBackingField = new ColorMaskState()
- {
- Red = true,
- Green = true,
- Blue = true,
- Alpha = true
- };
-
- public static ColorMaskState Default => DefaultBackingField;
-
- public bool Red;
- public bool Green;
- public bool Blue;
- public bool Alpha;
- }
-
- public struct BlendState
- {
- private static readonly BlendState DefaultBackingField = new BlendState()
- {
- Enabled = false,
- SeparateAlpha = false,
- EquationRgb = GalBlendEquation.FuncAdd,
- FuncSrcRgb = GalBlendFactor.One,
- FuncDstRgb = GalBlendFactor.Zero,
- EquationAlpha = GalBlendEquation.FuncAdd,
- FuncSrcAlpha = GalBlendFactor.One,
- FuncDstAlpha = GalBlendFactor.Zero
- };
-
- public static BlendState Default => DefaultBackingField;
-
- public bool Enabled;
- public bool SeparateAlpha;
- public GalBlendEquation EquationRgb;
- public GalBlendFactor FuncSrcRgb;
- public GalBlendFactor FuncDstRgb;
- public GalBlendEquation EquationAlpha;
- public GalBlendFactor FuncSrcAlpha;
- public GalBlendFactor FuncDstAlpha;
- }
-
- public class GalPipelineState
- {
- public const int Stages = 5;
- public const int ConstBuffersPerStage = 18;
- public const int RenderTargetsCount = 8;
-
- public long[][] ConstBufferKeys;
-
- public GalVertexBinding[] VertexBindings;
-
- public bool FramebufferSrgb;
-
- public float FlipX;
- public float FlipY;
-
- public int Instance;
-
- public GalFrontFace FrontFace;
-
- public bool CullFaceEnabled;
- public GalCullFace CullFace;
-
- public bool DepthTestEnabled;
- public bool DepthWriteEnabled;
- public GalComparisonOp DepthFunc;
- public float DepthRangeNear;
- public float DepthRangeFar;
-
- public bool StencilTestEnabled;
- public bool StencilTwoSideEnabled;
-
- public GalComparisonOp StencilBackFuncFunc;
- public int StencilBackFuncRef;
- public uint StencilBackFuncMask;
- public GalStencilOp StencilBackOpFail;
- public GalStencilOp StencilBackOpZFail;
- public GalStencilOp StencilBackOpZPass;
- public uint StencilBackMask;
-
- public GalComparisonOp StencilFrontFuncFunc;
- public int StencilFrontFuncRef;
- public uint StencilFrontFuncMask;
- public GalStencilOp StencilFrontOpFail;
- public GalStencilOp StencilFrontOpZFail;
- public GalStencilOp StencilFrontOpZPass;
- public uint StencilFrontMask;
-
- public int ScissorTestCount;
- public bool[] ScissorTestEnabled;
- public int[] ScissorTestX;
- public int[] ScissorTestY;
- public int[] ScissorTestWidth;
- public int[] ScissorTestHeight;
-
- public bool BlendIndependent;
- public BlendState[] Blends;
-
- public bool ColorMaskCommon;
- public ColorMaskState[] ColorMasks;
-
- public bool PrimitiveRestartEnabled;
- public uint PrimitiveRestartIndex;
-
- public GalPipelineState()
- {
- ConstBufferKeys = new long[Stages][];
-
- for (int stage = 0; stage < Stages; stage++)
- {
- ConstBufferKeys[stage] = new long[ConstBuffersPerStage];
- }
-
- Blends = new BlendState[RenderTargetsCount];
-
- ScissorTestEnabled = new bool[RenderTargetsCount];
- ScissorTestY = new int[RenderTargetsCount];
- ScissorTestX = new int[RenderTargetsCount];
- ScissorTestWidth = new int[RenderTargetsCount];
- ScissorTestHeight = new int[RenderTargetsCount];
-
- ColorMasks = new ColorMaskState[RenderTargetsCount];
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalPrimitiveType.cs b/Ryujinx.Graphics/Gal/GalPrimitiveType.cs
deleted file mode 100644
index ce084149d..000000000
--- a/Ryujinx.Graphics/Gal/GalPrimitiveType.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalPrimitiveType
- {
- Points = 0x0,
- Lines = 0x1,
- LineLoop = 0x2,
- LineStrip = 0x3,
- Triangles = 0x4,
- TriangleStrip = 0x5,
- TriangleFan = 0x6,
- Quads = 0x7,
- QuadStrip = 0x8,
- Polygon = 0x9,
- LinesAdjacency = 0xa,
- LineStripAdjacency = 0xb,
- TrianglesAdjacency = 0xc,
- TriangleStripAdjacency = 0xd,
- Patches = 0xe
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalShaderType.cs b/Ryujinx.Graphics/Gal/GalShaderType.cs
deleted file mode 100644
index eb5aaf889..000000000
--- a/Ryujinx.Graphics/Gal/GalShaderType.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalShaderType
- {
- Vertex = 0,
- TessControl = 1,
- TessEvaluation = 2,
- Geometry = 3,
- Fragment = 4
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalStencilOp.cs b/Ryujinx.Graphics/Gal/GalStencilOp.cs
deleted file mode 100644
index fc83ca5ea..000000000
--- a/Ryujinx.Graphics/Gal/GalStencilOp.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalStencilOp
- {
- Keep = 0x1,
- Zero = 0x2,
- Replace = 0x3,
- Incr = 0x4,
- Decr = 0x5,
- Invert = 0x6,
- IncrWrap = 0x7,
- DecrWrap = 0x8
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalSurfaceFormat.cs b/Ryujinx.Graphics/Gal/GalSurfaceFormat.cs
deleted file mode 100644
index 9cebcc272..000000000
--- a/Ryujinx.Graphics/Gal/GalSurfaceFormat.cs
+++ /dev/null
@@ -1,68 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalSurfaceFormat
- {
- Bitmap = 0x1c,
- Unknown1D = 0x1d,
- Rgba32Float = 0xc0,
- Rgba32Sint = 0xc1,
- Rgba32Uint = 0xc2,
- Rgbx32Float = 0xc3,
- Rgbx32Sint = 0xc4,
- Rgbx32Uint = 0xc5,
- Rgba16Unorm = 0xc6,
- Rgba16Snorm = 0xc7,
- Rgba16Sint = 0xc8,
- Rgba16Uint = 0xc9,
- Rgba16Float = 0xca,
- Rg32Float = 0xcb,
- Rg32Sint = 0xcc,
- Rg32Uint = 0xcd,
- Rgbx16Float = 0xce,
- Bgra8Unorm = 0xcf,
- Bgra8Srgb = 0xd0,
- Rgb10A2Unorm = 0xd1,
- Rgb10A2Uint = 0xd2,
- Rgba8Unorm = 0xd5,
- Rgba8Srgb = 0xd6,
- Rgba8Snorm = 0xd7,
- Rgba8Sint = 0xd8,
- Rgba8Uint = 0xd9,
- Rg16Unorm = 0xda,
- Rg16Snorm = 0xdb,
- Rg16Sint = 0xdc,
- Rg16Uint = 0xdd,
- Rg16Float = 0xde,
- Bgr10A2Unorm = 0xdf,
- R11G11B10Float = 0xe0,
- R32Sint = 0xe3,
- R32Uint = 0xe4,
- R32Float = 0xe5,
- Bgrx8Unorm = 0xe6,
- Bgrx8Srgb = 0xe7,
- B5G6R5Unorm = 0xe8,
- Bgr5A1Unorm = 0xe9,
- Rg8Unorm = 0xea,
- Rg8Snorm = 0xeb,
- Rg8Sint = 0xec,
- Rg8Uint = 0xed,
- R16Unorm = 0xee,
- R16Snorm = 0xef,
- R16Sint = 0xf0,
- R16Uint = 0xf1,
- R16Float = 0xf2,
- R8Unorm = 0xf3,
- R8Snorm = 0xf4,
- R8Sint = 0xf5,
- R8Uint = 0xf6,
- A8Unorm = 0xf7,
- Bgr5x1Unorm = 0xf8,
- Rgbx8Unorm = 0xf9,
- Rgbx8Srgb = 0xfa,
- Bgr5x1UnormUnknownFB = 0xfb,
- Bgr5x1UnormUnknownFC = 0xfc,
- Bgrx8UnormUnknownFD = 0xfd,
- Bgrx8UnormUnknownFE = 0xfe,
- Y32UintUnknownFF = 0xff
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalTextureFilter.cs b/Ryujinx.Graphics/Gal/GalTextureFilter.cs
deleted file mode 100644
index 8e9669f00..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureFilter.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalTextureFilter
- {
- Nearest = 1,
- Linear = 2
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalTextureFormat.cs b/Ryujinx.Graphics/Gal/GalTextureFormat.cs
deleted file mode 100644
index ed27180a2..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureFormat.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalTextureFormat
- {
- Rgba32 = 0x1,
- Rgba16 = 0x3,
- Rg32 = 0x4,
- Rgba8 = 0x8,
- Rgb10A2 = 0x9,
- Rg16 = 0xc,
- R32 = 0xf,
- BptcSfloat = 0x10,
- BptcUfloat = 0x11,
- Rgba4 = 0x12,
- Rgb5A1 = 0x14,
- Rgb565 = 0x15,
- BptcUnorm = 0x17,
- Rg8 = 0x18,
- R16 = 0x1b,
- R8 = 0x1d,
- R11G11B10F = 0x21,
- BC1 = 0x24,
- BC2 = 0x25,
- BC3 = 0x26,
- BC4 = 0x27,
- BC5 = 0x28,
- D24S8 = 0x29,
- D32F = 0x2f,
- D32Fx24S8 = 0x30,
- D16 = 0x3a,
- Astc2D4x4 = 0x40,
- Astc2D5x5 = 0x41,
- Astc2D6x6 = 0x42,
- Astc2D8x8 = 0x44,
- Astc2D10x10 = 0x45,
- Astc2D12x12 = 0x46,
- Astc2D5x4 = 0x50,
- Astc2D6x5 = 0x51,
- Astc2D8x6 = 0x52,
- Astc2D10x8 = 0x53,
- Astc2D12x10 = 0x54,
- Astc2D8x5 = 0x55,
- Astc2D10x5 = 0x56,
- Astc2D10x6 = 0x57
- }
-}
diff --git a/Ryujinx.Graphics/Gal/GalTextureMipFilter.cs b/Ryujinx.Graphics/Gal/GalTextureMipFilter.cs
deleted file mode 100644
index 2123ec7d2..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureMipFilter.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalTextureMipFilter
- {
- None = 1,
- Nearest = 2,
- Linear = 3
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalTextureSampler.cs b/Ryujinx.Graphics/Gal/GalTextureSampler.cs
deleted file mode 100644
index 2e57a130c..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureSampler.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public struct GalTextureSampler
- {
- public GalTextureWrap AddressU { get; private set; }
- public GalTextureWrap AddressV { get; private set; }
- public GalTextureWrap AddressP { get; private set; }
-
- public GalTextureFilter MinFilter { get; private set; }
- public GalTextureFilter MagFilter { get; private set; }
- public GalTextureMipFilter MipFilter { get; private set; }
-
- public GalColorF BorderColor { get; private set; }
-
- public bool DepthCompare { get; private set; }
- public DepthCompareFunc DepthCompareFunc { get; private set; }
-
- public GalTextureSampler(
- GalTextureWrap addressU,
- GalTextureWrap addressV,
- GalTextureWrap addressP,
- GalTextureFilter minFilter,
- GalTextureFilter magFilter,
- GalTextureMipFilter mipFilter,
- GalColorF borderColor,
- bool depthCompare,
- DepthCompareFunc depthCompareFunc)
- {
- AddressU = addressU;
- AddressV = addressV;
- AddressP = addressP;
- MinFilter = minFilter;
- MagFilter = magFilter;
- MipFilter = mipFilter;
- BorderColor = borderColor;
-
- DepthCompare = depthCompare;
- DepthCompareFunc = depthCompareFunc;
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalTextureSource.cs b/Ryujinx.Graphics/Gal/GalTextureSource.cs
deleted file mode 100644
index 72dbec606..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureSource.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalTextureSource
- {
- Zero = 0,
- Red = 2,
- Green = 3,
- Blue = 4,
- Alpha = 5,
- OneInt = 6,
- OneFloat = 7
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalTextureTarget.cs b/Ryujinx.Graphics/Gal/GalTextureTarget.cs
deleted file mode 100644
index bcc0c49a5..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureTarget.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalTextureTarget
- {
- OneD = 0,
- TwoD = 1,
- ThreeD = 2,
- CubeMap = 3,
- OneDArray = 4,
- TwoDArray = 5,
- OneDBuffer = 6,
- TwoDNoMipMap = 7,
- CubeArray = 8,
- }
-}
diff --git a/Ryujinx.Graphics/Gal/GalTextureType.cs b/Ryujinx.Graphics/Gal/GalTextureType.cs
deleted file mode 100644
index b02b8b37b..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureType.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalTextureType
- {
- Snorm = 1,
- Unorm = 2,
- Sint = 3,
- Uint = 4,
- SnormForceFp16 = 5,
- UnormForceFp16 = 6,
- Float = 7
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalTextureWrap.cs b/Ryujinx.Graphics/Gal/GalTextureWrap.cs
deleted file mode 100644
index 66e531540..000000000
--- a/Ryujinx.Graphics/Gal/GalTextureWrap.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalTextureWrap
- {
- Repeat = 0,
- MirroredRepeat = 1,
- ClampToEdge = 2,
- ClampToBorder = 3,
- Clamp = 4,
- MirrorClampToEdge = 5,
- MirrorClampToBorder = 6,
- MirrorClamp = 7
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalVertexAttrib.cs b/Ryujinx.Graphics/Gal/GalVertexAttrib.cs
deleted file mode 100644
index feca5aea3..000000000
--- a/Ryujinx.Graphics/Gal/GalVertexAttrib.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public struct GalVertexAttrib
- {
- public int Index { get; private set; }
- public bool IsConst { get; private set; }
- public int Offset { get; private set; }
- public byte[] Data { get; private set; }
-
- public GalVertexAttribSize Size { get; private set; }
- public GalVertexAttribType Type { get; private set; }
-
- public bool IsBgra { get; private set; }
-
- public GalVertexAttrib(
- int index,
- bool isConst,
- int offset,
- byte[] data,
- GalVertexAttribSize size,
- GalVertexAttribType type,
- bool isBgra)
- {
- Index = index;
- IsConst = isConst;
- Data = data;
- Offset = offset;
- Size = size;
- Type = type;
- IsBgra = isBgra;
- }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalVertexAttribSize.cs b/Ryujinx.Graphics/Gal/GalVertexAttribSize.cs
deleted file mode 100644
index d3ce60ace..000000000
--- a/Ryujinx.Graphics/Gal/GalVertexAttribSize.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalVertexAttribSize
- {
- _32_32_32_32 = 0x1,
- _32_32_32 = 0x2,
- _16_16_16_16 = 0x3,
- _32_32 = 0x4,
- _16_16_16 = 0x5,
- _8_8_8_8 = 0xa,
- _16_16 = 0xf,
- _32 = 0x12,
- _8_8_8 = 0x13,
- _8_8 = 0x18,
- _16 = 0x1b,
- _8 = 0x1d,
- _10_10_10_2 = 0x30,
- _11_11_10 = 0x31
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalVertexAttribType.cs b/Ryujinx.Graphics/Gal/GalVertexAttribType.cs
deleted file mode 100644
index 358836fda..000000000
--- a/Ryujinx.Graphics/Gal/GalVertexAttribType.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalVertexAttribType
- {
- Snorm = 1,
- Unorm = 2,
- Sint = 3,
- Uint = 4,
- Uscaled = 5,
- Sscaled = 6,
- Float = 7
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalVertexBinding.cs b/Ryujinx.Graphics/Gal/GalVertexBinding.cs
deleted file mode 100644
index 2337c2e32..000000000
--- a/Ryujinx.Graphics/Gal/GalVertexBinding.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public struct GalVertexBinding
- {
- // VboKey shouldn't be here, but ARB_vertex_attrib_binding is core since 4.3
-
- public bool Enabled;
- public int Stride;
- public long VboKey;
- public bool Instanced;
- public int Divisor;
- public GalVertexAttrib[] Attribs;
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/GalZetaFormat.cs b/Ryujinx.Graphics/Gal/GalZetaFormat.cs
deleted file mode 100644
index 2429249e5..000000000
--- a/Ryujinx.Graphics/Gal/GalZetaFormat.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public enum GalZetaFormat
- {
- D32Float = 0x0a,
- D16Unorm = 0x13,
- S8D24Unorm = 0x14,
- D24X8Unorm = 0x15,
- D24S8Unorm = 0x16,
- D24C8Unorm = 0x18,
- D32S8X24Float = 0x19,
- D24X8S8C8X16Unorm = 0x1d,
- D32X8C8X16Float = 0x1e,
- D32S8C8X16Float = 0x1f
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalConstBuffer.cs b/Ryujinx.Graphics/Gal/IGalConstBuffer.cs
deleted file mode 100644
index 8c4e6d032..000000000
--- a/Ryujinx.Graphics/Gal/IGalConstBuffer.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-using System;
-
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalConstBuffer
- {
- void LockCache();
- void UnlockCache();
-
- void Create(long key, long size);
-
- bool IsCached(long key, long size);
-
- void SetData(long key, long size, IntPtr hostAddress);
- void SetData(long key, byte[] data);
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalMemory.cs b/Ryujinx.Graphics/Gal/IGalMemory.cs
deleted file mode 100644
index 78eb7154b..000000000
--- a/Ryujinx.Graphics/Gal/IGalMemory.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalMemory
- {
- int ReadInt32(long position);
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalPipeline.cs b/Ryujinx.Graphics/Gal/IGalPipeline.cs
deleted file mode 100644
index 1ecb26028..000000000
--- a/Ryujinx.Graphics/Gal/IGalPipeline.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalPipeline
- {
- void Bind(GalPipelineState state);
- void Unbind(GalPipelineState state);
-
- void ResetDepthMask();
- void ResetColorMask(int index);
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalRasterizer.cs b/Ryujinx.Graphics/Gal/IGalRasterizer.cs
deleted file mode 100644
index 33bdeaad8..000000000
--- a/Ryujinx.Graphics/Gal/IGalRasterizer.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System;
-
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalRasterizer
- {
- void LockCaches();
- void UnlockCaches();
-
- void ClearBuffers(
- GalClearBufferFlags flags,
- int attachment,
- float red,
- float green,
- float blue,
- float alpha,
- float depth,
- int stencil);
-
- bool IsVboCached(long key, long dataSize);
-
- bool IsIboCached(long key, long dataSize);
-
- void CreateVbo(long key, int dataSize, IntPtr hostAddress);
- void CreateVbo(long key, byte[] data);
-
- void CreateIbo(long key, int dataSize, IntPtr hostAddress);
- void CreateIbo(long key, int dataSize, byte[] buffer);
-
- void SetIndexArray(int size, GalIndexFormat format);
-
- void DrawArrays(int first, int count, GalPrimitiveType primType);
-
- void DrawElements(long iboKey, int first, int vertexBase, GalPrimitiveType primType);
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalRenderTarget.cs b/Ryujinx.Graphics/Gal/IGalRenderTarget.cs
deleted file mode 100644
index c281fe06c..000000000
--- a/Ryujinx.Graphics/Gal/IGalRenderTarget.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalRenderTarget
- {
- void Bind();
-
- void BindColor(long key, int attachment);
-
- void UnbindColor(int attachment);
-
- void BindZeta(long key);
-
- void UnbindZeta();
-
- void Present(long key);
-
- void SetMap(int[] map);
-
- void SetTransform(bool flipX, bool flipY, int top, int left, int right, int bottom);
-
- void SetWindowSize(int width, int height);
-
- void SetViewport(int attachment, int x, int y, int width, int height);
-
- void Render();
-
- void Copy(
- GalImage srcImage,
- GalImage dstImage,
- long srcKey,
- long dstKey,
- int srcLayer,
- int dstLayer,
- int srcX0,
- int srcY0,
- int srcX1,
- int srcY1,
- int dstX0,
- int dstY0,
- int dstX1,
- int dstY1);
-
- void Reinterpret(long key, GalImage newImage);
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalRenderer.cs b/Ryujinx.Graphics/Gal/IGalRenderer.cs
deleted file mode 100644
index 1acc4d03b..000000000
--- a/Ryujinx.Graphics/Gal/IGalRenderer.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System;
-
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalRenderer
- {
- void QueueAction(Action actionMthd);
-
- void RunActions();
-
- IGalConstBuffer Buffer { get; }
-
- IGalRenderTarget RenderTarget { get; }
-
- IGalRasterizer Rasterizer { get; }
-
- IGalShader Shader { get; }
-
- IGalPipeline Pipeline { get; }
-
- IGalTexture Texture { get; }
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalShader.cs b/Ryujinx.Graphics/Gal/IGalShader.cs
deleted file mode 100644
index 6a9abe75b..000000000
--- a/Ryujinx.Graphics/Gal/IGalShader.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using Ryujinx.Graphics.Shader;
-using System.Collections.Generic;
-
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalShader
- {
- void Create(IGalMemory memory, long key, GalShaderType type);
-
- void Create(IGalMemory memory, long vpAPos, long key, GalShaderType type);
-
- IEnumerable GetConstBufferUsage(long key);
- IEnumerable GetTextureUsage(long key);
-
- void Bind(long key);
-
- void Unbind(GalShaderType type);
-
- void BindProgram();
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/IGalTexture.cs b/Ryujinx.Graphics/Gal/IGalTexture.cs
deleted file mode 100644
index 23ce054ae..000000000
--- a/Ryujinx.Graphics/Gal/IGalTexture.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-namespace Ryujinx.Graphics.Gal
-{
- public interface IGalTexture
- {
- void LockCache();
- void UnlockCache();
-
- void Create(long key, int size, GalImage image);
-
- void Create(long key, byte[] data, GalImage image);
-
- bool TryGetImage(long key, out GalImage image);
-
- void Bind(long key, int index, GalImage image);
-
- void SetSampler(GalImage image, GalTextureSampler sampler);
- }
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/OpenGL/DeleteValueCallback.cs b/Ryujinx.Graphics/Gal/OpenGL/DeleteValueCallback.cs
deleted file mode 100644
index 63b626f18..000000000
--- a/Ryujinx.Graphics/Gal/OpenGL/DeleteValueCallback.cs
+++ /dev/null
@@ -1,4 +0,0 @@
-namespace Ryujinx.Graphics.Gal.OpenGL
-{
- delegate void DeleteValue(T value);
-}
\ No newline at end of file
diff --git a/Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs b/Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs
deleted file mode 100644
index d7f6f0044..000000000
--- a/Ryujinx.Graphics/Gal/OpenGL/ImageHandler.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using Ryujinx.Graphics.Texture;
-
-namespace Ryujinx.Graphics.Gal.OpenGL
-{
- class ImageHandler
- {
- public GalImage Image { get; private set; }
-
- public int Width => Image.Width;
- public int Height => Image.Height;
- public int Depth => Image.Depth;
-
- public GalImageFormat Format => Image.Format;
-
- public int Handle { get; private set; }
-
- public bool HasColor => ImageUtils.HasColor(Image.Format);
- public bool HasDepth => ImageUtils.HasDepth(Image.Format);
- public bool HasStencil => ImageUtils.HasStencil(Image.Format);
-
- public ImageHandler(int handle, GalImage image)
- {
- Handle = handle;
- Image = image;
- }
- }
-}
diff --git a/Ryujinx.Graphics/Gal/OpenGL/OglCachedResource.cs b/Ryujinx.Graphics/Gal/OpenGL/OglCachedResource.cs
deleted file mode 100644
index 91f0a7e16..000000000
--- a/Ryujinx.Graphics/Gal/OpenGL/OglCachedResource.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-using Ryujinx.Common;
-using System;
-using System.Collections.Generic;
-
-namespace Ryujinx.Graphics.Gal.OpenGL
-{
- class OglCachedResource
- {
- public delegate void DeleteValue(T value);
-
- private const int MinTimeDelta = 5 * 60000;
- private const int MaxRemovalsPerRun = 10;
-
- private struct CacheBucket
- {
- public T Value { get; private set; }
-
- public LinkedListNode Node { get; private set; }
-
- public long DataSize { get; private set; }
-
- public long Timestamp { get; private set; }
-
- public CacheBucket(T value, long dataSize, LinkedListNode node)
- {
- Value = value;
- DataSize = dataSize;
- Node = node;
-
- Timestamp = PerformanceCounter.ElapsedMilliseconds;
- }
- }
-
- private Dictionary _cache;
-
- private LinkedList _sortedCache;
-
- private DeleteValue _deleteValueCallback;
-
- private Queue _deletePending;
-
- private bool _locked;
-
- private long _maxSize;
- private long _totalSize;
-
- public OglCachedResource(DeleteValue deleteValueCallback, long maxSize)
- {
- _maxSize = maxSize;
-
- if (deleteValueCallback == null)
- {
- throw new ArgumentNullException(nameof(deleteValueCallback));
- }
-
- _deleteValueCallback = deleteValueCallback;
-
- _cache = new Dictionary();
-
- _sortedCache = new LinkedList();
-
- _deletePending = new Queue