| 1 |
#include "GsTexture.h" |
| 2 |
#include "GsDevice.h" |
| 3 |
#include "GsStagingBuffer.h" |
| 4 |
|
| 5 |
#include "../../../../Main.h" |
| 6 |
|
| 7 |
#include <cstring> |
| 8 |
|
| 9 |
extern "C" { |
| 10 |
#include <draw.h> |
| 11 |
#include <dma.h> |
| 12 |
#include <gs_psm.h> |
| 13 |
} |
| 14 |
|
| 15 |
using namespace Death::Containers::Literals; |
| 16 |
|
| 17 |
namespace nCine::RHI::GS |
| 18 |
{ |
| 19 |
namespace |
| 20 |
{ |
| 21 |
/** @brief Words per page - `libgraph`/`libdraw` address local memory in 32-bit words, `GsVram` in pages */ |
| 22 |
constexpr std::uint32_t WordsPerPage = GsVram::PageBytes / 4; |
| 23 |
|
| 24 |
/** @brief Rounds a texture dimension up to the next power of two within the GS's [8, 1024] window */ |
| 25 |
std::int32_t NextPow2(std::int32_t value) |
| 26 |
{ |
| 27 |
std::int32_t result = 8; |
| 28 |
while (result < value && result < 1024) { |
| 29 |
result <<= 1; |
| 30 |
} |
| 31 |
return result; |
| 32 |
} |
| 33 |
|
| 34 |
/** @brief Rounds up to a multiple of @p alignment */ |
| 35 |
std::int32_t AlignUpInt(std::int32_t value, std::int32_t alignment) |
| 36 |
{ |
| 37 |
return (value + alignment - 1) / alignment * alignment; |
| 38 |
} |
| 39 |
|
| 40 |
/** @brief The hardware `PSM` value of a storage mode */ |
| 41 |
std::int32_t PsmToHardware(GsPsm psm) |
| 42 |
{ |
| 43 |
switch (psm) { |
| 44 |
case GsPsm::Ct32: return GS_PSM_32; |
| 45 |
case GsPsm::Ct24: return GS_PSM_24; |
| 46 |
case GsPsm::Ct16: return GS_PSM_16; |
| 47 |
case GsPsm::Ct16S: return GS_PSM_16S; |
| 48 |
case GsPsm::T8: return GS_PSM_8; |
| 49 |
case GsPsm::T4: return GS_PSM_4; |
| 50 |
default: return GS_PSM_32; |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
/** @brief Bits per texel of a storage mode, for sizing the staging buffer */ |
| 55 |
std::int32_t PsmBitsPerTexel(GsPsm psm) |
| 56 |
{ |
| 57 |
switch (psm) { |
| 58 |
case GsPsm::Ct32: |
| 59 |
case GsPsm::Ct24: return 32; |
| 60 |
case GsPsm::Ct16: |
| 61 |
case GsPsm::Ct16S: return 16; |
| 62 |
case GsPsm::T8: return 8; |
| 63 |
case GsPsm::T4: return 4; |
| 64 |
default: return 32; |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
@brief Staging buffer the transfers are issued from |
| 70 |
|
| 71 |
A transfer reads main memory directly, so the source has to be a contiguous, qword-aligned image |
| 72 |
in the destination's pitch - see @ref GsStagingBuffer for why an ordinary container is not that. |
| 73 |
*/ |
| 74 |
GsStagingBuffer _staging; |
| 75 |
|
| 76 |
/** |
| 77 |
@brief GIF packet scratch for the transfers |
| 78 |
|
| 79 |
Separate from anything the device builds, because a transfer is a DMA **chain** and cannot be |
| 80 |
appended to the device's ordinary register packet. That makes the ORDER between the two the |
| 81 |
caller's problem - see @ref TransferToLocalMemory(). |
| 82 |
*/ |
| 83 |
alignas(64) qword_t _uploadPacket[512]; |
| 84 |
|
| 85 |
/** |
| 86 |
@brief Transfers @p source into local memory at @p page |
| 87 |
|
| 88 |
`draw_texture_transfer()` emits DMA **tags** around the image data, so the packet it builds is a |
| 89 |
chain and has to go out with `dma_channel_send_chain()`. Sending it as a normal transfer hands |
| 90 |
those tags to the GIF as if they were pixels and wedges the channel with no error of any kind - |
| 91 |
this is the single most expensive mistake available on this path, so it is spelled out here rather |
| 92 |
than left to the reader of the call site. |
| 93 |
*/ |
| 94 |
void TransferToLocalMemory(const void* source, std::int32_t pitchTexels, std::int32_t height, |
| 95 |
GsPsm psm, std::uint32_t page) |
| 96 |
{ |
| 97 |
if (source == nullptr || pitchTexels <= 0 || height <= 0 || page == GsVram::InvalidPage) { |
| 98 |
return; |
| 99 |
} |
| 100 |
|
| 101 |
// The GS consumes GIF data in order, and this transfer goes out on its own channel packet, so |
| 102 |
// anything the device still has queued has to reach the GS FIRST. An upload is triggered from the |
| 103 |
// middle of the draw path whenever a store was evicted and has to be rebuilt - and without this |
| 104 |
// flush the transfer overtakes the draws already queued *behind* it, which then sample the new |
| 105 |
// store instead of the one they were submitted with. At 100% cache occupancy that happens several |
| 106 |
// times a frame, and it is what made the picture flash and sprites take other sprites' pixels. |
| 107 |
GsDevice::FlushPendingPackets(); |
| 108 |
|
| 109 |
// The chain below REFs the staging image rather than carrying it, so PS2SDK's own SyncDCache over |
| 110 |
// the chain does not reach it and the CPU's writes have to be pushed out here (see the |
| 111 |
// declaration of WritebackForDma - this is the intermittent-garbled-texture bug) |
| 112 |
GsDevice::WritebackForDma(source, |
| 113 |
(std::size_t(pitchTexels) * std::size_t(height) * std::size_t(PsmBitsPerTexel(psm))) / 8); |
| 114 |
|
| 115 |
qword_t* q = _uploadPacket; |
| 116 |
q = draw_texture_transfer(q, const_cast<void*>(source), pitchTexels, height, PsmToHardware(psm), |
| 117 |
std::int32_t(page * WordsPerPage), pitchTexels); |
| 118 |
q = draw_texture_flush(q); |
| 119 |
|
| 120 |
dma_channel_send_chain(DMA_CHANNEL_GIF, _uploadPacket, std::int32_t(q - _uploadPacket), 0, 0); |
| 121 |
dma_wait_fast(); |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
std::uint32_t GsTexture::_nextHandle = 1; |
| 126 |
std::uint32_t GsTexture::_nextContentVersion = 0; |
| 127 |
GsTexture* GsTexture::_liveHead = nullptr; |
| 128 |
GsTexture* GsTexture::_liveTail = nullptr; |
| 129 |
|
| 130 |
GsTexture::GsTexture(TextureTarget target) |
| 131 |
: _handle(_nextHandle++), _contentVersion(0), _target(target), _format(PixelFormat::Unknown), |
| 132 |
_uploadFormat(PixelFormat::Unknown), _width(0), _height(0), _strideBytes(0), _bytesPerPixel(0), |
| 133 |
_minFilter(nCine::SamplerFilter::Nearest), _magFilter(nCine::SamplerFilter::Nearest), |
| 134 |
_wrap(SamplerWrapping::ClampToEdge), _textureUnit(0), _isRenderTarget(false), _isPaletteTexture(false), |
| 135 |
_page(GsVram::InvalidPage), _pageCount(0), _pageFromReserve(false), _psm(GsPsm::Ct32), _bufferPitch(0), |
| 136 |
_paddedWidth(0), _paddedHeight(0), _uScale(1.0f), _vScale(1.0f), |
| 137 |
_bakedSlots{}, _nextBakedSlot(0), _livePrev(nullptr), _liveNext(nullptr), _lastUsedFrame(NeverUsed) |
| 138 |
{ |
| 139 |
_swizzle[0] = SwizzleChannel::Red; |
| 140 |
_swizzle[1] = SwizzleChannel::Green; |
| 141 |
_swizzle[2] = SwizzleChannel::Blue; |
| 142 |
_swizzle[3] = SwizzleChannel::Alpha; |
| 143 |
} |
| 144 |
|
| 145 |
GsTexture::~GsTexture() |
| 146 |
{ |
| 147 |
GsDevice::UnbindTexture(this); |
| 148 |
FreeStores(); |
| 149 |
Unlink(); |
| 150 |
} |
| 151 |
|
| 152 |
// ---- Most-recently-used list ------------------------------------------------------------------ |
| 153 |
|
| 154 |
void GsTexture::Unlink() |
| 155 |
{ |
| 156 |
if (_livePrev != nullptr) { |
| 157 |
_livePrev->_liveNext = _liveNext; |
| 158 |
} else if (_liveHead == this) { |
| 159 |
_liveHead = _liveNext; |
| 160 |
} |
| 161 |
if (_liveNext != nullptr) { |
| 162 |
_liveNext->_livePrev = _livePrev; |
| 163 |
} else if (_liveTail == this) { |
| 164 |
_liveTail = _livePrev; |
| 165 |
} |
| 166 |
_livePrev = nullptr; |
| 167 |
_liveNext = nullptr; |
| 168 |
} |
| 169 |
|
| 170 |
void GsTexture::Touch() |
| 171 |
{ |
| 172 |
_lastUsedFrame = GsDevice::GetFrameCounter(); |
| 173 |
if (_liveHead == this) { |
| 174 |
return; |
| 175 |
} |
| 176 |
Unlink(); |
| 177 |
_liveNext = _liveHead; |
| 178 |
if (_liveHead != nullptr) { |
| 179 |
_liveHead->_livePrev = this; |
| 180 |
} |
| 181 |
_liveHead = this; |
| 182 |
if (_liveTail == nullptr) { |
| 183 |
_liveTail = this; |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
void GsTexture::LinkAsLeastRecent() |
| 188 |
{ |
| 189 |
if (_livePrev != nullptr || _liveNext != nullptr || _liveHead == this) { |
| 190 |
return; // Already in the list, keep its position (and its frame stamp) |
| 191 |
} |
| 192 |
_livePrev = _liveTail; |
| 193 |
if (_liveTail != nullptr) { |
| 194 |
_liveTail->_liveNext = this; |
| 195 |
} |
| 196 |
_liveTail = this; |
| 197 |
if (_liveHead == nullptr) { |
| 198 |
_liveHead = this; |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
std::uint32_t GsTexture::AllocatePages(std::uint32_t pageCount, const GsTexture* keepAlive) |
| 203 |
{ |
| 204 |
if (std::uint32_t result = GsVram::AllocatePages(pageCount); result != GsVram::InvalidPage) { |
| 205 |
return result; |
| 206 |
} |
| 207 |
|
| 208 |
const std::uint32_t currentFrame = GsDevice::GetFrameCounter(); |
| 209 |
|
| 210 |
// Out of local memory. Before dropping any STORE, drop the palette bakes that were not read this |
| 211 |
// frame: a bake is a PSMCT32 expansion of an RG8 store - four bytes a texel where the source is two, |
| 212 |
// and up to BakedSlotCount of them per texture - so it is by far the most local memory per texel in |
| 213 |
// the cache, and it is the cheapest thing to lose. Rebuilding one costs a CPU pass over the texels; |
| 214 |
// rebuilding a store costs that too, for every texture the store's eviction then displaces. Slots |
| 215 |
// read this frame are spared for the reason the store walk below spares this frame's stores. |
| 216 |
for (GsTexture* texture = _liveTail; texture != nullptr; texture = texture->_livePrev) { |
| 217 |
for (std::int32_t i = 0; i < BakedSlotCount; i++) { |
| 218 |
BakedSlot& slot = texture->_bakedSlots[i]; |
| 219 |
if (slot.Page == GsVram::InvalidPage || slot.LastUsedFrame == currentFrame) { |
| 220 |
continue; |
| 221 |
} |
| 222 |
GsVram::FreePages(slot.Page, slot.PageCount); |
| 223 |
slot.Page = GsVram::InvalidPage; |
| 224 |
slot.PageCount = 0; |
| 225 |
slot.Valid = false; |
| 226 |
|
| 227 |
if (std::uint32_t result = GsVram::AllocatePages(pageCount); result != GsVram::InvalidPage) { |
| 228 |
return result; |
| 229 |
} |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
// Still short: drop the stores of the textures that have gone unused the longest and try again. The |
| 234 |
// first pass spares anything already drawn into the frame being assembled, because the GS may still |
| 235 |
// be reading it - a GIF packet already handed to the DMA controller is not done yet. |
| 236 |
for (std::int32_t pass = 0; pass < 2; pass++) { |
| 237 |
// Nothing outside the current frame was left to free. Rather than fail the allocation - which |
| 238 |
// happens when a level's working set suddenly has to make room for the pause menu's - the second |
| 239 |
// pass evicts from the current frame too. Primitives already submitted this frame can then sample |
| 240 |
// a store that has been reused, so they can come out wrong; that is a single frame of artifacts |
| 241 |
// against a texture that never appears, and the store is re-transferred on the next draw. |
| 242 |
const bool sparingCurrentFrame = (pass == 0); |
| 243 |
GsTexture* victim = _liveTail; |
| 244 |
while (victim != nullptr) { |
| 245 |
GsTexture* next = victim->_livePrev; |
| 246 |
// Render targets have no copy in main memory to rebuild from, so they are never evicted. |
| 247 |
// Usually they are not in this window at all, but one too large for the reserve is (see |
| 248 |
// SetRenderTarget), and that one has to be spared here rather than by where it happens to live |
| 249 |
const bool evictable = (victim != keepAlive && !victim->_isRenderTarget && |
| 250 |
(!sparingCurrentFrame || victim->_lastUsedFrame != currentFrame)); |
| 251 |
if (evictable) { |
| 252 |
victim->FreeStores(); |
| 253 |
victim->Unlink(); |
| 254 |
|
| 255 |
if (std::uint32_t result = GsVram::AllocatePages(pageCount); result != GsVram::InvalidPage) { |
| 256 |
return result; |
| 257 |
} |
| 258 |
} |
| 259 |
victim = next; |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
return GsVram::InvalidPage; |
| 264 |
} |
| 265 |
|
| 266 |
// ---- Storage layout -------------------------------------------------------------------------- |
| 267 |
|
| 268 |
void GsTexture::ResolveStorage(GsPsm& psm, std::int32_t& bufferPitch, std::uint32_t& pageCount) const |
| 269 |
{ |
| 270 |
switch (_uploadFormat) { |
| 271 |
case PixelFormat::R8: |
| 272 |
// Indices sample straight through a CLUT the device selects per draw |
| 273 |
psm = GsPsm::T8; |
| 274 |
break; |
| 275 |
case PixelFormat::RGB565: |
| 276 |
// NOT PSMCT16: the GS's 16-bit colour mode is RGBA**5551**, not RGB565 - five bits of green |
| 277 |
// instead of six, and an alpha bit where green's low bit used to be. Storing 565 texels there |
| 278 |
// verbatim shifts every channel and comes out as a wrong palette, which is exactly how the |
| 279 |
// cinematics looked. The texels are expanded to PSMCT32 on upload instead; the cinematic |
| 280 |
// player is the only user and one full-screen frame is 1120 KB against a 2816 KB cache, so |
| 281 |
// the cost is affordable where the corruption was not. |
| 282 |
psm = GsPsm::Ct32; |
| 283 |
break; |
| 284 |
default: |
| 285 |
// RGB8 / RGBA8, and the RG8 bakes. The GS samples 32-bit natively, so unlike the PowerVR |
| 286 |
// there is no precision loss here; PSMCT16 would halve the cost but its single alpha bit is |
| 287 |
// useless for blended sprite art |
| 288 |
psm = GsPsm::Ct32; |
| 289 |
break; |
| 290 |
} |
| 291 |
|
| 292 |
// The store only has to COVER the real image, not the sampled extent. `TEX0.TBW` is the pitch and |
| 293 |
// `TW`/`TH` are the sampled power-of-two extent, and they are INDEPENDENT fields - so padding the |
| 294 |
// store to the sampled size as well wasted up to 37% of every texture (a 640x480 sheet was stored as |
| 295 |
// 1024x512, 64 pages where 40 will do). That waste is what put a level's working set over the cache: |
| 296 |
// at 100% occupancy the allocator starts refusing pages, a refused page skips the draw, and whole |
| 297 |
// groups of sprites - the HUD first, since it is drawn last - dropped out on alternate frames. |
| 298 |
// |
| 299 |
// The pitch rounds up to the page width (which is also a multiple of the 64-texel TBW unit) and the |
| 300 |
// height to the page height, because a page is the allocation unit. |
| 301 |
bufferPitch = GsVram::GetPaddedWidth(psm, _width); |
| 302 |
pageCount = GsVram::GetPageCount(psm, bufferPitch, ResolveStoreHeight(psm)); |
| 303 |
} |
| 304 |
|
| 305 |
std::int32_t GsTexture::ResolveStoreHeight(GsPsm psm) const |
| 306 |
{ |
| 307 |
std::int32_t pageWidth, pageHeight; |
| 308 |
GsVram::GetPageGeometry(psm, pageWidth, pageHeight); |
| 309 |
return AlignUpInt(_height, pageHeight); |
| 310 |
} |
| 311 |
|
| 312 |
bool GsTexture::EnsureStore() |
| 313 |
{ |
| 314 |
GsPsm psm; |
| 315 |
std::int32_t bufferPitch; |
| 316 |
std::uint32_t pageCount; |
| 317 |
ResolveStorage(psm, bufferPitch, pageCount); |
| 318 |
|
| 319 |
// A texture does not always end up in the storage mode it was first uploaded in - a true-colour one |
| 320 |
// that turns out to fit a colour table becomes indexed and shrinks fourfold - and writing the new |
| 321 |
// mode into the old allocation would either waste most of it or run past its end |
| 322 |
if (_page != GsVram::InvalidPage && (_psm != psm || _pageCount != pageCount)) { |
| 323 |
GsVram::FreePages(_page, _pageCount); |
| 324 |
_page = GsVram::InvalidPage; |
| 325 |
_pageCount = 0; |
| 326 |
} |
| 327 |
|
| 328 |
if (_page == GsVram::InvalidPage) { |
| 329 |
_page = AllocatePages(pageCount, this); |
| 330 |
if (_page == GsVram::InvalidPage) { |
| 331 |
return false; |
| 332 |
} |
| 333 |
_pageCount = pageCount; |
| 334 |
_pageFromReserve = false; |
| 335 |
} |
| 336 |
|
| 337 |
_psm = psm; |
| 338 |
_bufferPitch = bufferPitch; |
| 339 |
// The store has to be reachable by the eviction walk immediately, not only from the first draw |
| 340 |
LinkAsLeastRecent(); |
| 341 |
return true; |
| 342 |
} |
| 343 |
|
| 344 |
void GsTexture::RefreshStore() |
| 345 |
{ |
| 346 |
if (_pixels.empty() || _width <= 0 || _height <= 0 || _isPaletteTexture || _isRenderTarget) { |
| 347 |
return; |
| 348 |
} |
| 349 |
|
| 350 |
if (!EnsureStore()) { |
| 351 |
LOGE("Out of GS local memory for a {}x{} texture ({} pages)", _width, _height, _pageCount); |
| 352 |
return; |
| 353 |
} |
| 354 |
|
| 355 |
const std::int32_t storeHeight = ResolveStoreHeight(_psm); |
| 356 |
const std::int32_t bytesPerTexel = PsmBitsPerTexel(_psm) / 8; |
| 357 |
|
| 358 |
// Pad the linear image into a staging buffer in the destination's pitch. The GS does the block |
| 359 |
// swizzling on the way in, so the source stays plain raster order - the Dreamcast's twiddling pass |
| 360 |
// has no counterpart here. Only the padding is cleared; the image area is overwritten right after. |
| 361 |
const std::size_t stagingSize = std::size_t(_bufferPitch) * std::size_t(storeHeight) * std::size_t(bytesPerTexel); |
| 362 |
std::uint8_t* const staging = _staging.Reserve(stagingSize); |
| 363 |
if (staging == nullptr) { |
| 364 |
LOGE("Out of main memory for a {}x{} texture upload ({} bytes)", _width, _height, stagingSize); |
| 365 |
return; |
| 366 |
} |
| 367 |
const std::int32_t dstRowBytes = _bufferPitch * bytesPerTexel; |
| 368 |
|
| 369 |
if (_uploadFormat == PixelFormat::R8) { |
| 370 |
for (std::int32_t y = 0; y < _height; y++) { |
| 371 |
std::uint8_t* dstRow = staging + std::size_t(y) * dstRowBytes; |
| 372 |
std::memcpy(dstRow, _pixels.data() + std::size_t(y) * _strideBytes, std::size_t(_width)); |
| 373 |
std::memset(dstRow + _width, 0, std::size_t(dstRowBytes - _width)); |
| 374 |
} |
| 375 |
} else if (_uploadFormat == PixelFormat::RGB565) { |
| 376 |
// Expand 565 to the GS's PSMCT32; the low bits are replicated so that full-scale input stays |
| 377 |
// full-scale output rather than topping out at 248/252 |
| 378 |
for (std::int32_t y = 0; y < _height; y++) { |
| 379 |
std::uint32_t* dstRow = reinterpret_cast<std::uint32_t*>(staging + std::size_t(y) * dstRowBytes); |
| 380 |
const std::uint16_t* srcRow = reinterpret_cast<const std::uint16_t*>(_pixels.data() + std::size_t(y) * _strideBytes); |
| 381 |
for (std::int32_t x = 0; x < _width; x++) { |
| 382 |
const std::uint32_t texel = srcRow[x]; |
| 383 |
const std::uint32_t r5 = (texel >> 11) & 0x1F; |
| 384 |
const std::uint32_t g6 = (texel >> 5) & 0x3F; |
| 385 |
const std::uint32_t b5 = texel & 0x1F; |
| 386 |
const std::uint32_t r = (r5 << 3) | (r5 >> 2); |
| 387 |
const std::uint32_t g = (g6 << 2) | (g6 >> 4); |
| 388 |
const std::uint32_t b = (b5 << 3) | (b5 >> 2); |
| 389 |
// 0x80 is fully opaque in the GS's alpha convention, not 0xFF |
| 390 |
dstRow[x] = r | (g << 8) | (b << 16) | (0x80u << 24); |
| 391 |
} |
| 392 |
std::memset(dstRow + _width, 0, std::size_t(dstRowBytes) - std::size_t(_width) * 4); |
| 393 |
} |
| 394 |
} else { |
| 395 |
// RGB8 / RGBA8 expand to PSMCT32, which is what the GS samples |
| 396 |
const std::int32_t srcBytes = _bytesPerPixel; |
| 397 |
for (std::int32_t y = 0; y < _height; y++) { |
| 398 |
std::uint32_t* dstRow = reinterpret_cast<std::uint32_t*>(staging + std::size_t(y) * dstRowBytes); |
| 399 |
const std::uint8_t* srcRow = _pixels.data() + std::size_t(y) * _strideBytes; |
| 400 |
for (std::int32_t x = 0; x < _width; x++) { |
| 401 |
const std::uint8_t* t = srcRow + std::size_t(x) * srcBytes; |
| 402 |
// The GS treats 0x80 as fully opaque, so an 8-bit alpha is halved rather than copied - |
| 403 |
// passing 0xFF through would read as "twice opaque" and clamp oddly in blending |
| 404 |
const std::uint32_t a = (srcBytes >= 4 ? (std::uint32_t(t[3]) + 1) >> 1 : 0x80); |
| 405 |
dstRow[x] = std::uint32_t(t[0]) | (std::uint32_t(t[1]) << 8) | (std::uint32_t(t[2]) << 16) | (a << 24); |
| 406 |
} |
| 407 |
std::memset(dstRow + _width, 0, std::size_t(dstRowBytes) - std::size_t(_width) * 4); |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
if (_height < storeHeight) { |
| 412 |
std::memset(staging + std::size_t(_height) * dstRowBytes, 0, |
| 413 |
std::size_t(storeHeight - _height) * std::size_t(dstRowBytes)); |
| 414 |
} |
| 415 |
|
| 416 |
TransferToLocalMemory(staging, _bufferPitch, storeHeight, _psm, _page); |
| 417 |
} |
| 418 |
|
| 419 |
std::uint32_t GsTexture::AcquireTexturePage() |
| 420 |
{ |
| 421 |
if (_page == GsVram::InvalidPage) { |
| 422 |
RefreshStore(); |
| 423 |
} |
| 424 |
if (_page != GsVram::InvalidPage) { |
| 425 |
Touch(); |
| 426 |
} |
| 427 |
return _page; |
| 428 |
} |
| 429 |
|
| 430 |
void GsTexture::FreeStores() |
| 431 |
{ |
| 432 |
if (_page != GsVram::InvalidPage) { |
| 433 |
// Which pool it came from, not which pool its kind prefers - a render target too large for the |
| 434 |
// reserve is holding cache pages and returning those to the reserve would corrupt both |
| 435 |
if (_pageFromReserve) { |
| 436 |
GsVram::FreeReservedPages(_page, _pageCount); |
| 437 |
} else { |
| 438 |
GsVram::FreePages(_page, _pageCount); |
| 439 |
} |
| 440 |
_page = GsVram::InvalidPage; |
| 441 |
_pageCount = 0; |
| 442 |
_pageFromReserve = false; |
| 443 |
} |
| 444 |
for (std::int32_t i = 0; i < BakedSlotCount; i++) { |
| 445 |
if (_bakedSlots[i].Page != GsVram::InvalidPage) { |
| 446 |
GsVram::FreePages(_bakedSlots[i].Page, _bakedSlots[i].PageCount); |
| 447 |
_bakedSlots[i].Page = GsVram::InvalidPage; |
| 448 |
_bakedSlots[i].PageCount = 0; |
| 449 |
} |
| 450 |
_bakedSlots[i].Valid = false; |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
// ---- Allocation and uploads ----------------------------------------------------------------- |
| 455 |
|
| 456 |
std::int32_t GsTexture::BytesPerPixel(PixelFormat format) |
| 457 |
{ |
| 458 |
switch (format) { |
| 459 |
case PixelFormat::R8: return 1; |
| 460 |
case PixelFormat::RG8: return 2; |
| 461 |
case PixelFormat::RGB565: return 2; |
| 462 |
case PixelFormat::RGB8: return 3; |
| 463 |
case PixelFormat::RGBA8: return 4; |
| 464 |
default: return 0; |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
void GsTexture::Allocate(PixelFormat format, std::int32_t width, std::int32_t height) |
| 469 |
{ |
| 470 |
_uploadFormat = format; |
| 471 |
_format = format; |
| 472 |
_width = width; |
| 473 |
_height = height; |
| 474 |
_bytesPerPixel = BytesPerPixel(_format); |
| 475 |
_strideBytes = width * _bytesPerPixel; |
| 476 |
_pixels.assign(std::size_t(_strideBytes) * std::size_t(height > 0 ? height : 0), std::uint8_t(0)); |
| 477 |
FreeStores(); |
| 478 |
|
| 479 |
// `TEX0.TW`/`TH` are log2 fields, so the sampled extent is always a power of two and the texture |
| 480 |
// coordinates are compensated for it - the same as on the PowerVR. Note this is NOT the storage |
| 481 |
// pitch: `TBW` is a separate field, so padding the pitch to the page geometry costs memory but no |
| 482 |
// coordinate scaling at all (see GsVram::GetPaddedWidth). |
| 483 |
_paddedWidth = NextPow2(width); |
| 484 |
_paddedHeight = NextPow2(height); |
| 485 |
_uScale = (_paddedWidth > 0 ? float(width) / float(_paddedWidth) : 1.0f); |
| 486 |
_vScale = (_paddedHeight > 0 ? float(height) / float(_paddedHeight) : 1.0f); |
| 487 |
if (width > 1024 || height > 1024) { |
| 488 |
LOGE("Texture {}x{} exceeds the GS 1024 limit", width, height); |
| 489 |
} |
| 490 |
_contentVersion = ++_nextContentVersion; |
| 491 |
} |
| 492 |
|
| 493 |
void GsTexture::TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data) |
| 494 |
{ |
| 495 |
static_cast<void>(bgr); |
| 496 |
if (level != 0) { |
| 497 |
return; // Mip levels above 0 are accepted but not stored |
| 498 |
} |
| 499 |
|
| 500 |
Allocate(format, width, height); |
| 501 |
if (data != nullptr && RawPixelsSize() > 0) { |
| 502 |
std::memcpy(_pixels.data(), data, std::size_t(RawPixelsSize())); |
| 503 |
_contentVersion = ++_nextContentVersion; |
| 504 |
} |
| 505 |
// The shared palette texture keeps no store of its own - its rows become CLUTs the device loads on |
| 506 |
// demand - so an upload has to invalidate whatever it already loaded from them instead. Without this |
| 507 |
// a level's palette never reached the hardware: the resident CLUTs and RG8 bakes still held the |
| 508 |
// previous screen's colours, which is what made a level inherit the main menu's palette. |
| 509 |
if (_isPaletteTexture) { |
| 510 |
GsDevice::NotifyPaletteTextureChanged(this, 0, _height); |
| 511 |
} else if (data != nullptr && RawPixelsSize() > 0) { |
| 512 |
RefreshStore(); |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
void GsTexture::TexSubImage2D(std::int32_t level, std::int32_t xoffset, std::int32_t yoffset, std::int32_t width, std::int32_t height, PixelFormat format, bool bgr, const void* data) |
| 517 |
{ |
| 518 |
static_cast<void>(format); |
| 519 |
static_cast<void>(bgr); |
| 520 |
if (level != 0 || data == nullptr || _pixels.empty() || width <= 0 || height <= 0) { |
| 521 |
return; |
| 522 |
} |
| 523 |
if (xoffset < 0 || yoffset < 0 || xoffset + width > _width || yoffset + height > _height) { |
| 524 |
return; |
| 525 |
} |
| 526 |
|
| 527 |
const std::int32_t rowBytes = width * _bytesPerPixel; |
| 528 |
for (std::int32_t y = 0; y < height; y++) { |
| 529 |
std::memcpy(_pixels.data() + std::size_t(yoffset + y) * _strideBytes + std::size_t(xoffset) * _bytesPerPixel, |
| 530 |
static_cast<const std::uint8_t*>(data) + std::size_t(y) * rowBytes, std::size_t(rowBytes)); |
| 531 |
} |
| 532 |
|
| 533 |
_contentVersion = ++_nextContentVersion; |
| 534 |
if (_isPaletteTexture) { |
| 535 |
// Only the rows that changed, so a palette animation does not evict every resident CLUT |
| 536 |
GsDevice::NotifyPaletteTextureChanged(this, yoffset, height); |
| 537 |
return; |
| 538 |
} |
| 539 |
// The whole store is re-transferred rather than the patched rectangle: a partial transfer would have |
| 540 |
// to reproduce the destination's page swizzle to place the sub-rectangle, and the sub-uploads that |
| 541 |
// exist (tileset overrides) happen at load time, not per frame |
| 542 |
RefreshStore(); |
| 543 |
} |
| 544 |
|
| 545 |
void GsTexture::TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height) |
| 546 |
{ |
| 547 |
static_cast<void>(levels); |
| 548 |
Allocate(format, width, height); |
| 549 |
} |
| 550 |
|
| 551 |
void GsTexture::CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data) |
| 552 |
{ |
| 553 |
static_cast<void>(level); |
| 554 |
static_cast<void>(format); |
| 555 |
static_cast<void>(width); |
| 556 |
static_cast<void>(height); |
| 557 |
static_cast<void>(imageSize); |
| 558 |
static_cast<void>(data); |
| 559 |
} |
| 560 |
|
| 561 |
void GsTexture::CompressedTexSubImage2D(std::int32_t level, std::int32_t xoffset, std::int32_t yoffset, std::int32_t width, std::int32_t height, PixelFormat format, std::int32_t imageSize, const void* data) |
| 562 |
{ |
| 563 |
static_cast<void>(level); |
| 564 |
static_cast<void>(xoffset); |
| 565 |
static_cast<void>(yoffset); |
| 566 |
static_cast<void>(width); |
| 567 |
static_cast<void>(height); |
| 568 |
static_cast<void>(format); |
| 569 |
static_cast<void>(imageSize); |
| 570 |
static_cast<void>(data); |
| 571 |
} |
| 572 |
|
| 573 |
void GsTexture::GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels) |
| 574 |
{ |
| 575 |
static_cast<void>(format); |
| 576 |
static_cast<void>(bgr); |
| 577 |
if (level != 0 || pixels == nullptr || _pixels.empty()) { |
| 578 |
return; |
| 579 |
} |
| 580 |
std::memcpy(pixels, _pixels.data(), std::size_t(RawPixelsSize())); |
| 581 |
} |
| 582 |
|
| 583 |
// ---- Render target --------------------------------------------------------------------------- |
| 584 |
|
| 585 |
void GsTexture::SetRenderTarget(bool isRenderTarget) |
| 586 |
{ |
| 587 |
if (_isRenderTarget == isRenderTarget) { |
| 588 |
return; |
| 589 |
} |
| 590 |
|
| 591 |
FreeStores(); |
| 592 |
_isRenderTarget = isRenderTarget; |
| 593 |
if (!_isRenderTarget) { |
| 594 |
return; |
| 595 |
} |
| 596 |
|
| 597 |
// A render target is a colour surface the rasterizer writes into, so it takes PSMCT16 pages out of |
| 598 |
// the reserve. It has no host copy, which is why it must never be evicted - and why it goes to the |
| 599 |
// reserve rather than the cache: there it cannot be crowded out by streaming sheets. |
| 600 |
_psm = GsPsm::Ct16; |
| 601 |
_bufferPitch = GsVram::GetPaddedWidth(_psm, _paddedWidth); |
| 602 |
|
| 603 |
std::int32_t pageWidth, pageHeight; |
| 604 |
GsVram::GetPageGeometry(_psm, pageWidth, pageHeight); |
| 605 |
const std::int32_t storeHeight = AlignUpInt(_paddedHeight, pageHeight); |
| 606 |
_pageCount = GsVram::GetPageCount(_psm, _bufferPitch, storeHeight); |
| 607 |
|
| 608 |
_page = GsVram::AllocateReservedPages(_pageCount); |
| 609 |
_pageFromReserve = (_page != GsVram::InvalidPage); |
| 610 |
if (!_pageFromReserve) { |
| 611 |
// The reserve is sized for the target the levels usually ask for, and the size is not the |
| 612 |
// backend's to choose: TexturedBackgroundPass makes its target as large as the level's textured |
| 613 |
// layer, so a level with a 512x256 one wants 32 pages where an ordinary 256x256 wants 16. |
| 614 |
// Failing here would silently drop the whole background, so a target too large for the reserve |
| 615 |
// takes cache pages instead - evicting streaming sheets to get them if it has to. It is still |
| 616 |
// exempt from the eviction walk afterwards (AllocatePages() spares render targets), which is the |
| 617 |
// property that actually matters; all it loses is the guarantee of not competing for the window. |
| 618 |
_page = AllocatePages(_pageCount, this); |
| 619 |
if (_page == GsVram::InvalidPage) { |
| 620 |
LOGE("No room in GS local memory for a {}x{} render target ({} pages)", |
| 621 |
_paddedWidth, _paddedHeight, _pageCount); |
| 622 |
_pageCount = 0; |
| 623 |
} else { |
| 624 |
LOGW("A {}x{} render target ({} pages) does not fit the GS reserve and took cache pages instead", |
| 625 |
_paddedWidth, _paddedHeight, _pageCount); |
| 626 |
} |
| 627 |
} |
| 628 |
} |
| 629 |
|
| 630 |
// ---- Per-palette-row bake (RG8) -------------------------------------------------------------- |
| 631 |
|
| 632 |
std::uint32_t GsTexture::EnsureBakedColor(const std::uint32_t* paletteRow, std::uint32_t paletteRowIndex, |
| 633 |
std::uint32_t paletteGeneration, const void* palette) |
| 634 |
{ |
| 635 |
if (!NeedsPaletteBake() || paletteRow == nullptr || _pixels.empty() || _width <= 0 || _height <= 0) { |
| 636 |
return GsVram::InvalidPage; |
| 637 |
} |
| 638 |
|
| 639 |
const std::uint32_t currentFrame = GsDevice::GetFrameCounter(); |
| 640 |
|
| 641 |
// A slot already holding this row with the same palette contents and texel version is a hit |
| 642 |
for (std::int32_t i = 0; i < BakedSlotCount; i++) { |
| 643 |
BakedSlot& slot = _bakedSlots[i]; |
| 644 |
if (slot.Valid && slot.Page != GsVram::InvalidPage && slot.PaletteRow == paletteRowIndex && |
| 645 |
slot.PaletteGeneration == paletteGeneration && slot.ContentVersion == _contentVersion && |
| 646 |
slot.Palette == palette) { |
| 647 |
slot.LastUsedFrame = currentFrame; |
| 648 |
Touch(); |
| 649 |
return slot.Page; |
| 650 |
} |
| 651 |
} |
| 652 |
|
| 653 |
// Otherwise take the slot that has gone unused the longest, but never one used this frame - the GS |
| 654 |
// may still be reading it for a primitive already submitted |
| 655 |
BakedSlot* target = nullptr; |
| 656 |
for (std::int32_t i = 0; i < BakedSlotCount; i++) { |
| 657 |
BakedSlot& slot = _bakedSlots[i]; |
| 658 |
if (slot.LastUsedFrame == currentFrame && slot.Valid) { |
| 659 |
continue; |
| 660 |
} |
| 661 |
if (target == nullptr || slot.LastUsedFrame < target->LastUsedFrame) { |
| 662 |
target = &slot; |
| 663 |
} |
| 664 |
} |
| 665 |
if (target == nullptr) { |
| 666 |
// Every slot is in use this frame; round-robin and accept that the oldest of them may flicker |
| 667 |
target = &_bakedSlots[_nextBakedSlot]; |
| 668 |
_nextBakedSlot = (_nextBakedSlot + 1) % BakedSlotCount; |
| 669 |
} |
| 670 |
|
| 671 |
const std::int32_t bakedPitch = GsVram::GetPaddedWidth(GsPsm::Ct32, _width); |
| 672 |
const std::int32_t storeHeight = ResolveStoreHeight(GsPsm::Ct32); |
| 673 |
const std::uint32_t pageCount = GsVram::GetPageCount(GsPsm::Ct32, bakedPitch, storeHeight); |
| 674 |
|
| 675 |
if (target->Page != GsVram::InvalidPage && target->PageCount != pageCount) { |
| 676 |
GsVram::FreePages(target->Page, target->PageCount); |
| 677 |
target->Page = GsVram::InvalidPage; |
| 678 |
target->PageCount = 0; |
| 679 |
} |
| 680 |
if (target->Page == GsVram::InvalidPage) { |
| 681 |
target->Page = AllocatePages(pageCount, this); |
| 682 |
if (target->Page == GsVram::InvalidPage) { |
| 683 |
target->Valid = false; |
| 684 |
return GsVram::InvalidPage; |
| 685 |
} |
| 686 |
target->PageCount = pageCount; |
| 687 |
} |
| 688 |
|
| 689 |
// Resolve every index through the row, keeping the texel's own alpha - the reason this bake exists at |
| 690 |
// all is that a PSMT8 texel could only take its alpha from the CLUT entry |
| 691 |
const std::size_t stagingSize = std::size_t(bakedPitch) * std::size_t(storeHeight) * 4; |
| 692 |
std::uint8_t* const staging = _staging.Reserve(stagingSize); |
| 693 |
if (staging == nullptr) { |
| 694 |
target->Valid = false; |
| 695 |
return GsVram::InvalidPage; |
| 696 |
} |
| 697 |
for (std::int32_t y = 0; y < _height; y++) { |
| 698 |
std::uint32_t* dstRow = reinterpret_cast<std::uint32_t*>(staging + std::size_t(y) * bakedPitch * 4); |
| 699 |
const std::uint8_t* srcRow = _pixels.data() + std::size_t(y) * _strideBytes; |
| 700 |
for (std::int32_t x = 0; x < _width; x++) { |
| 701 |
const std::uint32_t entry = paletteRow[srcRow[std::size_t(x) * 2]]; |
| 702 |
// Halved into the GS's alpha convention, where 0x80 - not 0xFF - is fully opaque, exactly as |
| 703 |
// the RGBA8 path and the CLUT upload do. Copying the byte through instead made every texel at |
| 704 |
// or above half alpha come out fully opaque (the blend's `>> 7` saturates), which is what left |
| 705 |
// the per-pixel-alpha sprites - the glows, the shields, the fades - looking like cutouts. |
| 706 |
const std::uint32_t alpha = (std::uint32_t(srcRow[std::size_t(x) * 2 + 1]) + 1) >> 1; |
| 707 |
dstRow[x] = (entry & 0x00FFFFFFu) | (alpha << 24); |
| 708 |
} |
| 709 |
std::memset(dstRow + _width, 0, (std::size_t(bakedPitch) - std::size_t(_width)) * 4); |
| 710 |
} |
| 711 |
if (_height < storeHeight) { |
| 712 |
std::memset(staging + std::size_t(_height) * bakedPitch * 4, 0, |
| 713 |
std::size_t(storeHeight - _height) * std::size_t(bakedPitch) * 4); |
| 714 |
} |
| 715 |
|
| 716 |
TransferToLocalMemory(staging, bakedPitch, storeHeight, GsPsm::Ct32, target->Page); |
| 717 |
|
| 718 |
target->Valid = true; |
| 719 |
target->PaletteRow = paletteRowIndex; |
| 720 |
target->PaletteGeneration = paletteGeneration; |
| 721 |
target->ContentVersion = _contentVersion; |
| 722 |
target->Palette = palette; |
| 723 |
target->LastUsedFrame = currentFrame; |
| 724 |
LinkAsLeastRecent(); |
| 725 |
Touch(); |
| 726 |
return target->Page; |
| 727 |
} |
| 728 |
|
| 729 |
// ---- Sampler state and binding --------------------------------------------------------------- |
| 730 |
|
| 731 |
void* GsTexture::MapStreamingTexels(std::int32_t& strideBytes) |
| 732 |
{ |
| 733 |
// The GS has no host mapping of its local memory - see the declaration |
| 734 |
strideBytes = 0; |
| 735 |
return nullptr; |
| 736 |
} |
| 737 |
|
| 738 |
bool GsTexture::Bind(std::uint32_t textureUnit) const |
| 739 |
{ |
| 740 |
if (textureUnit >= MaxTextureUnits) { |
| 741 |
return false; |
| 742 |
} |
| 743 |
_textureUnit = textureUnit; |
| 744 |
GsDevice::BindTexture(textureUnit, this); |
| 745 |
return true; |
| 746 |
} |
| 747 |
|
| 748 |
bool GsTexture::Unbind() const |
| 749 |
{ |
| 750 |
return Unbind(_textureUnit); |
| 751 |
} |
| 752 |
|
| 753 |
bool GsTexture::Unbind(std::uint32_t textureUnit) |
| 754 |
{ |
| 755 |
if (textureUnit >= MaxTextureUnits) { |
| 756 |
return false; |
| 757 |
} |
| 758 |
GsDevice::BindTexture(textureUnit, nullptr); |
| 759 |
return true; |
| 760 |
} |
| 761 |
|
| 762 |
void GsTexture::SetMinFiltering(nCine::SamplerFilter filter) |
| 763 |
{ |
| 764 |
_minFilter = filter; |
| 765 |
} |
| 766 |
|
| 767 |
void GsTexture::SetMagFiltering(nCine::SamplerFilter filter) |
| 768 |
{ |
| 769 |
_magFilter = filter; |
| 770 |
} |
| 771 |
|
| 772 |
void GsTexture::SetWrap(SamplerWrapping wrap) |
| 773 |
{ |
| 774 |
_wrap = wrap; |
| 775 |
} |
| 776 |
|
| 777 |
void GsTexture::SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a) |
| 778 |
{ |
| 779 |
_swizzle[0] = r; |
| 780 |
_swizzle[1] = g; |
| 781 |
_swizzle[2] = b; |
| 782 |
_swizzle[3] = a; |
| 783 |
} |
| 784 |
|
| 785 |
void GsTexture::SetMaxLevel(std::int32_t maxLevel) |
| 786 |
{ |
| 787 |
static_cast<void>(maxLevel); |
| 788 |
} |
| 789 |
|
| 790 |
void GsTexture::SetUnpackAlignment(std::int32_t alignment) |
| 791 |
{ |
| 792 |
static_cast<void>(alignment); |
| 793 |
} |
| 794 |
|
| 795 |
void GsTexture::SetObjectLabel(StringView label) |
| 796 |
{ |
| 797 |
// The shared palette texture is intercepted by label, exactly as on the PVR and GU backends: its rows |
| 798 |
// become CLUTs loaded on demand, so it keeps no local-memory store of its own |
| 799 |
if (label == "Palettes"_s) { |
| 800 |
_isPaletteTexture = true; |
| 801 |
FreeStores(); |
| 802 |
GsDevice::RegisterPaletteTexture(this); |
| 803 |
} |
| 804 |
} |
| 805 |
} |