Debian Codegraph @

Sources/nCine/Graphics/RHI/RSX/RsxTexture.cpp

raw
1 #if defined(WITH_RHI_RSX)
2
3 #include "RsxTexture.h"
4 #include "RsxDevice.h"
5
6 #include "../../../../Main.h"
7
8 #include <cstring>
9
10 #include <rsx/rsx.h>
11 #include <rsx/commands.h>
12
13 namespace nCine::RHI::RSX
14 {
15 namespace
16 {
17 // Copies one packed row into the store, expanding a narrower source (RGB8, R8, RG8) to the RGBA8
18 // store by filling the extra channels with 255 (opaque). A same-width copy is a plain memcpy.
19 void CopyExpandRow(std::uint8_t* dst, std::int32_t dstBpp, const std::uint8_t* src, std::int32_t srcBpp, std::int32_t width)
20 {
21 if (srcBpp == dstBpp) {
22 std::memcpy(dst, src, std::size_t(width) * std::size_t(dstBpp));
23 return;
24 }
25 const std::int32_t shared = (srcBpp < dstBpp ? srcBpp : dstBpp);
26 for (std::int32_t x = 0; x < width; x++) {
27 std::int32_t c = 0;
28 for (; c < shared; c++) {
29 dst[x * dstBpp + c] = src[x * srcBpp + c];
30 }
31 for (; c < dstBpp; c++) {
32 dst[x * dstBpp + c] = 255;
33 }
34 }
35 }
36
37 /**
38 @brief Translates a minification filter, which is the only one that may mention mip levels
39
40 The store is single-level, so a mipmapped mode is reduced to its base filter rather than being
41 refused: the texture simply has nothing to minify into, and the hardware would sample level 0
42 regardless.
43 */
44 inline std::uint8_t TranslateMinFilter(nCine::SamplerFilter filter)
45 {
46 switch (filter) {
47 case nCine::SamplerFilter::Linear:
48 case nCine::SamplerFilter::LinearMipmapNearest:
49 case nCine::SamplerFilter::LinearMipmapLinear:
50 return GCM_TEXTURE_LINEAR;
51 default:
52 return GCM_TEXTURE_NEAREST;
53 }
54 }
55
56 inline std::uint8_t TranslateMagFilter(nCine::SamplerFilter filter)
57 {
58 return (filter == nCine::SamplerFilter::Linear ? GCM_TEXTURE_LINEAR : GCM_TEXTURE_NEAREST);
59 }
60
61 inline std::uint8_t TranslateWrap(SamplerWrapping wrap)
62 {
63 switch (wrap) {
64 case SamplerWrapping::Repeat: return GCM_TEXTURE_REPEAT;
65 case SamplerWrapping::MirroredRepeat: return GCM_TEXTURE_MIRRORED_REPEAT;
66 default: return GCM_TEXTURE_CLAMP_TO_EDGE;
67 }
68 }
69
70 /**
71 @brief Which hardware channel of the A8R8G8B8 word carries a logical RGBA8 channel
72
73 The engine's store holds bytes in R, G, B, A order. Read as one big-endian word that is
74 `0xRRGGBBAA`, and the hardware reads a word as A8R8G8B8 - so its A field holds the logical red,
75 its R field the logical green, and so on round the cycle. Sampling therefore needs the rotation
76 this table expresses, which @ref RsxTexture::BuildRemap() folds into the swizzle for free.
77 */
78 inline std::uint32_t HardwareChannelFor(SwizzleChannel channel)
79 {
80 switch (channel) {
81 case SwizzleChannel::Red: return GCM_TEXTURE_REMAP_COLOR_A;
82 case SwizzleChannel::Green: return GCM_TEXTURE_REMAP_COLOR_R;
83 case SwizzleChannel::Blue: return GCM_TEXTURE_REMAP_COLOR_G;
84 case SwizzleChannel::Alpha: return GCM_TEXTURE_REMAP_COLOR_B;
85 default: return GCM_TEXTURE_REMAP_COLOR_A;
86 }
87 }
88
89 /**
90 @brief Which hardware channel carries a logical RGBA8 channel of a GPU-WRITTEN surface
91
92 The rotation above exists only because the host store's bytes are read as a big-endian word: it
93 corrects a byte order, not a channel order. A render target never goes through that path - the ROP
94 writes it as an A8R8G8B8 word directly, with alpha already in the top byte - so sampling one needs
95 the identity mapping instead. This is the same remap @ref RsxDevice's own screen surface uses.
96 */
97 inline std::uint32_t HardwareChannelForSurface(SwizzleChannel channel)
98 {
99 switch (channel) {
100 case SwizzleChannel::Red: return GCM_TEXTURE_REMAP_COLOR_R;
101 case SwizzleChannel::Green: return GCM_TEXTURE_REMAP_COLOR_G;
102 case SwizzleChannel::Blue: return GCM_TEXTURE_REMAP_COLOR_B;
103 case SwizzleChannel::Alpha: return GCM_TEXTURE_REMAP_COLOR_A;
104 default: return GCM_TEXTURE_REMAP_COLOR_R;
105 }
106 }
107
108 /** @brief Row-stride granularity of the GPU copy (see @ref RsxTexture) */
109 constexpr std::uint32_t TexturePitchAlignment = 64;
110 }
111
112 std::uint32_t RsxTexture::_nextHandle = 1;
113
114 RsxTexture::RsxTexture(TextureTarget target)
115 : _handle(_nextHandle++), _target(target), _format(PixelFormat::Unknown), _uploadFormat(PixelFormat::Unknown),
116 _width(0), _height(0), _strideBytes(0),
117 _minFilter(nCine::SamplerFilter::Nearest), _magFilter(nCine::SamplerFilter::Nearest), _wrap(SamplerWrapping::ClampToEdge),
118 _textureUnit(0), _isRenderTarget(false), _gpuStride(0), _gpuValid(false), _contentsDirty(false)
119 {
120 _swizzle[0] = SwizzleChannel::Red;
121 _swizzle[1] = SwizzleChannel::Green;
122 _swizzle[2] = SwizzleChannel::Blue;
123 _swizzle[3] = SwizzleChannel::Alpha;
124 std::memset(&_gpuTexture, 0, sizeof(_gpuTexture));
125 }
126
127 RsxTexture::~RsxTexture()
128 {
129 // The device tracks bound textures by pointer, so it has to forget this one before the memory goes
130 RsxDevice::UnbindTexture(this);
131 ReleaseGpu();
132 }
133
134 void RsxTexture::ReleaseGpu() const
135 {
136 if (_gpuBlock.IsValid()) {
137 // The GPU may still be reading these texels from a frame that has not finished, so the block is
138 // handed to the device's retirement list rather than freed under the hardware
139 RsxDevice::RetireBlock(_gpuBlock);
140 }
141 _gpuValid = false;
142 _gpuStride = 0;
143 }
144
145 std::int32_t RsxTexture::BytesPerPixel(PixelFormat format)
146 {
147 switch (format) {
148 case PixelFormat::R8: return 1;
149 case PixelFormat::RG8: return 2;
150 case PixelFormat::RGB565:
151 case PixelFormat::RGB5A1:
152 case PixelFormat::RGBA4: return 2;
153 case PixelFormat::RGB8: return 3;
154 case PixelFormat::RGBA8: return 4;
155 case PixelFormat::RGBA16F: return 8;
156 case PixelFormat::RGBA32F: return 16;
157 default: return 0;
158 }
159 }
160
161 std::uint32_t RsxTexture::BuildRemap() const
162 {
163 // Each output channel independently picks a hardware source channel, or a constant. The engine's
164 // swizzle says which LOGICAL channel feeds each output; HardwareChannelFor() turns that into the
165 // hardware channel the RGBA8-as-A8R8G8B8 reinterpretation put it in (see the class documentation).
166 const auto typeOf = [](SwizzleChannel channel) -> std::uint32_t {
167 switch (channel) {
168 case SwizzleChannel::Zero: return GCM_TEXTURE_REMAP_TYPE_ZERO;
169 case SwizzleChannel::One: return GCM_TEXTURE_REMAP_TYPE_ONE;
170 default: return GCM_TEXTURE_REMAP_TYPE_REMAP;
171 }
172 };
173
174 // Host-uploaded texels need the byte-order rotation; a render target the GPU wrote itself does not.
175 // Confirmed empirically: forcing identity on host textures turns yellow (255,220,0) into blue-purple,
176 // i.e. it samples as (G,B,A,R) - so the rotation below is what puts every channel, alpha included,
177 // back where the engine expects it.
178 const auto channelOf = (_isRenderTarget ? &HardwareChannelForSurface : &HardwareChannelFor);
179
180 return ((typeOf(_swizzle[3]) << GCM_TEXTURE_REMAP_TYPE_A_SHIFT) |
181 (typeOf(_swizzle[0]) << GCM_TEXTURE_REMAP_TYPE_R_SHIFT) |
182 (typeOf(_swizzle[1]) << GCM_TEXTURE_REMAP_TYPE_G_SHIFT) |
183 (typeOf(_swizzle[2]) << GCM_TEXTURE_REMAP_TYPE_B_SHIFT) |
184 (channelOf(_swizzle[3]) << GCM_TEXTURE_REMAP_COLOR_A_SHIFT) |
185 (channelOf(_swizzle[0]) << GCM_TEXTURE_REMAP_COLOR_R_SHIFT) |
186 (channelOf(_swizzle[1]) << GCM_TEXTURE_REMAP_COLOR_G_SHIFT) |
187 (channelOf(_swizzle[2]) << GCM_TEXTURE_REMAP_COLOR_B_SHIFT));
188 }
189
190 void RsxTexture::Allocate(PixelFormat format, std::int32_t width, std::int32_t height)
191 {
192 // Keep a self-consistent 4-byte-per-texel store for the runtime formats: promote the narrower ones
193 // (RGB8 render targets and the palette-index formats R8 / RG8) to an RGBA8 store, remembering the
194 // original in _uploadFormat. One GPU-side format means one texture layout to get right.
195 _uploadFormat = format;
196 _format = (format == PixelFormat::RGB8 || format == PixelFormat::R8 || format == PixelFormat::RG8) ? PixelFormat::RGBA8 : format;
197 _width = width;
198 _height = height;
199 const std::int32_t bpp = BytesPerPixel(_format);
200 _strideBytes = width * bpp;
201 _pixels.assign(std::size_t(_strideBytes) * std::size_t(height > 0 ? height : 0), std::uint8_t(0));
202 // The size/format changed, so the GPU copy has to be rebuilt on the next bind
203 ReleaseGpu();
204 _contentsDirty = true;
205 }
206
207 void RsxTexture::SetRenderTarget(bool isRenderTarget)
208 {
209 if (isRenderTarget == _isRenderTarget) {
210 return;
211 }
212 _isRenderTarget = isRenderTarget;
213 // Nothing about the allocation changes - an RSX surface and an RSX texture are the same memory read
214 // two ways - but a target's texels stop coming from the host store, so a pending upload would
215 // overwrite what the GPU drew. Rebuilding makes the transition explicit either way round.
216 ReleaseGpu();
217 _contentsDirty = !isRenderTarget;
218 }
219
220 bool RsxTexture::EnsureGpuTexture() const
221 {
222 if (_width <= 0 || _height <= 0 || _format != PixelFormat::RGBA8) {
223 // Only the promoted RGBA8 store has a GPU-side counterpart; the float and packed formats are
224 // accepted by the uploads but never sampled by this backend's shaders
225 return false;
226 }
227
228 if (!_gpuBlock.IsValid()) {
229 // Local memory, always. A texture is written once by the PPE and then sampled repeatedly by the
230 // GPU, which is exactly the access pattern GDDR3's uncached-write / fast-read asymmetry suits
231 // (see RsxVram). That holds for a render target too - there the PPE does not write it at all.
232 const std::uint32_t pitch = (std::uint32_t(_width) * 4u + TexturePitchAlignment - 1) & ~(TexturePitchAlignment - 1);
233 _gpuBlock = RsxVram::Alloc(pitch * std::uint32_t(_height), TexturePitchAlignment, RsxVram::Location::Local);
234 if (!_gpuBlock.IsValid()) {
235 LOGE("Cannot allocate a {}x{} texture in local memory", _width, _height);
236 return false;
237 }
238 _gpuStride = pitch;
239 _contentsDirty = !_isRenderTarget;
240
241 std::memset(&_gpuTexture, 0, sizeof(_gpuTexture));
242 // LIN: an explicit pitch, rather than the swizzled layout that would derive one from a
243 // power-of-two width. NRM would normalize the coordinates the other way round from what the
244 // engine's shaders expect, so it is deliberately absent - the RSX defaults to normalized.
245 _gpuTexture.format = (GCM_TEXTURE_FORMAT_A8R8G8B8 | GCM_TEXTURE_FORMAT_LIN);
246 _gpuTexture.mipmap = 1;
247 _gpuTexture.dimension = GCM_TEXTURE_DIMS_2D;
248 _gpuTexture.cubemap = GCM_FALSE;
249 _gpuTexture.width = std::uint16_t(_width);
250 _gpuTexture.height = std::uint16_t(_height);
251 _gpuTexture.depth = 1;
252 _gpuTexture.location = _gpuBlock.GetGcmLocation();
253 _gpuTexture.pitch = pitch;
254 _gpuTexture.offset = _gpuBlock.Offset;
255 _gpuValid = true;
256 }
257
258 // The remap is recomputed unconditionally: it is one word, and it depends only on the swizzle, so
259 // there is nothing to invalidate and nothing to get out of step
260 _gpuTexture.remap = BuildRemap();
261
262 if (_contentsDirty) {
263 UploadPixels();
264 _contentsDirty = false;
265 }
266 return _gpuValid;
267 }
268
269 void RsxTexture::UploadPixels() const
270 {
271 if (!_gpuBlock.IsValid() || _pixels.empty()) {
272 return;
273 }
274
275 // The texels go across unchanged - no swizzle is baked in and no byte order is fixed up, because the
276 // sampler's remap does both (see the class documentation). Only the row padding differs between the
277 // tightly packed host store and the aligned GPU pitch.
278 std::uint8_t* dst = static_cast<std::uint8_t*>(_gpuBlock.Base);
279 const std::uint32_t rowBytes = std::uint32_t(_width) * 4u;
280 if (_gpuStride == rowBytes) {
281 std::memcpy(dst, _pixels.data(), std::size_t(rowBytes) * std::size_t(_height));
282 } else {
283 for (std::int32_t y = 0; y < _height; y++) {
284 std::memcpy(dst + std::size_t(y) * _gpuStride, _pixels.data() + std::size_t(y) * rowBytes, rowBytes);
285 }
286 }
287 }
288
289 void RsxTexture::ApplySamplerState(std::uint32_t textureUnit) const
290 {
291 gcmContextData* context = RsxDevice::GetContext();
292 if (context == nullptr) {
293 return;
294 }
295
296 const std::uint8_t index = std::uint8_t(textureUnit);
297 // Enable the unit with a single mip level (min and max LOD both 0, in the 8.8 fixed point the
298 // command takes) and no anisotropy - the store has one level, so anything else would be a lie
299 rsxTextureControl(context, index, GCM_TRUE, 0 << 8, 0 << 8, GCM_TEXTURE_MAX_ANISO_1);
300 rsxTextureFilter(context, index, 0, TranslateMinFilter(_minFilter), TranslateMagFilter(_magFilter),
301 GCM_TEXTURE_CONVOLUTION_QUINCUNX);
302
303 // Unlike the sceGxm backend, no addressing mode has to be given up here: the RSX's linear layout
304 // accepts repeat and mirrored-repeat as readily as clamp, so the scrolling background's Repeat and
305 // the blur passes reading past an edge both work on the layout every texture already has.
306 const std::uint8_t wrap = TranslateWrap(_wrap);
307 rsxTextureWrapMode(context, index, wrap, wrap, GCM_TEXTURE_CLAMP_TO_EDGE, 0, GCM_TEXTURE_ZFUNC_LESS, 0);
308 }
309
310 const gcmTexture* RsxTexture::GetGcmTexture() const
311 {
312 return (EnsureGpuTexture() ? &_gpuTexture : nullptr);
313 }
314
315 void* RsxTexture::GetSurfaceData() const
316 {
317 return (EnsureGpuTexture() ? _gpuBlock.Base : nullptr);
318 }
319
320 bool RsxTexture::Bind(std::uint32_t textureUnit) const
321 {
322 _textureUnit = textureUnit;
323 RsxDevice::BindTexture(textureUnit, this);
324 return true;
325 }
326
327 bool RsxTexture::Unbind() const
328 {
329 RsxDevice::BindTexture(_textureUnit, nullptr);
330 return true;
331 }
332
333 bool RsxTexture::Unbind(std::uint32_t textureUnit)
334 {
335 RsxDevice::BindTexture(textureUnit, nullptr);
336 return true;
337 }
338
339 void RsxTexture::TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data)
340 {
341 static_cast<void>(bgr);
342 if (level != 0) {
343 return;
344 }
345
346 Allocate(format, width, height);
347 if (data != nullptr && !_pixels.empty()) {
348 const std::int32_t srcBpp = BytesPerPixel(format);
349 const std::int32_t dstBpp = BytesPerPixel(_format);
350 if (srcBpp == dstBpp) {
351 std::memcpy(_pixels.data(), data, _pixels.size());
352 } else {
353 const std::uint8_t* src = static_cast<const std::uint8_t*>(data);
354 for (std::int32_t y = 0; y < _height; y++) {
355 CopyExpandRow(_pixels.data() + std::size_t(y) * _strideBytes,
356 dstBpp, src + std::size_t(y) * std::size_t(_width) * srcBpp, srcBpp, _width);
357 }
358 }
359 }
360 }
361
362 void RsxTexture::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)
363 {
364 static_cast<void>(bgr);
365 if (level != 0 || data == nullptr || _pixels.empty()) {
366 return;
367 }
368 if (xoffset < 0 || yoffset < 0 || xoffset + width > _width || yoffset + height > _height) {
369 return;
370 }
371
372 _contentsDirty = true;
373 const std::int32_t srcBpp = BytesPerPixel(format);
374 const std::int32_t dstBpp = BytesPerPixel(_format);
375 const std::uint8_t* src = static_cast<const std::uint8_t*>(data);
376 for (std::int32_t y = 0; y < height; y++) {
377 CopyExpandRow(_pixels.data() + std::size_t(yoffset + y) * _strideBytes + std::size_t(xoffset) * dstBpp,
378 dstBpp, src + std::size_t(y) * std::size_t(width) * srcBpp, srcBpp, width);
379 }
380 }
381
382 void RsxTexture::TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height)
383 {
384 static_cast<void>(levels);
385 Allocate(format, width, height);
386 }
387
388 void RsxTexture::CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data)
389 {
390 // The RSX does have DXT sampling, but the engine's console content is delivered uncompressed and
391 // nothing in the pipeline reaches this path; accepted as a no-op rather than half-implemented
392 static_cast<void>(level);
393 static_cast<void>(format);
394 static_cast<void>(width);
395 static_cast<void>(height);
396 static_cast<void>(imageSize);
397 static_cast<void>(data);
398 }
399
400 void RsxTexture::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)
401 {
402 static_cast<void>(level);
403 static_cast<void>(xoffset);
404 static_cast<void>(yoffset);
405 static_cast<void>(width);
406 static_cast<void>(height);
407 static_cast<void>(format);
408 static_cast<void>(imageSize);
409 static_cast<void>(data);
410 }
411
412 void RsxTexture::GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels)
413 {
414 static_cast<void>(bgr);
415 if (level != 0 || pixels == nullptr || _width <= 0 || _height <= 0) {
416 return;
417 }
418
419 // A render target's texels live only in its GPU copy, and the GPU has to be done writing them first.
420 // This read comes out of local memory, which the PPE reaches uncached across the bus - it is by far
421 // the slowest thing this backend can do, and the reason nothing on a frame path calls it.
422 const std::uint8_t* source = _pixels.data();
423 std::size_t sourceStride = std::size_t(_strideBytes);
424 if (_isRenderTarget && _gpuBlock.IsValid()) {
425 RsxDevice::Finish();
426 source = static_cast<const std::uint8_t*>(_gpuBlock.Base);
427 sourceStride = std::size_t(_gpuStride);
428 }
429 if (source == nullptr) {
430 return;
431 }
432
433 const std::int32_t dstBpp = BytesPerPixel(format);
434 const std::int32_t srcBpp = BytesPerPixel(_format);
435 std::uint8_t* dst = static_cast<std::uint8_t*>(pixels);
436 if (dstBpp == srcBpp) {
437 const std::size_t rowBytes = std::size_t(_width) * std::size_t(srcBpp);
438 for (std::int32_t y = 0; y < _height; y++) {
439 std::memcpy(dst + std::size_t(y) * rowBytes, source + std::size_t(y) * sourceStride, rowBytes);
440 }
441 return;
442 }
443 // Narrowing readback (an RGBA8 store read back as RGB8): drop the trailing channels per texel
444 const std::int32_t shared = (srcBpp < dstBpp ? srcBpp : dstBpp);
445 for (std::int32_t y = 0; y < _height; y++) {
446 const std::uint8_t* in = source + std::size_t(y) * sourceStride;
447 std::uint8_t* out = dst + std::size_t(y) * std::size_t(_width) * std::size_t(dstBpp);
448 for (std::int32_t x = 0; x < _width; x++, in += srcBpp, out += dstBpp) {
449 std::int32_t c = 0;
450 for (; c < shared; c++) {
451 out[c] = in[c];
452 }
453 for (; c < dstBpp; c++) {
454 out[c] = 255;
455 }
456 }
457 }
458 }
459
460 void* RsxTexture::MapStreamingTexels(std::int32_t& strideBytes)
461 {
462 // A render target's texels belong to the GPU, and only the promoted RGBA8 store has a GPU copy at all
463 if (_isRenderTarget || _format != PixelFormat::RGBA8) {
464 return nullptr;
465 }
466 if (!EnsureGpuTexture()) {
467 return nullptr;
468 }
469
470 // The caller overwrites the whole surface every frame, so the host store is now stale by definition;
471 // clearing the dirty flag stops the next bind from copying it back over what was just written
472 _contentsDirty = false;
473
474 strideBytes = std::int32_t(_gpuStride);
475 return _gpuBlock.Base;
476 }
477
478 void RsxTexture::SetMinFiltering(nCine::SamplerFilter filter)
479 {
480 _minFilter = filter;
481 }
482
483 void RsxTexture::SetMagFiltering(nCine::SamplerFilter filter)
484 {
485 _magFilter = filter;
486 }
487
488 void RsxTexture::SetWrap(SamplerWrapping wrap)
489 {
490 _wrap = wrap;
491 }
492
493 void RsxTexture::SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a)
494 {
495 // Only the remap word changes; the texels stay as they were uploaded, which is what makes this cheap
496 // enough for the pipeline to set per material rather than per texture creation
497 _swizzle[0] = r;
498 _swizzle[1] = g;
499 _swizzle[2] = b;
500 _swizzle[3] = a;
501 }
502
503 void RsxTexture::SetMaxLevel(std::int32_t maxLevel)
504 {
505 static_cast<void>(maxLevel);
506 }
507
508 void RsxTexture::SetUnpackAlignment(std::int32_t alignment)
509 {
510 static_cast<void>(alignment);
511 }
512
513 void RsxTexture::SetObjectLabel(StringView label)
514 {
515 static_cast<void>(label);
516 }
517 }
518
519 #endif