Debian Codegraph @

Sources/nCine/Graphics/RHI/D3D11/D3D11Texture.cpp

raw
1 #include "D3D11Texture.h"
2 #include "D3D11Device.h"
3
4 #include <cstring>
5
6 #include <d3d11.h>
7
8 #include <Asserts.h>
9
10 namespace nCine::RHI::D3D11
11 {
12 namespace
13 {
14 // Copies one packed row into the store, expanding a narrower source (RGB8) to a wider store
15 // (RGBA8) by filling the extra channel with 255 (opaque). A same-width copy is a plain memcpy.
16 void CopyExpandRow(std::uint8_t* dst, std::int32_t dstBpp, const std::uint8_t* src, std::int32_t srcBpp, std::int32_t width)
17 {
18 if (srcBpp == dstBpp) {
19 std::memcpy(dst, src, std::size_t(width) * std::size_t(dstBpp));
20 return;
21 }
22 const std::int32_t shared = (srcBpp < dstBpp ? srcBpp : dstBpp);
23 for (std::int32_t x = 0; x < width; x++) {
24 std::int32_t c = 0;
25 for (; c < shared; c++) {
26 dst[x * dstBpp + c] = src[x * srcBpp + c];
27 }
28 for (; c < dstBpp; c++) {
29 dst[x * dstBpp + c] = 255;
30 }
31 }
32 }
33 }
34
35 std::uint32_t D3D11Texture::_nextHandle = 1;
36
37 D3D11Texture::D3D11Texture(TextureTarget target)
38 : _handle(_nextHandle++), _target(target), _format(PixelFormat::Unknown), _uploadFormat(PixelFormat::Unknown),
39 _width(0), _height(0), _strideBytes(0),
40 _minFilter(nCine::SamplerFilter::Nearest), _magFilter(nCine::SamplerFilter::Nearest), _wrap(SamplerWrapping::ClampToEdge),
41 _textureUnit(0), _isRenderTarget(false),
42 _gpuTexture(nullptr), _srv(nullptr), _sampler(nullptr), _contentsDirty(false), _hasCpuData(false),
43 _samplerMinFilter(nCine::SamplerFilter::Nearest), _samplerFilter(nCine::SamplerFilter::Nearest), _samplerWrap(SamplerWrapping::ClampToEdge)
44 {
45 _swizzle[0] = SwizzleChannel::Red;
46 _swizzle[1] = SwizzleChannel::Green;
47 _swizzle[2] = SwizzleChannel::Blue;
48 _swizzle[3] = SwizzleChannel::Alpha;
49 }
50
51 D3D11Texture::~D3D11Texture()
52 {
53 // Unbind from the device first so a later draw can't dereference this freed texture via _boundTextures
54 // (crashed in BindTextures during splitscreen level changes)
55 D3D11Device::UnbindTexture(this);
56 ReleaseGpu();
57 }
58
59 void D3D11Texture::ReleaseGpu() const
60 {
61 if (_srv != nullptr) { _srv->Release(); _srv = nullptr; }
62 if (_gpuTexture != nullptr) { _gpuTexture->Release(); _gpuTexture = nullptr; }
63 if (_sampler != nullptr) { _sampler->Release(); _sampler = nullptr; }
64 }
65
66 bool D3D11Texture::IsIdentitySwizzle() const
67 {
68 return (_swizzle[0] == SwizzleChannel::Red && _swizzle[1] == SwizzleChannel::Green &&
69 _swizzle[2] == SwizzleChannel::Blue && _swizzle[3] == SwizzleChannel::Alpha);
70 }
71
72 const std::uint8_t* D3D11Texture::SwizzledUploadPixels() const
73 {
74 // The store is always RGBA8 (4 bpp) after Allocate()'s promotion. D3D11's base SRV cannot remap
75 // channels the way GL's GL_TEXTURE_SWIZZLE_* does, so a non-identity swizzle (e.g. the palette-index
76 // RG8 textures set A<-Green so the shader's `src.a` reads the packed alpha byte) is baked into the
77 // uploaded texels here. Without this, `src.a` would always be 1.0 and RG8 sprites (gems, pre-packed
78 // index+alpha) would lose their transparency; R8 textures keep the identity swizzle and are untouched.
79 if (_pixels.empty() || IsIdentitySwizzle()) {
80 return _pixels.data();
81 }
82 auto pick = [](SwizzleChannel channel, const std::uint8_t* texel) -> std::uint8_t {
83 switch (channel) {
84 case SwizzleChannel::Red: return texel[0];
85 case SwizzleChannel::Green: return texel[1];
86 case SwizzleChannel::Blue: return texel[2];
87 case SwizzleChannel::Alpha: return texel[3];
88 case SwizzleChannel::Zero: return 0;
89 case SwizzleChannel::One: return 255;
90 default: return texel[0];
91 }
92 };
93 _swizzledPixels.resize(_pixels.size());
94 const std::size_t texelCount = _pixels.size() / 4;
95 for (std::size_t i = 0; i < texelCount; i++) {
96 const std::uint8_t* in = &_pixels[i * 4];
97 std::uint8_t* out = &_swizzledPixels[i * 4];
98 out[0] = pick(_swizzle[0], in);
99 out[1] = pick(_swizzle[1], in);
100 out[2] = pick(_swizzle[2], in);
101 out[3] = pick(_swizzle[3], in);
102 }
103 return _swizzledPixels.data();
104 }
105
106 void D3D11Texture::EnsureGpuTexture() const
107 {
108 ID3D11Device* device = D3D11Device::GetD3DDevice();
109 if (device == nullptr || _width <= 0 || _height <= 0) {
110 return;
111 }
112
113 if (_gpuTexture != nullptr && !_contentsDirty) {
114 return;
115 }
116
117 // A CPU re-upload into an existing same-size texture just refreshes its contents
118 if (_gpuTexture != nullptr && _contentsDirty && !_isRenderTarget && _hasCpuData && !_pixels.empty()) {
119 ID3D11DeviceContext* context = D3D11Device::GetD3DContext();
120 if (context != nullptr) {
121 context->UpdateSubresource(_gpuTexture, 0, nullptr, SwizzledUploadPixels(), std::uint32_t(_strideBytes), 0);
122 _contentsDirty = false;
123 return;
124 }
125 }
126
127 // (Re)create the texture from scratch. The host store is always RGBA8 after the promotion in
128 // Allocate(), so a single DXGI format covers every runtime texture.
129 if (_srv != nullptr) { _srv->Release(); _srv = nullptr; }
130 if (_gpuTexture != nullptr) { _gpuTexture->Release(); _gpuTexture = nullptr; }
131
132 D3D11_TEXTURE2D_DESC desc = {};
133 desc.Width = static_cast<UINT>(_width);
134 desc.Height = static_cast<UINT>(_height);
135 desc.MipLevels = 1;
136 desc.ArraySize = 1;
137 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
138 desc.SampleDesc.Count = 1;
139 desc.SampleDesc.Quality = 0;
140 desc.Usage = D3D11_USAGE_DEFAULT;
141 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | (_isRenderTarget ? D3D11_BIND_RENDER_TARGET : 0u);
142 desc.CPUAccessFlags = 0;
143 desc.MiscFlags = 0;
144
145 D3D11_SUBRESOURCE_DATA init = {};
146 const bool hasInit = (_hasCpuData && !_isRenderTarget && !_pixels.empty());
147 if (hasInit) {
148 init.pSysMem = SwizzledUploadPixels();
149 init.SysMemPitch = static_cast<UINT>(_strideBytes);
150 }
151
152 if (FAILED(device->CreateTexture2D(&desc, hasInit ? &init : nullptr, &_gpuTexture))) {
153 _gpuTexture = nullptr;
154 return;
155 }
156 device->CreateShaderResourceView(_gpuTexture, nullptr, &_srv);
157 _contentsDirty = false;
158 }
159
160 ID3D11ShaderResourceView* D3D11Texture::GetSRV() const
161 {
162 EnsureGpuTexture();
163 return _srv;
164 }
165
166 ID3D11Texture2D* D3D11Texture::GetOrCreateTexture2D() const
167 {
168 EnsureGpuTexture();
169 return _gpuTexture;
170 }
171
172 ID3D11SamplerState* D3D11Texture::GetSampler() const
173 {
174 ID3D11Device* device = D3D11Device::GetD3DDevice();
175 if (device == nullptr) {
176 return nullptr;
177 }
178 if (_sampler != nullptr && _samplerFilter == _magFilter && _samplerMinFilter == _minFilter && _samplerWrap == _wrap) {
179 return _sampler;
180 }
181 if (_sampler != nullptr) { _sampler->Release(); _sampler = nullptr; }
182
183 D3D11_SAMPLER_DESC desc = {};
184 // Compose the filter from both the minification and magnification modes (mip mode is irrelevant, the
185 // backend only ever stores level 0)
186 const bool magLinear = (_magFilter == nCine::SamplerFilter::Linear ||
187 _magFilter == nCine::SamplerFilter::LinearMipmapNearest || _magFilter == nCine::SamplerFilter::LinearMipmapLinear);
188 const bool minLinear = (_minFilter == nCine::SamplerFilter::Linear ||
189 _minFilter == nCine::SamplerFilter::LinearMipmapNearest || _minFilter == nCine::SamplerFilter::LinearMipmapLinear);
190 if (minLinear && magLinear) {
191 desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
192 } else if (minLinear) {
193 desc.Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
194 } else if (magLinear) {
195 desc.Filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
196 } else {
197 desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
198 }
199 D3D11_TEXTURE_ADDRESS_MODE address;
200 switch (_wrap) {
201 case SamplerWrapping::Repeat: address = D3D11_TEXTURE_ADDRESS_WRAP; break;
202 case SamplerWrapping::MirroredRepeat: address = D3D11_TEXTURE_ADDRESS_MIRROR; break;
203 default: address = D3D11_TEXTURE_ADDRESS_CLAMP; break;
204 }
205 desc.AddressU = address;
206 desc.AddressV = address;
207 desc.AddressW = address;
208 desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
209 desc.MinLOD = 0;
210 desc.MaxLOD = D3D11_FLOAT32_MAX;
211 device->CreateSamplerState(&desc, &_sampler);
212 _samplerMinFilter = _minFilter;
213 _samplerFilter = _magFilter;
214 _samplerWrap = _wrap;
215 return _sampler;
216 }
217
218 std::int32_t D3D11Texture::BytesPerPixel(PixelFormat format)
219 {
220 switch (format) {
221 case PixelFormat::R8: return 1;
222 case PixelFormat::RG8: return 2;
223 case PixelFormat::RGB8: return 3;
224 case PixelFormat::RGBA8: return 4;
225 default: return 0;
226 }
227 }
228
229 void D3D11Texture::Allocate(PixelFormat format, std::int32_t width, std::int32_t height)
230 {
231 // Keep a self-consistent 4-byte-per-texel store for the runtime formats: promote the narrower ones
232 // (RGB8 render targets and the palette-index formats R8 / RG8) to an RGBA8 store, remembering the
233 // original in _uploadFormat. Mirrors the software backend's promotion so the backend can lift the same
234 // bytes into an `ID3D11Texture2D` without a separate widening step.
235 _uploadFormat = format;
236 _format = (format == PixelFormat::RGB8 || format == PixelFormat::R8 || format == PixelFormat::RG8) ? PixelFormat::RGBA8 : format;
237 _width = width;
238 _height = height;
239 const std::int32_t bpp = BytesPerPixel(_format);
240 _strideBytes = width * bpp;
241 _pixels.assign(std::size_t(_strideBytes) * std::size_t(height > 0 ? height : 0), std::uint8_t(0));
242 // The size/format changed, so any existing GPU texture must be rebuilt on the next bind
243 if (_srv != nullptr) { _srv->Release(); _srv = nullptr; }
244 if (_gpuTexture != nullptr) { _gpuTexture->Release(); _gpuTexture = nullptr; }
245 _contentsDirty = true;
246 }
247
248 bool D3D11Texture::Bind(std::uint32_t textureUnit) const
249 {
250 _textureUnit = textureUnit;
251 D3D11Device::BindTexture(textureUnit, this);
252 return true;
253 }
254
255 bool D3D11Texture::Unbind() const
256 {
257 D3D11Device::BindTexture(_textureUnit, nullptr);
258 return true;
259 }
260
261 bool D3D11Texture::Unbind(std::uint32_t textureUnit)
262 {
263 D3D11Device::BindTexture(textureUnit, nullptr);
264 return true;
265 }
266
267 void D3D11Texture::TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data)
268 {
269 static_cast<void>(bgr);
270 if (level != 0) {
271 return;
272 }
273 Allocate(format, width, height);
274 if (data != nullptr && !_pixels.empty()) {
275 _hasCpuData = true;
276 const std::int32_t srcBpp = BytesPerPixel(format);
277 const std::int32_t dstBpp = BytesPerPixel(_format);
278 if (srcBpp == dstBpp) {
279 std::memcpy(_pixels.data(), data, _pixels.size());
280 } else {
281 const std::uint8_t* src = static_cast<const std::uint8_t*>(data);
282 for (std::int32_t y = 0; y < _height; y++) {
283 CopyExpandRow(_pixels.data() + std::size_t(y) * _strideBytes,
284 dstBpp, src + std::size_t(y) * std::size_t(_width) * srcBpp, srcBpp, _width);
285 }
286 }
287 }
288 }
289
290 void D3D11Texture::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)
291 {
292 static_cast<void>(bgr);
293 if (level != 0 || data == nullptr || _pixels.empty()) {
294 return;
295 }
296 _hasCpuData = true;
297 _contentsDirty = true;
298 const std::int32_t srcBpp = BytesPerPixel(format);
299 const std::int32_t dstBpp = BytesPerPixel(_format);
300 for (std::int32_t y = 0; y < height; y++) {
301 const std::int32_t dstY = yoffset + y;
302 if (dstY < 0 || dstY >= _height) {
303 continue;
304 }
305 std::int32_t dstX = xoffset;
306 std::int32_t copyW = width;
307 std::int32_t srcX0 = 0;
308 if (dstX < 0) {
309 srcX0 = -dstX;
310 copyW += dstX;
311 dstX = 0;
312 }
313 if (dstX + copyW > _width) {
314 copyW = _width - dstX;
315 }
316 if (copyW <= 0) {
317 continue;
318 }
319 const std::uint8_t* srcRow = static_cast<const std::uint8_t*>(data) + std::size_t(y) * std::size_t(width) * srcBpp + std::size_t(srcX0) * srcBpp;
320 std::uint8_t* dstRow = _pixels.data() + std::size_t(dstY) * _strideBytes + std::size_t(dstX) * dstBpp;
321 CopyExpandRow(dstRow, dstBpp, srcRow, srcBpp, copyW);
322 }
323 }
324
325 void D3D11Texture::TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height)
326 {
327 static_cast<void>(levels);
328 Allocate(format, width, height);
329 }
330
331 void D3D11Texture::CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data)
332 {
333 static_cast<void>(level);
334 static_cast<void>(format);
335 static_cast<void>(width);
336 static_cast<void>(height);
337 static_cast<void>(imageSize);
338 static_cast<void>(data);
339 }
340
341 void D3D11Texture::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)
342 {
343 static_cast<void>(level);
344 static_cast<void>(xoffset);
345 static_cast<void>(yoffset);
346 static_cast<void>(width);
347 static_cast<void>(height);
348 static_cast<void>(format);
349 static_cast<void>(imageSize);
350 static_cast<void>(data);
351 }
352
353 void D3D11Texture::GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels)
354 {
355 static_cast<void>(level);
356 static_cast<void>(format);
357 static_cast<void>(bgr);
358 if (pixels == nullptr) {
359 return;
360 }
361
362 // A render target's contents only exist on the GPU (the host store is never written by draws), so read
363 // it back through a staging copy; plain textures return the host store directly
364 if (_isRenderTarget && _gpuTexture != nullptr) {
365 ID3D11Device* device = D3D11Device::GetD3DDevice();
366 ID3D11DeviceContext* context = D3D11Device::GetD3DContext();
367 if (device != nullptr && context != nullptr) {
368 D3D11_TEXTURE2D_DESC desc = {};
369 _gpuTexture->GetDesc(&desc);
370 desc.Usage = D3D11_USAGE_STAGING;
371 desc.BindFlags = 0;
372 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
373 desc.MiscFlags = 0;
374 ID3D11Texture2D* staging = nullptr;
375 if (SUCCEEDED(device->CreateTexture2D(&desc, nullptr, &staging))) {
376 context->CopyResource(staging, _gpuTexture);
377 D3D11_MAPPED_SUBRESOURCE mapped;
378 if (SUCCEEDED(context->Map(staging, 0, D3D11_MAP_READ, 0, &mapped))) {
379 const std::uint32_t rowBytes = std::uint32_t(_width) * 4;
380 std::uint8_t* dst = static_cast<std::uint8_t*>(pixels);
381 const std::uint8_t* src = static_cast<const std::uint8_t*>(mapped.pData);
382 for (std::int32_t y = 0; y < _height; y++) {
383 std::memcpy(dst + std::size_t(y) * rowBytes, src + std::size_t(y) * mapped.RowPitch, rowBytes);
384 }
385 context->Unmap(staging, 0);
386 staging->Release();
387 return;
388 }
389 staging->Release();
390 }
391 }
392 }
393
394 if (!_pixels.empty()) {
395 std::memcpy(pixels, _pixels.data(), _pixels.size());
396 }
397 }
398
399 void D3D11Texture::SetMinFiltering(nCine::SamplerFilter filter)
400 {
401 _minFilter = filter;
402 }
403
404 void D3D11Texture::SetMagFiltering(nCine::SamplerFilter filter)
405 {
406 _magFilter = filter;
407 }
408
409 void D3D11Texture::SetWrap(SamplerWrapping wrap)
410 {
411 _wrap = wrap;
412 }
413
414 void D3D11Texture::SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a)
415 {
416 _swizzle[0] = r;
417 _swizzle[1] = g;
418 _swizzle[2] = b;
419 _swizzle[3] = a;
420 // The swizzle is baked into the uploaded texels (D3D11 has no SRV channel remap), so a change must
421 // rebuild the GPU texture; it is usually set right after the upload, before the first bind.
422 _contentsDirty = true;
423 }
424
425 void D3D11Texture::SetMaxLevel(std::int32_t maxLevel)
426 {
427 static_cast<void>(maxLevel);
428 }
429
430 void D3D11Texture::SetUnpackAlignment(std::int32_t alignment)
431 {
432 static_cast<void>(alignment);
433 }
434
435 void D3D11Texture::SetObjectLabel(StringView label)
436 {
437 static_cast<void>(label);
438 }
439 }