• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2012 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // Image11.h: Implements the rx::Image11 class, which acts as the interface to
8 // the actual underlying resources of a Texture
9 
10 #include "libANGLE/renderer/d3d/d3d11/Image11.h"
11 
12 #include "common/utilities.h"
13 #include "image_util/loadimage.h"
14 #include "libANGLE/Context.h"
15 #include "libANGLE/Framebuffer.h"
16 #include "libANGLE/FramebufferAttachment.h"
17 #include "libANGLE/formatutils.h"
18 #include "libANGLE/renderer/d3d/d3d11/Context11.h"
19 #include "libANGLE/renderer/d3d/d3d11/RenderTarget11.h"
20 #include "libANGLE/renderer/d3d/d3d11/Renderer11.h"
21 #include "libANGLE/renderer/d3d/d3d11/TextureStorage11.h"
22 #include "libANGLE/renderer/d3d/d3d11/formatutils11.h"
23 #include "libANGLE/renderer/d3d/d3d11/renderer11_utils.h"
24 #include "libANGLE/renderer/d3d/d3d11/texture_format_table.h"
25 
26 namespace rx
27 {
28 
Image11(Renderer11 * renderer)29 Image11::Image11(Renderer11 *renderer)
30     : mRenderer(renderer),
31       mDXGIFormat(DXGI_FORMAT_UNKNOWN),
32       mStagingTexture(),
33       mStagingSubresource(0),
34       mRecoverFromStorage(false),
35       mAssociatedStorage(nullptr),
36       mAssociatedImageIndex(),
37       mRecoveredFromStorageCount(0)
38 {}
39 
~Image11()40 Image11::~Image11()
41 {
42     disassociateStorage();
43     releaseStagingTexture();
44 }
45 
46 // static
GenerateMipmap(const gl::Context * context,Image11 * dest,Image11 * src,const Renderer11DeviceCaps & rendererCaps)47 angle::Result Image11::GenerateMipmap(const gl::Context *context,
48                                       Image11 *dest,
49                                       Image11 *src,
50                                       const Renderer11DeviceCaps &rendererCaps)
51 {
52     ASSERT(src->getDXGIFormat() == dest->getDXGIFormat());
53     ASSERT(src->getWidth() == 1 || src->getWidth() / 2 == dest->getWidth());
54     ASSERT(src->getHeight() == 1 || src->getHeight() / 2 == dest->getHeight());
55 
56     D3D11_MAPPED_SUBRESOURCE destMapped;
57     ANGLE_TRY(dest->map(context, D3D11_MAP_WRITE, &destMapped));
58     d3d11::ScopedUnmapper<Image11> destRAII(dest);
59 
60     D3D11_MAPPED_SUBRESOURCE srcMapped;
61     ANGLE_TRY(src->map(context, D3D11_MAP_READ, &srcMapped));
62     d3d11::ScopedUnmapper<Image11> srcRAII(src);
63 
64     const uint8_t *sourceData = static_cast<const uint8_t *>(srcMapped.pData);
65     uint8_t *destData         = static_cast<uint8_t *>(destMapped.pData);
66 
67     auto mipGenerationFunction =
68         d3d11::Format::Get(src->getInternalFormat(), rendererCaps).format().mipGenerationFunction;
69     mipGenerationFunction(src->getWidth(), src->getHeight(), src->getDepth(), sourceData,
70                           srcMapped.RowPitch, srcMapped.DepthPitch, destData, destMapped.RowPitch,
71                           destMapped.DepthPitch);
72 
73     dest->markDirty();
74 
75     return angle::Result::Continue;
76 }
77 
78 // static
CopyImage(const gl::Context * context,Image11 * dest,Image11 * source,const gl::Box & sourceBox,const gl::Offset & destOffset,bool unpackFlipY,bool unpackPremultiplyAlpha,bool unpackUnmultiplyAlpha,const Renderer11DeviceCaps & rendererCaps)79 angle::Result Image11::CopyImage(const gl::Context *context,
80                                  Image11 *dest,
81                                  Image11 *source,
82                                  const gl::Box &sourceBox,
83                                  const gl::Offset &destOffset,
84                                  bool unpackFlipY,
85                                  bool unpackPremultiplyAlpha,
86                                  bool unpackUnmultiplyAlpha,
87                                  const Renderer11DeviceCaps &rendererCaps)
88 {
89     D3D11_MAPPED_SUBRESOURCE destMapped;
90     ANGLE_TRY(dest->map(context, D3D11_MAP_WRITE, &destMapped));
91     d3d11::ScopedUnmapper<Image11> destRAII(dest);
92 
93     D3D11_MAPPED_SUBRESOURCE srcMapped;
94     ANGLE_TRY(source->map(context, D3D11_MAP_READ, &srcMapped));
95     d3d11::ScopedUnmapper<Image11> sourceRAII(source);
96 
97     const auto &sourceFormat =
98         d3d11::Format::Get(source->getInternalFormat(), rendererCaps).format();
99     GLuint sourcePixelBytes =
100         gl::GetSizedInternalFormatInfo(sourceFormat.fboImplementationInternalFormat).pixelBytes;
101 
102     GLenum destUnsizedFormat = gl::GetUnsizedFormat(dest->getInternalFormat());
103     const auto &destFormat   = d3d11::Format::Get(dest->getInternalFormat(), rendererCaps).format();
104     const auto &destFormatInfo =
105         gl::GetSizedInternalFormatInfo(destFormat.fboImplementationInternalFormat);
106     GLuint destPixelBytes = destFormatInfo.pixelBytes;
107 
108     const uint8_t *sourceData = static_cast<const uint8_t *>(srcMapped.pData) +
109                                 sourceBox.x * sourcePixelBytes + sourceBox.y * srcMapped.RowPitch +
110                                 sourceBox.z * srcMapped.DepthPitch;
111     uint8_t *destData = static_cast<uint8_t *>(destMapped.pData) + destOffset.x * destPixelBytes +
112                         destOffset.y * destMapped.RowPitch + destOffset.z * destMapped.DepthPitch;
113 
114     CopyImageCHROMIUM(sourceData, srcMapped.RowPitch, sourcePixelBytes, srcMapped.DepthPitch,
115                       sourceFormat.pixelReadFunction, destData, destMapped.RowPitch, destPixelBytes,
116                       destMapped.DepthPitch, destFormat.pixelWriteFunction, destUnsizedFormat,
117                       destFormatInfo.componentType, sourceBox.width, sourceBox.height,
118                       sourceBox.depth, unpackFlipY, unpackPremultiplyAlpha, unpackUnmultiplyAlpha);
119 
120     dest->markDirty();
121 
122     return angle::Result::Continue;
123 }
124 
isDirty() const125 bool Image11::isDirty() const
126 {
127     // If mDirty is true AND mStagingTexture doesn't exist AND mStagingTexture doesn't need to be
128     // recovered from TextureStorage AND the texture doesn't require init data (i.e. a blank new
129     // texture will suffice) AND robust resource initialization is not enabled then isDirty should
130     // still return false.
131     if (mDirty && !mStagingTexture.valid() && !mRecoverFromStorage)
132     {
133         const Renderer11DeviceCaps &deviceCaps = mRenderer->getRenderer11DeviceCaps();
134         const auto &formatInfo                 = d3d11::Format::Get(mInternalFormat, deviceCaps);
135         if (formatInfo.dataInitializerFunction == nullptr)
136         {
137             return false;
138         }
139     }
140 
141     return mDirty;
142 }
143 
copyToStorage(const gl::Context * context,TextureStorage * storage,const gl::ImageIndex & index,const gl::Box & region)144 angle::Result Image11::copyToStorage(const gl::Context *context,
145                                      TextureStorage *storage,
146                                      const gl::ImageIndex &index,
147                                      const gl::Box &region)
148 {
149     TextureStorage11 *storage11 = GetAs<TextureStorage11>(storage);
150 
151     // If an app's behavior results in an Image11 copying its data to/from to a TextureStorage
152     // multiple times, then we should just keep the staging texture around to prevent the copying
153     // from impacting perf. We allow the Image11 to copy its data to/from TextureStorage once. This
154     // accounts for an app making a late call to glGenerateMipmap.
155     bool attemptToReleaseStagingTexture = (mRecoveredFromStorageCount < 2);
156 
157     if (attemptToReleaseStagingTexture)
158     {
159         // If another image is relying on this Storage for its data, then we must let it recover its
160         // data before we overwrite it.
161         ANGLE_TRY(storage11->releaseAssociatedImage(context, index, this));
162     }
163 
164     const TextureHelper11 *stagingTexture = nullptr;
165     unsigned int stagingSubresourceIndex  = 0;
166     ANGLE_TRY(getStagingTexture(context, &stagingTexture, &stagingSubresourceIndex));
167     ANGLE_TRY(storage11->updateSubresourceLevel(context, *stagingTexture, stagingSubresourceIndex,
168                                                 index, region));
169 
170     // Once the image data has been copied into the Storage, we can release it locally.
171     if (attemptToReleaseStagingTexture)
172     {
173         storage11->associateImage(this, index);
174         releaseStagingTexture();
175         mRecoverFromStorage   = true;
176         mAssociatedStorage    = storage11;
177         mAssociatedImageIndex = index;
178     }
179 
180     return angle::Result::Continue;
181 }
182 
verifyAssociatedStorageValid(TextureStorage11 * textureStorageEXT) const183 void Image11::verifyAssociatedStorageValid(TextureStorage11 *textureStorageEXT) const
184 {
185     ASSERT(mAssociatedStorage == textureStorageEXT);
186 }
187 
recoverFromAssociatedStorage(const gl::Context * context)188 angle::Result Image11::recoverFromAssociatedStorage(const gl::Context *context)
189 {
190     if (mRecoverFromStorage)
191     {
192         ANGLE_TRY(createStagingTexture(context));
193 
194         mAssociatedStorage->verifyAssociatedImageValid(mAssociatedImageIndex, this);
195 
196         // CopySubResource from the Storage to the Staging texture
197         gl::Box region(0, 0, 0, mWidth, mHeight, mDepth);
198         ANGLE_TRY(mAssociatedStorage->copySubresourceLevel(
199             context, mStagingTexture, mStagingSubresource, mAssociatedImageIndex, region));
200         mRecoveredFromStorageCount += 1;
201 
202         // Reset all the recovery parameters, even if the texture storage association is broken.
203         disassociateStorage();
204 
205         markDirty();
206     }
207 
208     return angle::Result::Continue;
209 }
210 
disassociateStorage()211 void Image11::disassociateStorage()
212 {
213     if (mRecoverFromStorage)
214     {
215         // Make the texturestorage release the Image11 too
216         mAssociatedStorage->disassociateImage(mAssociatedImageIndex, this);
217 
218         mRecoverFromStorage   = false;
219         mAssociatedStorage    = nullptr;
220         mAssociatedImageIndex = gl::ImageIndex();
221     }
222 }
223 
redefine(gl::TextureType type,GLenum internalformat,const gl::Extents & size,bool forceRelease)224 bool Image11::redefine(gl::TextureType type,
225                        GLenum internalformat,
226                        const gl::Extents &size,
227                        bool forceRelease)
228 {
229     if (mWidth != size.width || mHeight != size.height || mDepth != size.depth ||
230         mInternalFormat != internalformat || forceRelease)
231     {
232         // End the association with the TextureStorage, since that data will be out of date.
233         // Also reset mRecoveredFromStorageCount since this Image is getting completely redefined.
234         disassociateStorage();
235         mRecoveredFromStorageCount = 0;
236 
237         mWidth          = size.width;
238         mHeight         = size.height;
239         mDepth          = size.depth;
240         mInternalFormat = internalformat;
241         mType           = type;
242 
243         // compute the d3d format that will be used
244         const d3d11::Format &formatInfo =
245             d3d11::Format::Get(internalformat, mRenderer->getRenderer11DeviceCaps());
246         mDXGIFormat = formatInfo.texFormat;
247         mRenderable = (formatInfo.rtvFormat != DXGI_FORMAT_UNKNOWN);
248 
249         releaseStagingTexture();
250         mDirty = (formatInfo.dataInitializerFunction != nullptr);
251 
252         return true;
253     }
254 
255     return false;
256 }
257 
getDXGIFormat() const258 DXGI_FORMAT Image11::getDXGIFormat() const
259 {
260     // this should only happen if the image hasn't been redefined first
261     // which would be a bug by the caller
262     ASSERT(mDXGIFormat != DXGI_FORMAT_UNKNOWN);
263 
264     return mDXGIFormat;
265 }
266 
267 // Store the pixel rectangle designated by xoffset,yoffset,width,height with pixels stored as
268 // format/type at input
269 // into the target pixel rectangle.
loadData(const gl::Context * context,const gl::Box & area,const gl::PixelUnpackState & unpack,GLenum type,const void * input,bool applySkipImages)270 angle::Result Image11::loadData(const gl::Context *context,
271                                 const gl::Box &area,
272                                 const gl::PixelUnpackState &unpack,
273                                 GLenum type,
274                                 const void *input,
275                                 bool applySkipImages)
276 {
277     Context11 *context11 = GetImplAs<Context11>(context);
278 
279     const gl::InternalFormat &formatInfo = gl::GetSizedInternalFormatInfo(mInternalFormat);
280     GLuint inputRowPitch                 = 0;
281     ANGLE_CHECK_GL_MATH(context11, formatInfo.computeRowPitch(type, area.width, unpack.alignment,
282                                                               unpack.rowLength, &inputRowPitch));
283     GLuint inputDepthPitch = 0;
284     ANGLE_CHECK_GL_MATH(context11, formatInfo.computeDepthPitch(area.height, unpack.imageHeight,
285                                                                 inputRowPitch, &inputDepthPitch));
286     GLuint inputSkipBytes = 0;
287     ANGLE_CHECK_GL_MATH(context11,
288                         formatInfo.computeSkipBytes(type, inputRowPitch, inputDepthPitch, unpack,
289                                                     applySkipImages, &inputSkipBytes));
290 
291     const d3d11::DXGIFormatSize &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(mDXGIFormat);
292     GLuint outputPixelSize                      = dxgiFormatInfo.pixelBytes;
293 
294     const d3d11::Format &d3dFormatInfo =
295         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
296     LoadImageFunction loadFunction = d3dFormatInfo.getLoadFunctions()(type).loadFunction;
297 
298     D3D11_MAPPED_SUBRESOURCE mappedImage;
299     ANGLE_TRY(map(context, D3D11_MAP_WRITE, &mappedImage));
300 
301     uint8_t *offsetMappedData = (static_cast<uint8_t *>(mappedImage.pData) +
302                                  (area.y * mappedImage.RowPitch + area.x * outputPixelSize +
303                                   area.z * mappedImage.DepthPitch));
304     loadFunction(context11->getImageLoadContext(), area.width, area.height, area.depth,
305                  static_cast<const uint8_t *>(input) + inputSkipBytes, inputRowPitch,
306                  inputDepthPitch, offsetMappedData, mappedImage.RowPitch, mappedImage.DepthPitch);
307 
308     unmap();
309 
310     return angle::Result::Continue;
311 }
312 
loadCompressedData(const gl::Context * context,const gl::Box & area,const void * input)313 angle::Result Image11::loadCompressedData(const gl::Context *context,
314                                           const gl::Box &area,
315                                           const void *input)
316 {
317     Context11 *context11 = GetImplAs<Context11>(context);
318 
319     const gl::InternalFormat &formatInfo = gl::GetSizedInternalFormatInfo(mInternalFormat);
320     GLuint inputRowPitch                 = 0;
321     ANGLE_CHECK_GL_MATH(
322         context11, formatInfo.computeRowPitch(GL_UNSIGNED_BYTE, area.width, 1, 0, &inputRowPitch));
323     GLuint inputDepthPitch = 0;
324     ANGLE_CHECK_GL_MATH(
325         context11, formatInfo.computeDepthPitch(area.height, 0, inputRowPitch, &inputDepthPitch));
326 
327     const d3d11::DXGIFormatSize &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(mDXGIFormat);
328     GLuint outputPixelSize                      = dxgiFormatInfo.pixelBytes;
329     GLuint outputBlockWidth                     = dxgiFormatInfo.blockWidth;
330     GLuint outputBlockHeight                    = dxgiFormatInfo.blockHeight;
331 
332     ASSERT(area.x % outputBlockWidth == 0);
333     ASSERT(area.y % outputBlockHeight == 0);
334 
335     const d3d11::Format &d3dFormatInfo =
336         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
337     LoadImageFunction loadFunction =
338         d3dFormatInfo.getLoadFunctions()(GL_UNSIGNED_BYTE).loadFunction;
339 
340     D3D11_MAPPED_SUBRESOURCE mappedImage;
341     ANGLE_TRY(map(context, D3D11_MAP_WRITE, &mappedImage));
342 
343     uint8_t *offsetMappedData =
344         static_cast<uint8_t *>(mappedImage.pData) +
345         ((area.y / outputBlockHeight) * mappedImage.RowPitch +
346          (area.x / outputBlockWidth) * outputPixelSize + area.z * mappedImage.DepthPitch);
347 
348     loadFunction(context11->getImageLoadContext(), area.width, area.height, area.depth,
349                  static_cast<const uint8_t *>(input), inputRowPitch, inputDepthPitch,
350                  offsetMappedData, mappedImage.RowPitch, mappedImage.DepthPitch);
351 
352     unmap();
353 
354     return angle::Result::Continue;
355 }
356 
copyFromTexStorage(const gl::Context * context,const gl::ImageIndex & imageIndex,TextureStorage * source)357 angle::Result Image11::copyFromTexStorage(const gl::Context *context,
358                                           const gl::ImageIndex &imageIndex,
359                                           TextureStorage *source)
360 {
361     TextureStorage11 *storage11 = GetAs<TextureStorage11>(source);
362 
363     const TextureHelper11 *textureHelper = nullptr;
364     ANGLE_TRY(storage11->getResource(context, &textureHelper));
365 
366     UINT subresourceIndex = 0;
367     ANGLE_TRY(storage11->getSubresourceIndex(context, imageIndex, &subresourceIndex));
368 
369     gl::Box sourceBox(0, 0, 0, mWidth, mHeight, mDepth);
370     return copyWithoutConversion(context, gl::Offset(), sourceBox, *textureHelper,
371                                  subresourceIndex);
372 }
373 
copyFromFramebuffer(const gl::Context * context,const gl::Offset & destOffset,const gl::Rectangle & sourceArea,const gl::Framebuffer * sourceFBO)374 angle::Result Image11::copyFromFramebuffer(const gl::Context *context,
375                                            const gl::Offset &destOffset,
376                                            const gl::Rectangle &sourceArea,
377                                            const gl::Framebuffer *sourceFBO)
378 {
379     Context11 *context11 = GetImplAs<Context11>(context);
380 
381     const gl::FramebufferAttachment *srcAttachment = sourceFBO->getReadColorAttachment();
382     ASSERT(srcAttachment);
383 
384     GLenum sourceInternalFormat = srcAttachment->getFormat().info->sizedInternalFormat;
385     const auto &d3d11Format =
386         d3d11::Format::Get(sourceInternalFormat, mRenderer->getRenderer11DeviceCaps());
387 
388     if (d3d11Format.texFormat == mDXGIFormat && sourceInternalFormat == mInternalFormat)
389     {
390         RenderTarget11 *rt11 = nullptr;
391         ANGLE_TRY(srcAttachment->getRenderTarget(context, 0, &rt11));
392         ASSERT(rt11->getTexture().get());
393 
394         TextureHelper11 textureHelper  = rt11->getTexture();
395         unsigned int sourceSubResource = rt11->getSubresourceIndex();
396 
397         gl::Box sourceBox(sourceArea.x, sourceArea.y, 0, sourceArea.width, sourceArea.height, 1);
398         return copyWithoutConversion(context, destOffset, sourceBox, textureHelper,
399                                      sourceSubResource);
400     }
401 
402     // This format requires conversion, so we must copy the texture to staging and manually convert
403     // via readPixels
404     D3D11_MAPPED_SUBRESOURCE mappedImage;
405     ANGLE_TRY(map(context, D3D11_MAP_WRITE, &mappedImage));
406 
407     // determine the offset coordinate into the destination buffer
408     const auto &dxgiFormatInfo = d3d11::GetDXGIFormatSizeInfo(mDXGIFormat);
409     GLsizei rowOffset          = dxgiFormatInfo.pixelBytes * destOffset.x;
410 
411     uint8_t *dataOffset = static_cast<uint8_t *>(mappedImage.pData) +
412                           mappedImage.RowPitch * destOffset.y + rowOffset +
413                           destOffset.z * mappedImage.DepthPitch;
414 
415     const gl::InternalFormat &destFormatInfo = gl::GetSizedInternalFormatInfo(mInternalFormat);
416     const auto &destD3D11Format =
417         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
418 
419     auto loadFunction    = destD3D11Format.getLoadFunctions()(destFormatInfo.type);
420     angle::Result result = angle::Result::Continue;
421     if (loadFunction.requiresConversion)
422     {
423         size_t bufferSize = destFormatInfo.pixelBytes * sourceArea.width * sourceArea.height;
424         angle::MemoryBuffer *memoryBuffer = nullptr;
425         result = mRenderer->getScratchMemoryBuffer(context11, bufferSize, &memoryBuffer);
426 
427         if (result == angle::Result::Continue)
428         {
429             GLuint memoryBufferRowPitch = destFormatInfo.pixelBytes * sourceArea.width;
430 
431             result = mRenderer->readFromAttachment(
432                 context, *srcAttachment, sourceArea, destFormatInfo.format, destFormatInfo.type,
433                 memoryBufferRowPitch, gl::PixelPackState(), memoryBuffer->data());
434 
435             loadFunction.loadFunction(context11->getImageLoadContext(), sourceArea.width,
436                                       sourceArea.height, 1, memoryBuffer->data(),
437                                       memoryBufferRowPitch, 0, dataOffset, mappedImage.RowPitch,
438                                       mappedImage.DepthPitch);
439         }
440     }
441     else
442     {
443         result = mRenderer->readFromAttachment(
444             context, *srcAttachment, sourceArea, destFormatInfo.format, destFormatInfo.type,
445             mappedImage.RowPitch, gl::PixelPackState(), dataOffset);
446     }
447 
448     unmap();
449     mDirty = true;
450 
451     return result;
452 }
453 
copyWithoutConversion(const gl::Context * context,const gl::Offset & destOffset,const gl::Box & sourceArea,const TextureHelper11 & textureHelper,UINT sourceSubResource)454 angle::Result Image11::copyWithoutConversion(const gl::Context *context,
455                                              const gl::Offset &destOffset,
456                                              const gl::Box &sourceArea,
457                                              const TextureHelper11 &textureHelper,
458                                              UINT sourceSubResource)
459 {
460     // No conversion needed-- use copyback fastpath
461     const TextureHelper11 *stagingTexture = nullptr;
462     unsigned int stagingSubresourceIndex  = 0;
463     ANGLE_TRY(getStagingTexture(context, &stagingTexture, &stagingSubresourceIndex));
464 
465     ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
466 
467     const gl::Extents &extents = textureHelper.getExtents();
468 
469     D3D11_BOX srcBox;
470     srcBox.left   = sourceArea.x;
471     srcBox.right  = sourceArea.x + sourceArea.width;
472     srcBox.top    = sourceArea.y;
473     srcBox.bottom = sourceArea.y + sourceArea.height;
474     srcBox.front  = sourceArea.z;
475     srcBox.back   = sourceArea.z + sourceArea.depth;
476 
477     if (textureHelper.is2D() && textureHelper.getSampleCount() > 1)
478     {
479         D3D11_TEXTURE2D_DESC resolveDesc;
480         resolveDesc.Width              = extents.width;
481         resolveDesc.Height             = extents.height;
482         resolveDesc.MipLevels          = 1;
483         resolveDesc.ArraySize          = 1;
484         resolveDesc.Format             = textureHelper.getFormat();
485         resolveDesc.SampleDesc.Count   = 1;
486         resolveDesc.SampleDesc.Quality = 0;
487         resolveDesc.Usage              = D3D11_USAGE_DEFAULT;
488         resolveDesc.BindFlags          = 0;
489         resolveDesc.CPUAccessFlags     = 0;
490         resolveDesc.MiscFlags          = 0;
491 
492         d3d11::Texture2D resolveTex;
493         ANGLE_TRY(
494             mRenderer->allocateResource(GetImplAs<Context11>(context), resolveDesc, &resolveTex));
495 
496         deviceContext->ResolveSubresource(resolveTex.get(), 0, textureHelper.get(),
497                                           sourceSubResource, textureHelper.getFormat());
498 
499         deviceContext->CopySubresourceRegion(stagingTexture->get(), stagingSubresourceIndex,
500                                              destOffset.x, destOffset.y, destOffset.z,
501                                              resolveTex.get(), 0, &srcBox);
502     }
503     else
504     {
505         deviceContext->CopySubresourceRegion(stagingTexture->get(), stagingSubresourceIndex,
506                                              destOffset.x, destOffset.y, destOffset.z,
507                                              textureHelper.get(), sourceSubResource, &srcBox);
508     }
509 
510     mDirty = true;
511     return angle::Result::Continue;
512 }
513 
getStagingTexture(const gl::Context * context,const TextureHelper11 ** outStagingTexture,unsigned int * outSubresourceIndex)514 angle::Result Image11::getStagingTexture(const gl::Context *context,
515                                          const TextureHelper11 **outStagingTexture,
516                                          unsigned int *outSubresourceIndex)
517 {
518     ANGLE_TRY(createStagingTexture(context));
519 
520     *outStagingTexture   = &mStagingTexture;
521     *outSubresourceIndex = mStagingSubresource;
522     return angle::Result::Continue;
523 }
524 
releaseStagingTexture()525 void Image11::releaseStagingTexture()
526 {
527     mStagingTexture.reset();
528     mStagingTextureSubresourceVerifier.reset();
529 }
530 
createStagingTexture(const gl::Context * context)531 angle::Result Image11::createStagingTexture(const gl::Context *context)
532 {
533     if (mStagingTexture.valid())
534     {
535         return angle::Result::Continue;
536     }
537 
538     ASSERT(mWidth > 0 && mHeight > 0 && mDepth > 0);
539 
540     const DXGI_FORMAT dxgiFormat = getDXGIFormat();
541     const auto &formatInfo =
542         d3d11::Format::Get(mInternalFormat, mRenderer->getRenderer11DeviceCaps());
543 
544     int lodOffset  = 1;
545     GLsizei width  = mWidth;
546     GLsizei height = mHeight;
547 
548     // adjust size if needed for compressed textures
549     d3d11::MakeValidSize(false, dxgiFormat, &width, &height, &lodOffset);
550 
551     Context11 *context11 = GetImplAs<Context11>(context);
552 
553     switch (mType)
554     {
555         case gl::TextureType::_3D:
556         {
557             D3D11_TEXTURE3D_DESC desc;
558             desc.Width          = width;
559             desc.Height         = height;
560             desc.Depth          = mDepth;
561             desc.MipLevels      = lodOffset + 1;
562             desc.Format         = dxgiFormat;
563             desc.Usage          = D3D11_USAGE_STAGING;
564             desc.BindFlags      = 0;
565             desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
566             desc.MiscFlags      = 0;
567 
568             if (formatInfo.dataInitializerFunction != nullptr)
569             {
570                 gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> initialData;
571                 ANGLE_TRY(d3d11::GenerateInitialTextureData(
572                     context, mInternalFormat, mRenderer->getRenderer11DeviceCaps(), width, height,
573                     mDepth, lodOffset + 1, &initialData));
574 
575                 ANGLE_TRY(mRenderer->allocateTexture(context11, desc, formatInfo,
576                                                      initialData.data(), &mStagingTexture));
577             }
578             else
579             {
580                 ANGLE_TRY(
581                     mRenderer->allocateTexture(context11, desc, formatInfo, &mStagingTexture));
582             }
583 
584             mStagingTexture.setInternalName("Image11::StagingTexture3D");
585             mStagingSubresource = D3D11CalcSubresource(lodOffset, 0, lodOffset + 1);
586             mStagingTextureSubresourceVerifier.setDesc(desc);
587         }
588         break;
589 
590         case gl::TextureType::_2D:
591         case gl::TextureType::_2DArray:
592         case gl::TextureType::CubeMap:
593         {
594             D3D11_TEXTURE2D_DESC desc;
595             desc.Width              = width;
596             desc.Height             = height;
597             desc.MipLevels          = lodOffset + 1;
598             desc.ArraySize          = 1;
599             desc.Format             = dxgiFormat;
600             desc.SampleDesc.Count   = 1;
601             desc.SampleDesc.Quality = 0;
602             desc.Usage              = D3D11_USAGE_STAGING;
603             desc.BindFlags          = 0;
604             desc.CPUAccessFlags     = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
605             desc.MiscFlags          = 0;
606 
607             if (formatInfo.dataInitializerFunction != nullptr)
608             {
609                 gl::TexLevelArray<D3D11_SUBRESOURCE_DATA> initialData;
610                 ANGLE_TRY(d3d11::GenerateInitialTextureData(
611                     context, mInternalFormat, mRenderer->getRenderer11DeviceCaps(), width, height,
612                     1, lodOffset + 1, &initialData));
613 
614                 ANGLE_TRY(mRenderer->allocateTexture(context11, desc, formatInfo,
615                                                      initialData.data(), &mStagingTexture));
616             }
617             else
618             {
619                 ANGLE_TRY(
620                     mRenderer->allocateTexture(context11, desc, formatInfo, &mStagingTexture));
621             }
622 
623             mStagingTexture.setInternalName("Image11::StagingTexture2D");
624             mStagingSubresource = D3D11CalcSubresource(lodOffset, 0, lodOffset + 1);
625             mStagingTextureSubresourceVerifier.setDesc(desc);
626         }
627         break;
628 
629         default:
630             UNREACHABLE();
631     }
632 
633     mDirty = false;
634     return angle::Result::Continue;
635 }
636 
map(const gl::Context * context,D3D11_MAP mapType,D3D11_MAPPED_SUBRESOURCE * map)637 angle::Result Image11::map(const gl::Context *context,
638                            D3D11_MAP mapType,
639                            D3D11_MAPPED_SUBRESOURCE *map)
640 {
641     // We must recover from the TextureStorage if necessary, even for D3D11_MAP_WRITE.
642     ANGLE_TRY(recoverFromAssociatedStorage(context));
643 
644     const TextureHelper11 *stagingTexture = nullptr;
645     unsigned int subresourceIndex         = 0;
646     ANGLE_TRY(getStagingTexture(context, &stagingTexture, &subresourceIndex));
647 
648     ASSERT(stagingTexture && stagingTexture->valid());
649 
650     ANGLE_TRY(
651         mRenderer->mapResource(context, stagingTexture->get(), subresourceIndex, mapType, 0, map));
652 
653     if (!mStagingTextureSubresourceVerifier.wrap(mapType, map))
654     {
655         ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
656         deviceContext->Unmap(mStagingTexture.get(), mStagingSubresource);
657         Context11 *context11 = GetImplAs<Context11>(context);
658         context11->handleError(GL_OUT_OF_MEMORY,
659                                "Failed to allocate staging texture mapping verifier buffer.",
660                                __FILE__, ANGLE_FUNCTION, __LINE__);
661         return angle::Result::Stop;
662     }
663 
664     mDirty = true;
665 
666     return angle::Result::Continue;
667 }
668 
unmap()669 void Image11::unmap()
670 {
671     if (mStagingTexture.valid())
672     {
673         mStagingTextureSubresourceVerifier.unwrap();
674         ID3D11DeviceContext *deviceContext = mRenderer->getDeviceContext();
675         deviceContext->Unmap(mStagingTexture.get(), mStagingSubresource);
676     }
677 }
678 
679 }  // namespace rx
680