• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 Google LLC
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/gpu/d3d/GrD3DGpu.h"
9 
10 #include "include/gpu/GrBackendSurface.h"
11 #include "include/gpu/d3d/GrD3DBackendContext.h"
12 #include "src/core/SkConvertPixels.h"
13 #include "src/core/SkMipmap.h"
14 #include "src/gpu/GrBackendUtils.h"
15 #include "src/gpu/GrDataUtils.h"
16 #include "src/gpu/GrTexture.h"
17 #include "src/gpu/GrThreadSafePipelineBuilder.h"
18 #include "src/gpu/d3d/GrD3DAMDMemoryAllocator.h"
19 #include "src/gpu/d3d/GrD3DAttachment.h"
20 #include "src/gpu/d3d/GrD3DBuffer.h"
21 #include "src/gpu/d3d/GrD3DCaps.h"
22 #include "src/gpu/d3d/GrD3DOpsRenderPass.h"
23 #include "src/gpu/d3d/GrD3DSemaphore.h"
24 #include "src/gpu/d3d/GrD3DTexture.h"
25 #include "src/gpu/d3d/GrD3DTextureRenderTarget.h"
26 #include "src/gpu/d3d/GrD3DUtil.h"
27 #include "src/sksl/SkSLCompiler.h"
28 
29 #if GR_TEST_UTILS
30 #include <DXProgrammableCapture.h>
31 #endif
32 
pipelineBuilder()33 GrThreadSafePipelineBuilder* GrD3DGpu::pipelineBuilder() {
34     return nullptr;
35 }
36 
refPipelineBuilder()37 sk_sp<GrThreadSafePipelineBuilder> GrD3DGpu::refPipelineBuilder() {
38     return nullptr;
39 }
40 
41 
Make(const GrD3DBackendContext & backendContext,const GrContextOptions & contextOptions,GrDirectContext * direct)42 sk_sp<GrGpu> GrD3DGpu::Make(const GrD3DBackendContext& backendContext,
43                             const GrContextOptions& contextOptions, GrDirectContext* direct) {
44     sk_sp<GrD3DMemoryAllocator> memoryAllocator = backendContext.fMemoryAllocator;
45     if (!memoryAllocator) {
46         // We were not given a memory allocator at creation
47         memoryAllocator = GrD3DAMDMemoryAllocator::Make(
48                 backendContext.fAdapter.get(), backendContext.fDevice.get());
49     }
50     if (!memoryAllocator) {
51         SkDEBUGFAIL("No supplied Direct3D memory allocator and unable to create one internally.");
52         return nullptr;
53     }
54 
55     return sk_sp<GrGpu>(new GrD3DGpu(direct, contextOptions, backendContext, memoryAllocator));
56 }
57 
58 // This constant determines how many OutstandingCommandLists are allocated together as a block in
59 // the deque. As such it needs to balance allocating too much memory vs. incurring
60 // allocation/deallocation thrashing. It should roughly correspond to the max number of outstanding
61 // command lists we expect to see.
62 static const int kDefaultOutstandingAllocCnt = 8;
63 
64 // constants have to be aligned to 256
65 constexpr int kConstantAlignment = 256;
66 
GrD3DGpu(GrDirectContext * direct,const GrContextOptions & contextOptions,const GrD3DBackendContext & backendContext,sk_sp<GrD3DMemoryAllocator> allocator)67 GrD3DGpu::GrD3DGpu(GrDirectContext* direct, const GrContextOptions& contextOptions,
68                    const GrD3DBackendContext& backendContext,
69                    sk_sp<GrD3DMemoryAllocator> allocator)
70         : INHERITED(direct)
71         , fDevice(backendContext.fDevice)
72         , fQueue(backendContext.fQueue)
73         , fMemoryAllocator(std::move(allocator))
74         , fResourceProvider(this)
75         , fStagingBufferManager(this)
76         , fConstantsRingBuffer(this, 128 * 1024, kConstantAlignment, GrGpuBufferType::kVertex)
77         , fOutstandingCommandLists(sizeof(OutstandingCommandList), kDefaultOutstandingAllocCnt) {
78     this->initCapsAndCompiler(sk_make_sp<GrD3DCaps>(contextOptions,
79                                                     backendContext.fAdapter.get(),
80                                                     backendContext.fDevice.get()));
81 
82     fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList();
83     SkASSERT(fCurrentDirectCommandList);
84 
85     SkASSERT(fCurrentFenceValue == 0);
86     GR_D3D_CALL_ERRCHECK(fDevice->CreateFence(fCurrentFenceValue, D3D12_FENCE_FLAG_NONE,
87                                               IID_PPV_ARGS(&fFence)));
88 
89 #if GR_TEST_UTILS
90     HRESULT getAnalysis = DXGIGetDebugInterface1(0, IID_PPV_ARGS(&fGraphicsAnalysis));
91     if (FAILED(getAnalysis)) {
92         fGraphicsAnalysis = nullptr;
93     }
94 #endif
95 }
96 
~GrD3DGpu()97 GrD3DGpu::~GrD3DGpu() {
98     this->destroyResources();
99 }
100 
destroyResources()101 void GrD3DGpu::destroyResources() {
102     if (fCurrentDirectCommandList) {
103         fCurrentDirectCommandList->close();
104         fCurrentDirectCommandList->reset();
105     }
106 
107     // We need to make sure everything has finished on the queue.
108     this->waitForQueueCompletion();
109 
110     SkDEBUGCODE(uint64_t fenceValue = fFence->GetCompletedValue();)
111 
112     // We used a placement new for each object in fOutstandingCommandLists, so we're responsible
113     // for calling the destructor on each of them as well.
114     while (!fOutstandingCommandLists.empty()) {
115         OutstandingCommandList* list = (OutstandingCommandList*)fOutstandingCommandLists.front();
116         SkASSERT(list->fFenceValue <= fenceValue);
117         // No reason to recycle the command lists since we are destroying all resources anyways.
118         list->~OutstandingCommandList();
119         fOutstandingCommandLists.pop_front();
120     }
121 
122     fStagingBufferManager.reset();
123 
124     fResourceProvider.destroyResources();
125 }
126 
onGetOpsRenderPass(GrRenderTarget * rt,bool,GrAttachment *,GrSurfaceOrigin origin,const SkIRect & bounds,const GrOpsRenderPass::LoadAndStoreInfo & colorInfo,const GrOpsRenderPass::StencilLoadAndStoreInfo & stencilInfo,const SkTArray<GrSurfaceProxy *,true> & sampledProxies,GrXferBarrierFlags renderPassXferBarriers)127 GrOpsRenderPass* GrD3DGpu::onGetOpsRenderPass(
128         GrRenderTarget* rt,
129         bool /*useMSAASurface*/,
130         GrAttachment*,
131         GrSurfaceOrigin origin,
132         const SkIRect& bounds,
133         const GrOpsRenderPass::LoadAndStoreInfo& colorInfo,
134         const GrOpsRenderPass::StencilLoadAndStoreInfo& stencilInfo,
135         const SkTArray<GrSurfaceProxy*, true>& sampledProxies,
136         GrXferBarrierFlags renderPassXferBarriers) {
137     if (!fCachedOpsRenderPass) {
138         fCachedOpsRenderPass.reset(new GrD3DOpsRenderPass(this));
139     }
140 
141     if (!fCachedOpsRenderPass->set(rt, origin, bounds, colorInfo, stencilInfo, sampledProxies)) {
142         return nullptr;
143     }
144     return fCachedOpsRenderPass.get();
145 }
146 
submitDirectCommandList(SyncQueue sync)147 bool GrD3DGpu::submitDirectCommandList(SyncQueue sync) {
148     SkASSERT(fCurrentDirectCommandList);
149 
150     fResourceProvider.prepForSubmit();
151     for (int i = 0; i < fMipmapCPUDescriptors.count(); ++i) {
152         fResourceProvider.recycleShaderView(fMipmapCPUDescriptors[i]);
153     }
154     fMipmapCPUDescriptors.reset();
155 
156     GrD3DDirectCommandList::SubmitResult result = fCurrentDirectCommandList->submit(fQueue.get());
157     if (result == GrD3DDirectCommandList::SubmitResult::kFailure) {
158         fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList();
159         return false;
160     } else if (result == GrD3DDirectCommandList::SubmitResult::kNoWork) {
161         if (sync == SyncQueue::kForce) {
162             this->waitForQueueCompletion();
163             this->checkForFinishedCommandLists();
164         }
165         return true;
166     }
167 
168     // We just submitted the command list so make sure all GrD3DPipelineState's mark their cached
169     // uniform data as dirty.
170     fResourceProvider.markPipelineStateUniformsDirty();
171 
172     GrFence fence = this->insertFence();
173     new (fOutstandingCommandLists.push_back()) OutstandingCommandList(
174             std::move(fCurrentDirectCommandList), fence);
175 
176     if (sync == SyncQueue::kForce) {
177         this->waitForQueueCompletion();
178     }
179 
180     fCurrentDirectCommandList = fResourceProvider.findOrCreateDirectCommandList();
181 
182     // This should be done after we have a new command list in case the freeing of any resources
183     // held by a finished command list causes us send a new command to the gpu (like changing the
184     // resource state.
185     this->checkForFinishedCommandLists();
186 
187     SkASSERT(fCurrentDirectCommandList);
188     return true;
189 }
190 
checkForFinishedCommandLists()191 void GrD3DGpu::checkForFinishedCommandLists() {
192     uint64_t currentFenceValue = fFence->GetCompletedValue();
193 
194     // Iterate over all the outstanding command lists to see if any have finished. The commands
195     // lists are in order from oldest to newest, so we start at the front to check if their fence
196     // value is less than the last signaled value. If so we pop it off and move onto the next.
197     // Repeat till we find a command list that has not finished yet (and all others afterwards are
198     // also guaranteed to not have finished).
199     OutstandingCommandList* front = (OutstandingCommandList*)fOutstandingCommandLists.front();
200     while (front && front->fFenceValue <= currentFenceValue) {
201         std::unique_ptr<GrD3DDirectCommandList> currList(std::move(front->fCommandList));
202         // Since we used placement new we are responsible for calling the destructor manually.
203         front->~OutstandingCommandList();
204         fOutstandingCommandLists.pop_front();
205         fResourceProvider.recycleDirectCommandList(std::move(currList));
206         front = (OutstandingCommandList*)fOutstandingCommandLists.front();
207     }
208 }
209 
waitForQueueCompletion()210 void GrD3DGpu::waitForQueueCompletion() {
211     if (fFence->GetCompletedValue() < fCurrentFenceValue) {
212         HANDLE fenceEvent;
213         fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
214         SkASSERT(fenceEvent);
215         GR_D3D_CALL_ERRCHECK(fFence->SetEventOnCompletion(fCurrentFenceValue, fenceEvent));
216         WaitForSingleObject(fenceEvent, INFINITE);
217         CloseHandle(fenceEvent);
218     }
219 }
220 
submit(GrOpsRenderPass * renderPass)221 void GrD3DGpu::submit(GrOpsRenderPass* renderPass) {
222     SkASSERT(fCachedOpsRenderPass.get() == renderPass);
223 
224     fCachedOpsRenderPass->submit();
225     fCachedOpsRenderPass.reset();
226 }
227 
endRenderPass(GrRenderTarget * target,GrSurfaceOrigin origin,const SkIRect & bounds)228 void GrD3DGpu::endRenderPass(GrRenderTarget* target, GrSurfaceOrigin origin,
229                              const SkIRect& bounds) {
230     this->didWriteToSurface(target, origin, &bounds);
231 }
232 
addFinishedProc(GrGpuFinishedProc finishedProc,GrGpuFinishedContext finishedContext)233 void GrD3DGpu::addFinishedProc(GrGpuFinishedProc finishedProc,
234                                GrGpuFinishedContext finishedContext) {
235     SkASSERT(finishedProc);
236     this->addFinishedCallback(GrRefCntedCallback::Make(finishedProc, finishedContext));
237 }
238 
addFinishedCallback(sk_sp<GrRefCntedCallback> finishedCallback)239 void GrD3DGpu::addFinishedCallback(sk_sp<GrRefCntedCallback> finishedCallback) {
240     SkASSERT(finishedCallback);
241     // Besides the current command list, we also add the finishedCallback to the newest outstanding
242     // command list. Our contract for calling the proc is that all previous submitted command lists
243     // have finished when we call it. However, if our current command list has no work when it is
244     // flushed it will drop its ref to the callback immediately. But the previous work may not have
245     // finished. It is safe to only add the proc to the newest outstanding commandlist cause that
246     // must finish after all previously submitted command lists.
247     OutstandingCommandList* back = (OutstandingCommandList*)fOutstandingCommandLists.back();
248     if (back) {
249         back->fCommandList->addFinishedCallback(finishedCallback);
250     }
251     fCurrentDirectCommandList->addFinishedCallback(std::move(finishedCallback));
252 }
253 
createD3DTexture(SkISize dimensions,DXGI_FORMAT dxgiFormat,GrRenderable renderable,int renderTargetSampleCnt,SkBudgeted budgeted,GrProtected isProtected,int mipLevelCount,GrMipmapStatus mipmapStatus)254 sk_sp<GrD3DTexture> GrD3DGpu::createD3DTexture(SkISize dimensions,
255                                                DXGI_FORMAT dxgiFormat,
256                                                GrRenderable renderable,
257                                                int renderTargetSampleCnt,
258                                                SkBudgeted budgeted,
259                                                GrProtected isProtected,
260                                                int mipLevelCount,
261                                                GrMipmapStatus mipmapStatus) {
262     D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE;
263     if (renderable == GrRenderable::kYes) {
264         usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
265     }
266 
267     // This desc refers to a texture that will be read by the client. Thus even if msaa is
268     // requested, this describes the resolved texture. Therefore we always have samples set
269     // to 1.
270     SkASSERT(mipLevelCount > 0);
271     D3D12_RESOURCE_DESC resourceDesc = {};
272     resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
273     // TODO: will use 4MB alignment for MSAA textures and 64KB for everything else
274     //       might want to manually set alignment to 4KB for smaller textures
275     resourceDesc.Alignment = 0;
276     resourceDesc.Width = dimensions.fWidth;
277     resourceDesc.Height = dimensions.fHeight;
278     resourceDesc.DepthOrArraySize = 1;
279     resourceDesc.MipLevels = mipLevelCount;
280     resourceDesc.Format = dxgiFormat;
281     resourceDesc.SampleDesc.Count = 1;
282     resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
283     resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;  // use driver-selected swizzle
284     resourceDesc.Flags = usageFlags;
285 
286     if (renderable == GrRenderable::kYes) {
287         return GrD3DTextureRenderTarget::MakeNewTextureRenderTarget(
288                 this, budgeted, dimensions, renderTargetSampleCnt, resourceDesc, isProtected,
289                 mipmapStatus);
290     } else {
291         return GrD3DTexture::MakeNewTexture(this, budgeted, dimensions, resourceDesc, isProtected,
292                                             mipmapStatus);
293     }
294 }
295 
onCreateTexture(SkISize dimensions,const GrBackendFormat & format,GrRenderable renderable,int renderTargetSampleCnt,SkBudgeted budgeted,GrProtected isProtected,int mipLevelCount,uint32_t levelClearMask)296 sk_sp<GrTexture> GrD3DGpu::onCreateTexture(SkISize dimensions,
297                                            const GrBackendFormat& format,
298                                            GrRenderable renderable,
299                                            int renderTargetSampleCnt,
300                                            SkBudgeted budgeted,
301                                            GrProtected isProtected,
302                                            int mipLevelCount,
303                                            uint32_t levelClearMask) {
304     DXGI_FORMAT dxgiFormat;
305     SkAssertResult(format.asDxgiFormat(&dxgiFormat));
306     SkASSERT(!GrDxgiFormatIsCompressed(dxgiFormat));
307 
308     GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kDirty
309                                                     : GrMipmapStatus::kNotAllocated;
310 
311     sk_sp<GrD3DTexture> tex = this->createD3DTexture(dimensions, dxgiFormat, renderable,
312                                                      renderTargetSampleCnt, budgeted, isProtected,
313                                                      mipLevelCount, mipmapStatus);
314     if (!tex) {
315         return nullptr;
316     }
317 
318     if (levelClearMask) {
319         // TODO
320     }
321 
322     return std::move(tex);
323 }
324 
copy_compressed_data(char * mapPtr,DXGI_FORMAT dxgiFormat,D3D12_PLACED_SUBRESOURCE_FOOTPRINT * placedFootprints,UINT * numRows,UINT64 * rowSizeInBytes,const void * compressedData,int numMipLevels)325 static void copy_compressed_data(char* mapPtr, DXGI_FORMAT dxgiFormat,
326                                  D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints,
327                                  UINT* numRows, UINT64* rowSizeInBytes,
328                                  const void* compressedData, int numMipLevels) {
329     SkASSERT(compressedData && numMipLevels);
330     SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat));
331     SkASSERT(mapPtr);
332 
333     const char* src = static_cast<const char*>(compressedData);
334     for (int currentMipLevel = 0; currentMipLevel < numMipLevels; currentMipLevel++) {
335         // copy data into the buffer, skipping any trailing bytes
336         char* dst = mapPtr + placedFootprints[currentMipLevel].Offset;
337         SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch,
338                      src, rowSizeInBytes[currentMipLevel], rowSizeInBytes[currentMipLevel],
339                      numRows[currentMipLevel]);
340         src += numRows[currentMipLevel] * rowSizeInBytes[currentMipLevel];
341     }
342 }
343 
onCreateCompressedTexture(SkISize dimensions,const GrBackendFormat & format,SkBudgeted budgeted,GrMipmapped mipMapped,GrProtected isProtected,const void * data,size_t dataSize)344 sk_sp<GrTexture> GrD3DGpu::onCreateCompressedTexture(SkISize dimensions,
345                                                      const GrBackendFormat& format,
346                                                      SkBudgeted budgeted,
347                                                      GrMipmapped mipMapped,
348                                                      GrProtected isProtected,
349                                                      const void* data, size_t dataSize) {
350     DXGI_FORMAT dxgiFormat;
351     SkAssertResult(format.asDxgiFormat(&dxgiFormat));
352     SkASSERT(GrDxgiFormatIsCompressed(dxgiFormat));
353 
354     SkDEBUGCODE(SkImage::CompressionType compression = GrBackendFormatToCompressionType(format));
355     SkASSERT(dataSize == SkCompressedFormatDataSize(compression, dimensions,
356                                                     mipMapped == GrMipmapped::kYes));
357 
358     int mipLevelCount = 1;
359     if (mipMapped == GrMipmapped::kYes) {
360         mipLevelCount = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1;
361     }
362     GrMipmapStatus mipmapStatus = mipLevelCount > 1 ? GrMipmapStatus::kValid
363                                                     : GrMipmapStatus::kNotAllocated;
364 
365     sk_sp<GrD3DTexture> d3dTex = this->createD3DTexture(dimensions, dxgiFormat, GrRenderable::kNo,
366                                                      1, budgeted, isProtected,
367                                                      mipLevelCount, mipmapStatus);
368     if (!d3dTex) {
369         return nullptr;
370     }
371 
372     ID3D12Resource* d3dResource = d3dTex->d3dResource();
373     SkASSERT(d3dResource);
374     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
375     // Either upload only the first miplevel or all miplevels
376     SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels);
377 
378     SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
379     SkAutoTMalloc<UINT> numRows(mipLevelCount);
380     SkAutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount);
381     UINT64 combinedBufferSize;
382     // We reset the width and height in the description to match our subrectangle size
383     // so we don't end up allocating more space than we need.
384     desc.Width = dimensions.width();
385     desc.Height = dimensions.height();
386     fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(),
387                                    numRows.get(), rowSizeInBytes.get(), &combinedBufferSize);
388     SkASSERT(combinedBufferSize);
389 
390     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
391             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
392     if (!slice.fBuffer) {
393         return nullptr;
394     }
395 
396     char* bufferData = (char*)slice.fOffsetMapPtr;
397 
398     copy_compressed_data(bufferData, desc.Format, placedFootprints.get(), numRows.get(),
399                          rowSizeInBytes.get(), data, mipLevelCount);
400 
401     // Update the offsets in the footprints to be relative to the slice's offset
402     for (int i = 0; i < mipLevelCount; ++i) {
403         placedFootprints[i].Offset += slice.fOffset;
404     }
405 
406     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
407     fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer, d3dTex.get(), mipLevelCount,
408                                                    placedFootprints.get(), 0, 0);
409 
410     return std::move(d3dTex);
411 }
412 
get_surface_sample_cnt(GrSurface * surf)413 static int get_surface_sample_cnt(GrSurface* surf) {
414     if (const GrRenderTarget* rt = surf->asRenderTarget()) {
415         return rt->numSamples();
416     }
417     return 0;
418 }
419 
onCopySurface(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)420 bool GrD3DGpu::onCopySurface(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
421                    const SkIPoint& dstPoint) {
422 
423     if (src->isProtected() && !dst->isProtected()) {
424         SkDebugf("Can't copy from protected memory to non-protected");
425         return false;
426     }
427 
428     int dstSampleCnt = get_surface_sample_cnt(dst);
429     int srcSampleCnt = get_surface_sample_cnt(src);
430 
431     GrD3DTextureResource* dstTexResource;
432     GrD3DTextureResource* srcTexResource;
433     GrRenderTarget* dstRT = dst->asRenderTarget();
434     if (dstRT) {
435         GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(dstRT);
436         dstTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT;
437     } else {
438         SkASSERT(dst->asTexture());
439         dstTexResource = static_cast<GrD3DTexture*>(dst->asTexture());
440     }
441     GrRenderTarget* srcRT = src->asRenderTarget();
442     if (srcRT) {
443         GrD3DRenderTarget* d3dRT = static_cast<GrD3DRenderTarget*>(srcRT);
444         srcTexResource = d3dRT->numSamples() > 1 ? d3dRT->msaaTextureResource() : d3dRT;
445     } else {
446         SkASSERT(src->asTexture());
447         srcTexResource = static_cast<GrD3DTexture*>(src->asTexture());
448     }
449 
450     DXGI_FORMAT dstFormat = dstTexResource->dxgiFormat();
451     DXGI_FORMAT srcFormat = srcTexResource->dxgiFormat();
452 
453     if (this->d3dCaps().canCopyAsResolve(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) {
454         this->copySurfaceAsResolve(dst, src, srcRect, dstPoint);
455         return true;
456     }
457 
458     if (this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt)) {
459         this->copySurfaceAsCopyTexture(dst, src, dstTexResource, srcTexResource, srcRect, dstPoint);
460         return true;
461     }
462 
463     return false;
464 }
465 
copySurfaceAsCopyTexture(GrSurface * dst,GrSurface * src,GrD3DTextureResource * dstResource,GrD3DTextureResource * srcResource,const SkIRect & srcRect,const SkIPoint & dstPoint)466 void GrD3DGpu::copySurfaceAsCopyTexture(GrSurface* dst, GrSurface* src,
467                                         GrD3DTextureResource* dstResource,
468                                         GrD3DTextureResource* srcResource,
469                                         const SkIRect& srcRect, const SkIPoint& dstPoint) {
470 #ifdef SK_DEBUG
471     int dstSampleCnt = get_surface_sample_cnt(dst);
472     int srcSampleCnt = get_surface_sample_cnt(src);
473     DXGI_FORMAT dstFormat = dstResource->dxgiFormat();
474     DXGI_FORMAT srcFormat;
475     SkAssertResult(dst->backendFormat().asDxgiFormat(&srcFormat));
476     SkASSERT(this->d3dCaps().canCopyTexture(dstFormat, dstSampleCnt, srcFormat, srcSampleCnt));
477 #endif
478     if (src->isProtected() && !dst->isProtected()) {
479         SkDebugf("Can't copy from protected memory to non-protected");
480         return;
481     }
482 
483     dstResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
484     srcResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
485 
486     D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
487     dstLocation.pResource = dstResource->d3dResource();
488     dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
489     dstLocation.SubresourceIndex = 0;
490 
491     D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
492     srcLocation.pResource = srcResource->d3dResource();
493     srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
494     srcLocation.SubresourceIndex = 0;
495 
496     D3D12_BOX srcBox = {};
497     srcBox.left = srcRect.fLeft;
498     srcBox.top = srcRect.fTop;
499     srcBox.right = srcRect.fRight;
500     srcBox.bottom = srcRect.fBottom;
501     srcBox.front = 0;
502     srcBox.back = 1;
503     // TODO: use copyResource if copying full resource and sizes match
504     fCurrentDirectCommandList->copyTextureRegionToTexture(dstResource->resource(),
505                                                           &dstLocation,
506                                                           dstPoint.fX, dstPoint.fY,
507                                                           srcResource->resource(),
508                                                           &srcLocation,
509                                                           &srcBox);
510 
511     SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
512                                         srcRect.width(), srcRect.height());
513     // The rect is already in device space so we pass in kTopLeft so no flip is done.
514     this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
515 }
516 
copySurfaceAsResolve(GrSurface * dst,GrSurface * src,const SkIRect & srcRect,const SkIPoint & dstPoint)517 void GrD3DGpu::copySurfaceAsResolve(GrSurface* dst, GrSurface* src, const SkIRect& srcRect,
518                                     const SkIPoint& dstPoint) {
519     GrD3DRenderTarget* srcRT = static_cast<GrD3DRenderTarget*>(src->asRenderTarget());
520     SkASSERT(srcRT);
521 
522     this->resolveTexture(dst, dstPoint.fX, dstPoint.fY, srcRT, srcRect);
523     SkIRect dstRect = SkIRect::MakeXYWH(dstPoint.fX, dstPoint.fY,
524                                         srcRect.width(), srcRect.height());
525     // The rect is already in device space so we pass in kTopLeft so no flip is done.
526     this->didWriteToSurface(dst, kTopLeft_GrSurfaceOrigin, &dstRect);
527 }
528 
resolveTexture(GrSurface * dst,int32_t dstX,int32_t dstY,GrD3DRenderTarget * src,const SkIRect & srcIRect)529 void GrD3DGpu::resolveTexture(GrSurface* dst, int32_t dstX, int32_t dstY,
530                               GrD3DRenderTarget* src, const SkIRect& srcIRect) {
531     SkASSERT(dst);
532     SkASSERT(src && src->numSamples() > 1 && src->msaaTextureResource());
533 
534     D3D12_RECT srcRect = { srcIRect.fLeft, srcIRect.fTop, srcIRect.fRight, srcIRect.fBottom };
535 
536     GrD3DTextureResource* dstTextureResource;
537     GrRenderTarget* dstRT = dst->asRenderTarget();
538     if (dstRT) {
539         dstTextureResource = static_cast<GrD3DRenderTarget*>(dstRT);
540     } else {
541         SkASSERT(dst->asTexture());
542         dstTextureResource = static_cast<GrD3DTexture*>(dst->asTexture());
543     }
544 
545     dstTextureResource->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_DEST);
546     src->msaaTextureResource()->setResourceState(this, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
547 
548     fCurrentDirectCommandList->resolveSubresourceRegion(dstTextureResource, dstX, dstY,
549                                                         src->msaaTextureResource(), &srcRect);
550 }
551 
onResolveRenderTarget(GrRenderTarget * target,const SkIRect & resolveRect)552 void GrD3DGpu::onResolveRenderTarget(GrRenderTarget* target, const SkIRect& resolveRect) {
553     SkASSERT(target->numSamples() > 1);
554     GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(target);
555     SkASSERT(rt->msaaTextureResource() && rt != rt->msaaTextureResource());
556 
557     this->resolveTexture(target, resolveRect.fLeft, resolveRect.fTop, rt, resolveRect);
558 }
559 
onReadPixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType dstColorType,void * buffer,size_t rowBytes)560 bool GrD3DGpu::onReadPixels(GrSurface* surface,
561                             SkIRect rect,
562                             GrColorType surfaceColorType,
563                             GrColorType dstColorType,
564                             void* buffer,
565                             size_t rowBytes) {
566     SkASSERT(surface);
567 
568     if (surfaceColorType != dstColorType) {
569         return false;
570     }
571 
572     GrD3DTextureResource* texResource = nullptr;
573     GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget());
574     if (rt) {
575         texResource = rt;
576     } else {
577         texResource = static_cast<GrD3DTexture*>(surface->asTexture());
578     }
579 
580     if (!texResource) {
581         return false;
582     }
583 
584     D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc();
585     D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint;
586     UINT64 transferTotalBytes;
587     fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint,
588                                    nullptr, nullptr, &transferTotalBytes);
589     SkASSERT(transferTotalBytes);
590     // TODO: implement some way of reusing buffers instead of making a new one every time.
591     sk_sp<GrGpuBuffer> transferBuffer = this->createBuffer(transferTotalBytes,
592                                                            GrGpuBufferType::kXferGpuToCpu,
593                                                            kDynamic_GrAccessPattern);
594 
595     this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint);
596     this->submitDirectCommandList(SyncQueue::kForce);
597 
598     // Copy back to CPU buffer
599     size_t bpp = GrColorTypeBytesPerPixel(dstColorType);
600     if (GrDxgiFormatBytesPerBlock(texResource->dxgiFormat()) != bpp) {
601         return false;
602     }
603     size_t tightRowBytes = bpp * rect.width();
604 
605     const void* mappedMemory = transferBuffer->map();
606 
607     SkRectMemcpy(buffer,
608                  rowBytes,
609                  mappedMemory,
610                  placedFootprint.Footprint.RowPitch,
611                  tightRowBytes,
612                  rect.height());
613 
614     transferBuffer->unmap();
615 
616     return true;
617 }
618 
readOrTransferPixels(GrD3DTextureResource * texResource,SkIRect rect,sk_sp<GrGpuBuffer> transferBuffer,const D3D12_PLACED_SUBRESOURCE_FOOTPRINT & placedFootprint)619 void GrD3DGpu::readOrTransferPixels(GrD3DTextureResource* texResource,
620                                     SkIRect rect,
621                                     sk_sp<GrGpuBuffer> transferBuffer,
622                                     const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& placedFootprint) {
623     // Set up src location and box
624     D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
625     srcLocation.pResource = texResource->d3dResource();
626     SkASSERT(srcLocation.pResource);
627     srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
628     srcLocation.SubresourceIndex = 0;
629 
630     D3D12_BOX srcBox = {};
631     srcBox.left = rect.left();
632     srcBox.top = rect.top();
633     srcBox.right = rect.right();
634     srcBox.bottom = rect.bottom();
635     srcBox.front = 0;
636     srcBox.back = 1;
637 
638     // Set up dst location
639     D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
640     dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
641     dstLocation.PlacedFootprint = placedFootprint;
642     GrD3DBuffer* d3dBuf = static_cast<GrD3DBuffer*>(transferBuffer.get());
643     dstLocation.pResource = d3dBuf->d3dResource();
644 
645     // Need to change the resource state to COPY_SOURCE in order to download from it
646     texResource->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
647 
648     fCurrentDirectCommandList->copyTextureRegionToBuffer(transferBuffer, &dstLocation, 0, 0,
649                                                          texResource->resource(), &srcLocation,
650                                                          &srcBox);
651 }
652 
onWritePixels(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType srcColorType,const GrMipLevel texels[],int mipLevelCount,bool prepForTexSampling)653 bool GrD3DGpu::onWritePixels(GrSurface* surface,
654                              SkIRect rect,
655                              GrColorType surfaceColorType,
656                              GrColorType srcColorType,
657                              const GrMipLevel texels[],
658                              int mipLevelCount,
659                              bool prepForTexSampling) {
660     GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(surface->asTexture());
661     if (!d3dTex) {
662         return false;
663     }
664 
665     // Make sure we have at least the base level
666     if (!mipLevelCount || !texels[0].fPixels) {
667         return false;
668     }
669 
670     SkASSERT(!GrDxgiFormatIsCompressed(d3dTex->dxgiFormat()));
671     bool success = false;
672 
673     // Need to change the resource state to COPY_DEST in order to upload to it
674     d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
675 
676     SkASSERT(mipLevelCount <= d3dTex->maxMipmapLevel() + 1);
677     success = this->uploadToTexture(d3dTex, rect, srcColorType, texels, mipLevelCount);
678 
679     if (prepForTexSampling) {
680         d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
681     }
682 
683     return success;
684 }
685 
uploadToTexture(GrD3DTexture * tex,SkIRect rect,GrColorType colorType,const GrMipLevel * texels,int mipLevelCount)686 bool GrD3DGpu::uploadToTexture(GrD3DTexture* tex,
687                                SkIRect rect,
688                                GrColorType colorType,
689                                const GrMipLevel* texels,
690                                int mipLevelCount) {
691     SkASSERT(this->d3dCaps().isFormatTexturable(tex->dxgiFormat()));
692     // The assumption is either that we have no mipmaps, or that our rect is the entire texture
693     SkASSERT(mipLevelCount == 1 || rect == SkIRect::MakeSize(tex->dimensions()));
694 
695     // We assume that if the texture has mip levels, we either upload to all the levels or just the
696     // first.
697     SkASSERT(mipLevelCount == 1 || mipLevelCount == (tex->maxMipmapLevel() + 1));
698 
699     if (rect.isEmpty()) {
700         return false;
701     }
702 
703     SkASSERT(this->d3dCaps().surfaceSupportsWritePixels(tex));
704     SkASSERT(this->d3dCaps().areColorTypeAndFormatCompatible(colorType, tex->backendFormat()));
705 
706     ID3D12Resource* d3dResource = tex->d3dResource();
707     SkASSERT(d3dResource);
708     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
709     // Either upload only the first miplevel or all miplevels
710     SkASSERT(1 == mipLevelCount || mipLevelCount == (int)desc.MipLevels);
711 
712     if (1 == mipLevelCount && !texels[0].fPixels) {
713         return true;   // no data to upload
714     }
715 
716     for (int i = 0; i < mipLevelCount; ++i) {
717         // We do not allow any gaps in the mip data
718         if (!texels[i].fPixels) {
719             return false;
720         }
721     }
722 
723     SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
724     UINT64 combinedBufferSize;
725     // We reset the width and height in the description to match our subrectangle size
726     // so we don't end up allocating more space than we need.
727     desc.Width = rect.width();
728     desc.Height = rect.height();
729     fDevice->GetCopyableFootprints(&desc, 0, mipLevelCount, 0, placedFootprints.get(),
730                                    nullptr, nullptr, &combinedBufferSize);
731     size_t bpp = GrColorTypeBytesPerPixel(colorType);
732     SkASSERT(combinedBufferSize);
733 
734     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
735             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
736     if (!slice.fBuffer) {
737         return false;
738     }
739 
740     char* bufferData = (char*)slice.fOffsetMapPtr;
741 
742     int currentWidth = rect.width();
743     int currentHeight = rect.height();
744     for (int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) {
745         if (texels[currentMipLevel].fPixels) {
746 
747             const size_t trimRowBytes = currentWidth * bpp;
748             const size_t srcRowBytes = texels[currentMipLevel].fRowBytes;
749 
750             char* dst = bufferData + placedFootprints[currentMipLevel].Offset;
751 
752             // copy data into the buffer, skipping any trailing bytes
753             const char* src = (const char*)texels[currentMipLevel].fPixels;
754             SkRectMemcpy(dst, placedFootprints[currentMipLevel].Footprint.RowPitch,
755                          src, srcRowBytes, trimRowBytes, currentHeight);
756         }
757         currentWidth = std::max(1, currentWidth / 2);
758         currentHeight = std::max(1, currentHeight / 2);
759     }
760 
761     // Update the offsets in the footprints to be relative to the slice's offset
762     for (int i = 0; i < mipLevelCount; ++i) {
763         placedFootprints[i].Offset += slice.fOffset;
764     }
765 
766     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
767     fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer,
768                                                    tex,
769                                                    mipLevelCount,
770                                                    placedFootprints.get(),
771                                                    rect.left(),
772                                                    rect.top());
773 
774     if (mipLevelCount < (int)desc.MipLevels) {
775         tex->markMipmapsDirty();
776     }
777 
778     return true;
779 }
780 
onTransferPixelsTo(GrTexture * texture,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t bufferOffset,size_t rowBytes)781 bool GrD3DGpu::onTransferPixelsTo(GrTexture* texture,
782                                   SkIRect rect,
783                                   GrColorType surfaceColorType,
784                                   GrColorType bufferColorType,
785                                   sk_sp<GrGpuBuffer> transferBuffer,
786                                   size_t bufferOffset,
787                                   size_t rowBytes) {
788     if (!this->currentCommandList()) {
789         return false;
790     }
791 
792     if (!transferBuffer) {
793         return false;
794     }
795 
796     size_t bpp = GrColorTypeBytesPerPixel(bufferColorType);
797     if (GrBackendFormatBytesPerPixel(texture->backendFormat()) != bpp) {
798         return false;
799     }
800 
801     // D3D requires offsets for texture transfers to be aligned to this value
802     if (SkToBool(bufferOffset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) {
803         return false;
804     }
805 
806     GrD3DTexture* d3dTex = static_cast<GrD3DTexture*>(texture);
807     if (!d3dTex) {
808         return false;
809     }
810 
811     SkDEBUGCODE(DXGI_FORMAT format = d3dTex->dxgiFormat());
812 
813     // Can't transfer compressed data
814     SkASSERT(!GrDxgiFormatIsCompressed(format));
815 
816     SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType));
817 
818     SkASSERT(SkIRect::MakeSize(texture->dimensions()).contains(rect));
819 
820     // Set up copy region
821     D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint = {};
822     ID3D12Resource* d3dResource = d3dTex->d3dResource();
823     SkASSERT(d3dResource);
824     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
825     desc.Width = rect.width();
826     desc.Height = rect.height();
827     UINT64 totalBytes;
828     fDevice->GetCopyableFootprints(&desc, 0, 1, 0, &placedFootprint,
829                                    nullptr, nullptr, &totalBytes);
830     placedFootprint.Offset = bufferOffset;
831 
832     // Change state of our target so it can be copied to
833     d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
834 
835     // Copy the buffer to the image.
836     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(transferBuffer.get())->d3dResource();
837     fCurrentDirectCommandList->copyBufferToTexture(d3dBuffer,
838                                                    d3dTex,
839                                                    1,
840                                                    &placedFootprint,
841                                                    rect.left(),
842                                                    rect.top());
843     this->currentCommandList()->addGrBuffer(std::move(transferBuffer));
844 
845     d3dTex->markMipmapsDirty();
846     return true;
847 }
848 
onTransferPixelsFrom(GrSurface * surface,SkIRect rect,GrColorType surfaceColorType,GrColorType bufferColorType,sk_sp<GrGpuBuffer> transferBuffer,size_t offset)849 bool GrD3DGpu::onTransferPixelsFrom(GrSurface* surface,
850                                     SkIRect rect,
851                                     GrColorType surfaceColorType,
852                                     GrColorType bufferColorType,
853                                     sk_sp<GrGpuBuffer> transferBuffer,
854                                     size_t offset) {
855     if (!this->currentCommandList()) {
856         return false;
857     }
858     SkASSERT(surface);
859     SkASSERT(transferBuffer);
860     // TODO
861     //if (fProtectedContext == GrProtected::kYes) {
862     //    return false;
863     //}
864 
865     // D3D requires offsets for texture transfers to be aligned to this value
866     if (SkToBool(offset & (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT-1))) {
867         return false;
868     }
869 
870     GrD3DTextureResource* texResource = nullptr;
871     GrD3DRenderTarget* rt = static_cast<GrD3DRenderTarget*>(surface->asRenderTarget());
872     if (rt) {
873         texResource = rt;
874     } else {
875         texResource = static_cast<GrD3DTexture*>(surface->asTexture());
876     }
877 
878     if (!texResource) {
879         return false;
880     }
881 
882     SkDEBUGCODE(DXGI_FORMAT format = texResource->dxgiFormat());
883     SkASSERT(GrDxgiFormatBytesPerBlock(format) == GrColorTypeBytesPerPixel(bufferColorType));
884 
885     D3D12_RESOURCE_DESC desc = texResource->d3dResource()->GetDesc();
886     desc.Width = rect.width();
887     desc.Height = rect.height();
888     D3D12_PLACED_SUBRESOURCE_FOOTPRINT placedFootprint;
889     UINT64 transferTotalBytes;
890     fDevice->GetCopyableFootprints(&desc, 0, 1, offset, &placedFootprint,
891                                    nullptr, nullptr, &transferTotalBytes);
892     SkASSERT(transferTotalBytes);
893 
894     this->readOrTransferPixels(texResource, rect, transferBuffer, placedFootprint);
895 
896     // TODO: It's not clear how to ensure the transfer is done before we read from the buffer,
897     // other than maybe doing a resource state transition.
898 
899     return true;
900 }
901 
check_resource_info(const GrD3DTextureResourceInfo & info)902 static bool check_resource_info(const GrD3DTextureResourceInfo& info) {
903     if (!info.fResource.get()) {
904         return false;
905     }
906     return true;
907 }
908 
check_tex_resource_info(const GrD3DCaps & caps,const GrD3DTextureResourceInfo & info)909 static bool check_tex_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info) {
910     if (!caps.isFormatTexturable(info.fFormat)) {
911         return false;
912     }
913     // We don't support sampling from multisampled textures.
914     if (info.fSampleCount != 1) {
915         return false;
916     }
917     return true;
918 }
919 
check_rt_resource_info(const GrD3DCaps & caps,const GrD3DTextureResourceInfo & info,int sampleCnt)920 static bool check_rt_resource_info(const GrD3DCaps& caps, const GrD3DTextureResourceInfo& info,
921                                 int sampleCnt) {
922     if (!caps.isFormatRenderable(info.fFormat, sampleCnt)) {
923         return false;
924     }
925     return true;
926 }
927 
onWrapBackendTexture(const GrBackendTexture & tex,GrWrapOwnership,GrWrapCacheable wrapType,GrIOType ioType)928 sk_sp<GrTexture> GrD3DGpu::onWrapBackendTexture(const GrBackendTexture& tex,
929                                                 GrWrapOwnership,
930                                                 GrWrapCacheable wrapType,
931                                                 GrIOType ioType) {
932     GrD3DTextureResourceInfo textureInfo;
933     if (!tex.getD3DTextureResourceInfo(&textureInfo)) {
934         return nullptr;
935     }
936 
937     if (!check_resource_info(textureInfo)) {
938         return nullptr;
939     }
940 
941     if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) {
942         return nullptr;
943     }
944 
945     // TODO: support protected context
946     if (tex.isProtected()) {
947         return nullptr;
948     }
949 
950     sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState();
951     SkASSERT(state);
952     return GrD3DTexture::MakeWrappedTexture(this, tex.dimensions(), wrapType, ioType, textureInfo,
953                                             std::move(state));
954 }
955 
onWrapCompressedBackendTexture(const GrBackendTexture & tex,GrWrapOwnership ownership,GrWrapCacheable wrapType)956 sk_sp<GrTexture> GrD3DGpu::onWrapCompressedBackendTexture(const GrBackendTexture& tex,
957                                                           GrWrapOwnership ownership,
958                                                           GrWrapCacheable wrapType) {
959     return this->onWrapBackendTexture(tex, ownership, wrapType, kRead_GrIOType);
960 }
961 
onWrapRenderableBackendTexture(const GrBackendTexture & tex,int sampleCnt,GrWrapOwnership ownership,GrWrapCacheable cacheable)962 sk_sp<GrTexture> GrD3DGpu::onWrapRenderableBackendTexture(const GrBackendTexture& tex,
963                                                           int sampleCnt,
964                                                           GrWrapOwnership ownership,
965                                                           GrWrapCacheable cacheable) {
966     GrD3DTextureResourceInfo textureInfo;
967     if (!tex.getD3DTextureResourceInfo(&textureInfo)) {
968         return nullptr;
969     }
970 
971     if (!check_resource_info(textureInfo)) {
972         return nullptr;
973     }
974 
975     if (!check_tex_resource_info(this->d3dCaps(), textureInfo)) {
976         return nullptr;
977     }
978     if (!check_rt_resource_info(this->d3dCaps(), textureInfo, sampleCnt)) {
979         return nullptr;
980     }
981 
982     // TODO: support protected context
983     if (tex.isProtected()) {
984         return nullptr;
985     }
986 
987     sampleCnt = this->d3dCaps().getRenderTargetSampleCount(sampleCnt, textureInfo.fFormat);
988 
989     sk_sp<GrD3DResourceState> state = tex.getGrD3DResourceState();
990     SkASSERT(state);
991 
992     return GrD3DTextureRenderTarget::MakeWrappedTextureRenderTarget(this, tex.dimensions(),
993                                                                     sampleCnt, cacheable,
994                                                                     textureInfo, std::move(state));
995 }
996 
onWrapBackendRenderTarget(const GrBackendRenderTarget & rt)997 sk_sp<GrRenderTarget> GrD3DGpu::onWrapBackendRenderTarget(const GrBackendRenderTarget& rt) {
998     GrD3DTextureResourceInfo info;
999     if (!rt.getD3DTextureResourceInfo(&info)) {
1000         return nullptr;
1001     }
1002 
1003     if (!check_resource_info(info)) {
1004         return nullptr;
1005     }
1006 
1007     if (!check_rt_resource_info(this->d3dCaps(), info, rt.sampleCnt())) {
1008         return nullptr;
1009     }
1010 
1011     // TODO: support protected context
1012     if (rt.isProtected()) {
1013         return nullptr;
1014     }
1015 
1016     sk_sp<GrD3DResourceState> state = rt.getGrD3DResourceState();
1017 
1018     sk_sp<GrD3DRenderTarget> tgt = GrD3DRenderTarget::MakeWrappedRenderTarget(
1019             this, rt.dimensions(), rt.sampleCnt(), info, std::move(state));
1020 
1021     // We don't allow the client to supply a premade stencil buffer. We always create one if needed.
1022     SkASSERT(!rt.stencilBits());
1023     if (tgt) {
1024         SkASSERT(tgt->canAttemptStencilAttachment(tgt->numSamples() > 1));
1025     }
1026 
1027     return std::move(tgt);
1028 }
1029 
is_odd(int x)1030 static bool is_odd(int x) {
1031     return x > 1 && SkToBool(x & 0x1);
1032 }
1033 
1034 // TODO: enable when sRGB shader supported
1035 //static bool is_srgb(DXGI_FORMAT format) {
1036 //    // the only one we support at the moment
1037 //    return (format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);
1038 //}
1039 
is_bgra(DXGI_FORMAT format)1040 static bool is_bgra(DXGI_FORMAT format) {
1041     // the only one we support at the moment
1042     return (format == DXGI_FORMAT_B8G8R8A8_UNORM);
1043 }
1044 
onRegenerateMipMapLevels(GrTexture * tex)1045 bool GrD3DGpu::onRegenerateMipMapLevels(GrTexture * tex) {
1046     auto * d3dTex = static_cast<GrD3DTexture*>(tex);
1047     SkASSERT(tex->textureType() == GrTextureType::k2D);
1048     int width = tex->width();
1049     int height = tex->height();
1050 
1051     // determine if we can read from and mipmap this format
1052     const GrD3DCaps & caps = this->d3dCaps();
1053     if (!caps.isFormatTexturable(d3dTex->dxgiFormat()) ||
1054         !caps.mipmapSupport()) {
1055         return false;
1056     }
1057 
1058     sk_sp<GrD3DTexture> uavTexture;
1059     sk_sp<GrD3DTexture> bgraAliasTexture;
1060     DXGI_FORMAT originalFormat = d3dTex->dxgiFormat();
1061     D3D12_RESOURCE_DESC originalDesc = d3dTex->d3dResource()->GetDesc();
1062     // if the format is unordered accessible and resource flag is set, use resource for uav
1063     if (caps.isFormatUnorderedAccessible(originalFormat) &&
1064         (originalDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) {
1065         uavTexture = sk_ref_sp(d3dTex);
1066     } else {
1067         // need to make a copy and use that for our uav
1068         D3D12_RESOURCE_DESC uavDesc = originalDesc;
1069         uavDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
1070         // if the format is unordered accessible, copy to resource with same format and flag set
1071         if (!caps.isFormatUnorderedAccessible(originalFormat)) {
1072             // for the BGRA and sRGB cases, we find a suitable RGBA format to use instead
1073             if (is_bgra(originalFormat)) {
1074                 uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1075                 // Technically if this support is not available we should not be doing
1076                 // aliasing. However, on Intel the BGRA and RGBA swizzle appears to be
1077                 // the same so it still works. We may need to disable BGRA support
1078                 // on a case-by-base basis if this doesn't hold true in general.
1079                 if (caps.standardSwizzleLayoutSupport()) {
1080                     uavDesc.Layout = D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE;
1081                 }
1082             // TODO: enable when sRGB shader supported
1083             //} else if (is_srgb(originalFormat)) {
1084             //    uavDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
1085             } else {
1086                 return false;
1087             }
1088         }
1089         // TODO: make this a scratch texture
1090         GrProtected grProtected = tex->isProtected() ? GrProtected::kYes : GrProtected::kNo;
1091         uavTexture = GrD3DTexture::MakeNewTexture(this, SkBudgeted::kNo, tex->dimensions(),
1092                                                   uavDesc, grProtected, GrMipmapStatus::kDirty);
1093         if (!uavTexture) {
1094             return false;
1095         }
1096 
1097         d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
1098         if (!caps.isFormatUnorderedAccessible(originalFormat) && is_bgra(originalFormat)) {
1099             // for BGRA, we alias this uavTexture with a BGRA texture and copy to that
1100             bgraAliasTexture = GrD3DTexture::MakeAliasingTexture(this, uavTexture, originalDesc,
1101                                                                  D3D12_RESOURCE_STATE_COPY_DEST);
1102             // make the BGRA version the active alias
1103             this->currentCommandList()->aliasingBarrier(nullptr,
1104                                                         nullptr,
1105                                                         bgraAliasTexture->resource(),
1106                                                         bgraAliasTexture->d3dResource());
1107             // copy top miplevel to bgraAliasTexture (should already be in COPY_DEST state)
1108             this->currentCommandList()->copyTextureToTexture(bgraAliasTexture.get(), d3dTex, 0);
1109             // make the RGBA version the active alias
1110             this->currentCommandList()->aliasingBarrier(bgraAliasTexture->resource(),
1111                                                         bgraAliasTexture->d3dResource(),
1112                                                         uavTexture->resource(),
1113                                                         uavTexture->d3dResource());
1114         } else {
1115             // copy top miplevel to uavTexture
1116             uavTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1117             this->currentCommandList()->copyTextureToTexture(uavTexture.get(), d3dTex, 0);
1118         }
1119     }
1120 
1121     uint32_t levelCount = d3dTex->mipLevels();
1122     // SkMipmap doesn't include the base level in the level count so we have to add 1
1123     SkASSERT((int)levelCount == SkMipmap::ComputeLevelCount(tex->width(), tex->height()) + 1);
1124 
1125     sk_sp<GrD3DRootSignature> rootSig = fResourceProvider.findOrCreateRootSignature(1, 1);
1126     this->currentCommandList()->setComputeRootSignature(rootSig);
1127 
1128     // TODO: use linear vs. srgb shader based on texture format
1129     sk_sp<GrD3DPipeline> pipeline = this->resourceProvider().findOrCreateMipmapPipeline();
1130     SkASSERT(pipeline);
1131     this->currentCommandList()->setPipelineState(std::move(pipeline));
1132 
1133     // set sampler
1134     GrSamplerState samplerState(SkFilterMode::kLinear, SkMipmapMode::kNearest);
1135     std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> samplers(1);
1136     samplers[0] = fResourceProvider.findOrCreateCompatibleSampler(samplerState);
1137     this->currentCommandList()->addSampledTextureRef(uavTexture.get());
1138     sk_sp<GrD3DDescriptorTable> samplerTable = fResourceProvider.findOrCreateSamplerTable(samplers);
1139 
1140     // Transition the top subresource to be readable in the compute shader
1141     D3D12_RESOURCE_STATES currentResourceState = uavTexture->currentState();
1142     D3D12_RESOURCE_TRANSITION_BARRIER barrier;
1143     barrier.pResource = uavTexture->d3dResource();
1144     barrier.Subresource = 0;
1145     barrier.StateBefore = currentResourceState;
1146     barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1147     this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1148 
1149     // Generate the miplevels
1150     for (unsigned int dstMip = 1; dstMip < levelCount; ++dstMip) {
1151         unsigned int srcMip = dstMip - 1;
1152         width = std::max(1, width / 2);
1153         height = std::max(1, height / 2);
1154 
1155         unsigned int sampleMode = 0;
1156         if (is_odd(width) && is_odd(height)) {
1157             sampleMode = 1;
1158         } else if (is_odd(width)) {
1159             sampleMode = 2;
1160         } else if (is_odd(height)) {
1161             sampleMode = 3;
1162         }
1163 
1164         // set constants
1165         struct {
1166             SkSize inverseSize;
1167             uint32_t mipLevel;
1168             uint32_t sampleMode;
1169         } constantData = { {1.f / width, 1.f / height}, srcMip, sampleMode };
1170 
1171         D3D12_GPU_VIRTUAL_ADDRESS constantsAddress =
1172             fResourceProvider.uploadConstantData(&constantData, sizeof(constantData));
1173         this->currentCommandList()->setComputeRootConstantBufferView(
1174                 (unsigned int)GrD3DRootSignature::ParamIndex::kConstantBufferView,
1175                 constantsAddress);
1176 
1177         std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> shaderViews;
1178         // create SRV
1179         GrD3DDescriptorHeap::CPUHandle srvHandle =
1180                 fResourceProvider.createShaderResourceView(uavTexture->d3dResource(), srcMip, 1);
1181         shaderViews.push_back(srvHandle.fHandle);
1182         fMipmapCPUDescriptors.push_back(srvHandle);
1183         // create UAV
1184         GrD3DDescriptorHeap::CPUHandle uavHandle =
1185                 fResourceProvider.createUnorderedAccessView(uavTexture->d3dResource(), dstMip);
1186         shaderViews.push_back(uavHandle.fHandle);
1187         fMipmapCPUDescriptors.push_back(uavHandle);
1188 
1189         // set up shaderView descriptor table
1190         sk_sp<GrD3DDescriptorTable> srvTable =
1191                 fResourceProvider.findOrCreateShaderViewTable(shaderViews);
1192 
1193         // bind both descriptor tables
1194         this->currentCommandList()->setDescriptorHeaps(srvTable->heap(), samplerTable->heap());
1195         this->currentCommandList()->setComputeRootDescriptorTable(
1196                 (unsigned int)GrD3DRootSignature::ParamIndex::kShaderViewDescriptorTable,
1197                 srvTable->baseGpuDescriptor());
1198         this->currentCommandList()->setComputeRootDescriptorTable(
1199                 static_cast<unsigned int>(GrD3DRootSignature::ParamIndex::kSamplerDescriptorTable),
1200                 samplerTable->baseGpuDescriptor());
1201 
1202         // Transition resource state of dstMip subresource so we can write to it
1203         barrier.Subresource = dstMip;
1204         barrier.StateBefore = currentResourceState;
1205         barrier.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
1206         this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1207 
1208         // Using the form (x+7)/8 ensures that the remainder is covered as well
1209         this->currentCommandList()->dispatch((width+7)/8, (height+7)/8);
1210 
1211         // guarantee UAV writes have completed
1212         this->currentCommandList()->uavBarrier(uavTexture->resource(), uavTexture->d3dResource());
1213 
1214         // Transition resource state of dstMip subresource so we can read it in the next stage
1215         barrier.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
1216         barrier.StateAfter = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1217         this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1218     }
1219 
1220     // copy back if necessary
1221     if (uavTexture.get() != d3dTex) {
1222         d3dTex->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1223         if (bgraAliasTexture) {
1224             // make the BGRA version the active alias
1225             this->currentCommandList()->aliasingBarrier(uavTexture->resource(),
1226                                                         uavTexture->d3dResource(),
1227                                                         bgraAliasTexture->resource(),
1228                                                         bgraAliasTexture->d3dResource());
1229             // copy from bgraAliasTexture to d3dTex
1230             bgraAliasTexture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_SOURCE);
1231             this->currentCommandList()->copyTextureToTexture(d3dTex, bgraAliasTexture.get());
1232         } else {
1233             barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1234             barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1235             barrier.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
1236             this->addResourceBarriers(uavTexture->resource(), 1, &barrier);
1237             this->currentCommandList()->copyTextureToTexture(d3dTex, uavTexture.get());
1238         }
1239     } else {
1240         // For simplicity our resource state tracking considers all subresources to have the same
1241         // state. However, we've changed that state one subresource at a time without going through
1242         // the tracking system, so we need to patch up the resource states back to the original.
1243         barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1244         barrier.StateBefore = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1245         barrier.StateAfter = currentResourceState;
1246         this->addResourceBarriers(d3dTex->resource(), 1, &barrier);
1247     }
1248 
1249     return true;
1250 }
1251 
onCreateBuffer(size_t sizeInBytes,GrGpuBufferType type,GrAccessPattern accessPattern,const void * data)1252 sk_sp<GrGpuBuffer> GrD3DGpu::onCreateBuffer(size_t sizeInBytes, GrGpuBufferType type,
1253                                              GrAccessPattern accessPattern, const void* data) {
1254     sk_sp<GrD3DBuffer> buffer = GrD3DBuffer::Make(this, sizeInBytes, type, accessPattern);
1255     if (data && buffer) {
1256         buffer->updateData(data, sizeInBytes);
1257     }
1258 
1259     return std::move(buffer);
1260 }
1261 
makeStencilAttachment(const GrBackendFormat &,SkISize dimensions,int numStencilSamples)1262 sk_sp<GrAttachment> GrD3DGpu::makeStencilAttachment(const GrBackendFormat& /*colorFormat*/,
1263                                                     SkISize dimensions, int numStencilSamples) {
1264     DXGI_FORMAT sFmt = this->d3dCaps().preferredStencilFormat();
1265 
1266     fStats.incStencilAttachmentCreates();
1267     return GrD3DAttachment::MakeStencil(this, dimensions, numStencilSamples, sFmt);
1268 }
1269 
createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat,SkISize dimensions,GrTexturable texturable,GrRenderable renderable,GrMipmapped mipMapped,int sampleCnt,GrD3DTextureResourceInfo * info,GrProtected isProtected)1270 bool GrD3DGpu::createTextureResourceForBackendSurface(DXGI_FORMAT dxgiFormat,
1271                                                       SkISize dimensions,
1272                                                       GrTexturable texturable,
1273                                                       GrRenderable renderable,
1274                                                       GrMipmapped mipMapped,
1275                                                       int sampleCnt,
1276                                                       GrD3DTextureResourceInfo* info,
1277                                                       GrProtected isProtected) {
1278     SkASSERT(texturable == GrTexturable::kYes || renderable == GrRenderable::kYes);
1279 
1280     if (this->protectedContext() != (isProtected == GrProtected::kYes)) {
1281         return false;
1282     }
1283 
1284     if (texturable == GrTexturable::kYes && !this->d3dCaps().isFormatTexturable(dxgiFormat)) {
1285         return false;
1286     }
1287 
1288     if (renderable == GrRenderable::kYes && !this->d3dCaps().isFormatRenderable(dxgiFormat, 1)) {
1289         return false;
1290     }
1291 
1292     int numMipLevels = 1;
1293     if (mipMapped == GrMipmapped::kYes) {
1294         numMipLevels = SkMipmap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1;
1295     }
1296 
1297     // create the texture
1298     D3D12_RESOURCE_FLAGS usageFlags = D3D12_RESOURCE_FLAG_NONE;
1299     if (renderable == GrRenderable::kYes) {
1300         usageFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
1301     }
1302 
1303     D3D12_RESOURCE_DESC resourceDesc = {};
1304     resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1305     resourceDesc.Alignment = 0;  // use default alignment
1306     resourceDesc.Width = dimensions.fWidth;
1307     resourceDesc.Height = dimensions.fHeight;
1308     resourceDesc.DepthOrArraySize = 1;
1309     resourceDesc.MipLevels = numMipLevels;
1310     resourceDesc.Format = dxgiFormat;
1311     resourceDesc.SampleDesc.Count = sampleCnt;
1312     resourceDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;
1313     resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;  // use driver-selected swizzle
1314     resourceDesc.Flags = usageFlags;
1315 
1316     D3D12_CLEAR_VALUE* clearValuePtr = nullptr;
1317     D3D12_CLEAR_VALUE clearValue = {};
1318     if (renderable == GrRenderable::kYes) {
1319         clearValue.Format = dxgiFormat;
1320         // Assume transparent black
1321         clearValue.Color[0] = 0;
1322         clearValue.Color[1] = 0;
1323         clearValue.Color[2] = 0;
1324         clearValue.Color[3] = 0;
1325         clearValuePtr = &clearValue;
1326     }
1327 
1328     D3D12_RESOURCE_STATES initialState = (renderable == GrRenderable::kYes)
1329                                                  ? D3D12_RESOURCE_STATE_RENDER_TARGET
1330                                                  : D3D12_RESOURCE_STATE_COPY_DEST;
1331     if (!GrD3DTextureResource::InitTextureResourceInfo(this, resourceDesc, initialState,
1332                                                        isProtected, clearValuePtr, info)) {
1333         SkDebugf("Failed to init texture resource info\n");
1334         return false;
1335     }
1336 
1337     return true;
1338 }
1339 
onCreateBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrRenderable renderable,GrMipmapped mipMapped,GrProtected isProtected)1340 GrBackendTexture GrD3DGpu::onCreateBackendTexture(SkISize dimensions,
1341                                                   const GrBackendFormat& format,
1342                                                   GrRenderable renderable,
1343                                                   GrMipmapped mipMapped,
1344                                                   GrProtected isProtected) {
1345     const GrD3DCaps& caps = this->d3dCaps();
1346 
1347     if (this->protectedContext() != (isProtected == GrProtected::kYes)) {
1348         return {};
1349     }
1350 
1351     DXGI_FORMAT dxgiFormat;
1352     if (!format.asDxgiFormat(&dxgiFormat)) {
1353         return {};
1354     }
1355 
1356     // TODO: move the texturability check up to GrGpu::createBackendTexture and just assert here
1357     if (!caps.isFormatTexturable(dxgiFormat)) {
1358         return {};
1359     }
1360 
1361     GrD3DTextureResourceInfo info;
1362     if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kYes,
1363                                                       renderable, mipMapped, 1, &info,
1364                                                       isProtected)) {
1365         return {};
1366     }
1367 
1368     return GrBackendTexture(dimensions.width(), dimensions.height(), info);
1369 }
1370 
copy_color_data(const GrD3DCaps & caps,char * mapPtr,DXGI_FORMAT dxgiFormat,SkISize dimensions,D3D12_PLACED_SUBRESOURCE_FOOTPRINT * placedFootprints,std::array<float,4> color)1371 static bool copy_color_data(const GrD3DCaps& caps,
1372                             char* mapPtr,
1373                             DXGI_FORMAT dxgiFormat,
1374                             SkISize dimensions,
1375                             D3D12_PLACED_SUBRESOURCE_FOOTPRINT* placedFootprints,
1376                             std::array<float, 4> color) {
1377     auto colorType = caps.getFormatColorType(dxgiFormat);
1378     if (colorType == GrColorType::kUnknown) {
1379         return false;
1380     }
1381     GrImageInfo ii(colorType, kUnpremul_SkAlphaType, nullptr, dimensions);
1382     if (!GrClearImage(ii, mapPtr, placedFootprints[0].Footprint.RowPitch, color)) {
1383         return false;
1384     }
1385 
1386     return true;
1387 }
1388 
onClearBackendTexture(const GrBackendTexture & backendTexture,sk_sp<GrRefCntedCallback> finishedCallback,std::array<float,4> color)1389 bool GrD3DGpu::onClearBackendTexture(const GrBackendTexture& backendTexture,
1390                                      sk_sp<GrRefCntedCallback> finishedCallback,
1391                                      std::array<float, 4> color) {
1392     GrD3DTextureResourceInfo info;
1393     SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info));
1394     SkASSERT(!GrDxgiFormatIsCompressed(info.fFormat));
1395 
1396     sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState();
1397     SkASSERT(state);
1398     sk_sp<GrD3DTexture> texture =
1399             GrD3DTexture::MakeWrappedTexture(this, backendTexture.dimensions(),
1400                                              GrWrapCacheable::kNo,
1401                                              kRW_GrIOType, info, std::move(state));
1402     if (!texture) {
1403         return false;
1404     }
1405 
1406     GrD3DDirectCommandList* cmdList = this->currentCommandList();
1407     if (!cmdList) {
1408         return false;
1409     }
1410 
1411     texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1412 
1413     ID3D12Resource* d3dResource = texture->d3dResource();
1414     SkASSERT(d3dResource);
1415     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
1416     unsigned int mipLevelCount = 1;
1417     if (backendTexture.fMipmapped == GrMipmapped::kYes) {
1418         mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions()) + 1;
1419     }
1420     SkASSERT(mipLevelCount == info.fLevelCount);
1421     SkAutoSTMalloc<15, D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
1422     UINT numRows;
1423     UINT64 rowSizeInBytes;
1424     UINT64 combinedBufferSize;
1425     // We reuse the same top-level buffer area for all levels, hence passing 1 for level count.
1426     fDevice->GetCopyableFootprints(&desc,
1427                                    /* first resource  */ 0,
1428                                    /* mip level count */ 1,
1429                                    /* base offset     */ 0,
1430                                    placedFootprints.get(),
1431                                    &numRows,
1432                                    &rowSizeInBytes,
1433                                    &combinedBufferSize);
1434     SkASSERT(combinedBufferSize);
1435 
1436     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
1437             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
1438     if (!slice.fBuffer) {
1439         return false;
1440     }
1441 
1442     char* bufferData = (char*)slice.fOffsetMapPtr;
1443     SkASSERT(bufferData);
1444     if (!copy_color_data(this->d3dCaps(),
1445                          bufferData,
1446                          info.fFormat,
1447                          backendTexture.dimensions(),
1448                          placedFootprints,
1449                          color)) {
1450         return false;
1451     }
1452     // Update the offsets in the footprint to be relative to the slice's offset
1453     placedFootprints[0].Offset += slice.fOffset;
1454     // Since we're sharing data for all the levels, set all the upper level footprints to the base.
1455     UINT w = placedFootprints[0].Footprint.Width;
1456     UINT h = placedFootprints[0].Footprint.Height;
1457     for (unsigned int i = 1; i < mipLevelCount; ++i) {
1458         w = std::max(1U, w/2);
1459         h = std::max(1U, h/2);
1460         placedFootprints[i].Offset = placedFootprints[0].Offset;
1461         placedFootprints[i].Footprint.Format   = placedFootprints[0].Footprint.Format;
1462         placedFootprints[i].Footprint.Width    = w;
1463         placedFootprints[i].Footprint.Height   = h;
1464         placedFootprints[i].Footprint.Depth    = 1;
1465         placedFootprints[i].Footprint.RowPitch = placedFootprints[0].Footprint.RowPitch;
1466     }
1467 
1468     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
1469     cmdList->copyBufferToTexture(d3dBuffer,
1470                                  texture.get(),
1471                                  mipLevelCount,
1472                                  placedFootprints.get(),
1473                                  /*left*/ 0,
1474                                  /*top */ 0);
1475 
1476     if (finishedCallback) {
1477         this->addFinishedCallback(std::move(finishedCallback));
1478     }
1479 
1480     return true;
1481 }
1482 
onCreateCompressedBackendTexture(SkISize dimensions,const GrBackendFormat & format,GrMipmapped mipMapped,GrProtected isProtected)1483 GrBackendTexture GrD3DGpu::onCreateCompressedBackendTexture(
1484     SkISize dimensions, const GrBackendFormat& format, GrMipmapped mipMapped,
1485     GrProtected isProtected) {
1486     return this->onCreateBackendTexture(dimensions, format, GrRenderable::kNo, mipMapped,
1487                                         isProtected);
1488 }
1489 
onUpdateCompressedBackendTexture(const GrBackendTexture & backendTexture,sk_sp<GrRefCntedCallback> finishedCallback,const void * data,size_t size)1490 bool GrD3DGpu::onUpdateCompressedBackendTexture(const GrBackendTexture& backendTexture,
1491                                                 sk_sp<GrRefCntedCallback> finishedCallback,
1492                                                 const void* data,
1493                                                 size_t size) {
1494     GrD3DTextureResourceInfo info;
1495     SkAssertResult(backendTexture.getD3DTextureResourceInfo(&info));
1496 
1497     sk_sp<GrD3DResourceState> state = backendTexture.getGrD3DResourceState();
1498     SkASSERT(state);
1499     sk_sp<GrD3DTexture> texture = GrD3DTexture::MakeWrappedTexture(this,
1500                                                                    backendTexture.dimensions(),
1501                                                                    GrWrapCacheable::kNo,
1502                                                                    kRW_GrIOType,
1503                                                                    info,
1504                                                                    std::move(state));
1505     if (!texture) {
1506         return false;
1507     }
1508 
1509     GrD3DDirectCommandList* cmdList = this->currentCommandList();
1510     if (!cmdList) {
1511         return false;
1512     }
1513 
1514     texture->setResourceState(this, D3D12_RESOURCE_STATE_COPY_DEST);
1515 
1516     ID3D12Resource* d3dResource = texture->d3dResource();
1517     SkASSERT(d3dResource);
1518     D3D12_RESOURCE_DESC desc = d3dResource->GetDesc();
1519     unsigned int mipLevelCount = 1;
1520     if (backendTexture.hasMipmaps()) {
1521         mipLevelCount = SkMipmap::ComputeLevelCount(backendTexture.dimensions().width(),
1522                                                     backendTexture.dimensions().height()) + 1;
1523     }
1524     SkASSERT(mipLevelCount == info.fLevelCount);
1525     SkAutoTMalloc<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> placedFootprints(mipLevelCount);
1526     UINT64 combinedBufferSize;
1527     SkAutoTMalloc<UINT> numRows(mipLevelCount);
1528     SkAutoTMalloc<UINT64> rowSizeInBytes(mipLevelCount);
1529     fDevice->GetCopyableFootprints(&desc,
1530                                    0,
1531                                    mipLevelCount,
1532                                    0,
1533                                    placedFootprints.get(),
1534                                    numRows.get(),
1535                                    rowSizeInBytes.get(),
1536                                    &combinedBufferSize);
1537     SkASSERT(combinedBufferSize);
1538     SkASSERT(GrDxgiFormatIsCompressed(info.fFormat));
1539 
1540     GrStagingBufferManager::Slice slice = fStagingBufferManager.allocateStagingBufferSlice(
1541             combinedBufferSize, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT);
1542     if (!slice.fBuffer) {
1543         return false;
1544     }
1545 
1546     char* bufferData = (char*)slice.fOffsetMapPtr;
1547     SkASSERT(bufferData);
1548     copy_compressed_data(bufferData,
1549                          info.fFormat,
1550                          placedFootprints.get(),
1551                          numRows.get(),
1552                          rowSizeInBytes.get(),
1553                          data,
1554                          info.fLevelCount);
1555 
1556     // Update the offsets in the footprints to be relative to the slice's offset
1557     for (unsigned int i = 0; i < mipLevelCount; ++i) {
1558         placedFootprints[i].Offset += slice.fOffset;
1559     }
1560 
1561     ID3D12Resource* d3dBuffer = static_cast<GrD3DBuffer*>(slice.fBuffer)->d3dResource();
1562     cmdList->copyBufferToTexture(d3dBuffer,
1563                                  texture.get(),
1564                                  mipLevelCount,
1565                                  placedFootprints.get(),
1566                                  0,
1567                                  0);
1568 
1569     if (finishedCallback) {
1570         this->addFinishedCallback(std::move(finishedCallback));
1571     }
1572 
1573     return true;
1574 }
1575 
deleteBackendTexture(const GrBackendTexture & tex)1576 void GrD3DGpu::deleteBackendTexture(const GrBackendTexture& tex) {
1577     SkASSERT(GrBackendApi::kDirect3D == tex.fBackend);
1578     // Nothing to do here, will get cleaned up when the GrBackendTexture object goes away
1579 }
1580 
compile(const GrProgramDesc &,const GrProgramInfo &)1581 bool GrD3DGpu::compile(const GrProgramDesc&, const GrProgramInfo&) {
1582     return false;
1583 }
1584 
1585 #if GR_TEST_UTILS
isTestingOnlyBackendTexture(const GrBackendTexture & tex) const1586 bool GrD3DGpu::isTestingOnlyBackendTexture(const GrBackendTexture& tex) const {
1587     SkASSERT(GrBackendApi::kDirect3D == tex.backend());
1588 
1589     GrD3DTextureResourceInfo info;
1590     if (!tex.getD3DTextureResourceInfo(&info)) {
1591         return false;
1592     }
1593     ID3D12Resource* textureResource = info.fResource.get();
1594     if (!textureResource) {
1595         return false;
1596     }
1597     return !(textureResource->GetDesc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE);
1598 }
1599 
createTestingOnlyBackendRenderTarget(SkISize dimensions,GrColorType colorType,int sampleCnt,GrProtected isProtected)1600 GrBackendRenderTarget GrD3DGpu::createTestingOnlyBackendRenderTarget(SkISize dimensions,
1601                                                                      GrColorType colorType,
1602                                                                      int sampleCnt,
1603                                                                      GrProtected isProtected) {
1604     if (dimensions.width()  > this->caps()->maxRenderTargetSize() ||
1605         dimensions.height() > this->caps()->maxRenderTargetSize()) {
1606         return {};
1607     }
1608 
1609     DXGI_FORMAT dxgiFormat = this->d3dCaps().getFormatFromColorType(colorType);
1610 
1611     GrD3DTextureResourceInfo info;
1612     if (!this->createTextureResourceForBackendSurface(dxgiFormat, dimensions, GrTexturable::kNo,
1613                                                       GrRenderable::kYes, GrMipmapped::kNo,
1614                                                       sampleCnt, &info, isProtected)) {
1615         return {};
1616     }
1617 
1618     return GrBackendRenderTarget(dimensions.width(), dimensions.height(), info);
1619 }
1620 
deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget & rt)1621 void GrD3DGpu::deleteTestingOnlyBackendRenderTarget(const GrBackendRenderTarget& rt) {
1622     SkASSERT(GrBackendApi::kDirect3D == rt.backend());
1623 
1624     GrD3DTextureResourceInfo info;
1625     if (rt.getD3DTextureResourceInfo(&info)) {
1626         this->submitToGpu(true);
1627         // Nothing else to do here, will get cleaned up when the GrBackendRenderTarget
1628         // is deleted.
1629     }
1630 }
1631 
testingOnly_startCapture()1632 void GrD3DGpu::testingOnly_startCapture() {
1633     if (fGraphicsAnalysis) {
1634         fGraphicsAnalysis->BeginCapture();
1635     }
1636 }
1637 
testingOnly_endCapture()1638 void GrD3DGpu::testingOnly_endCapture() {
1639     if (fGraphicsAnalysis) {
1640         fGraphicsAnalysis->EndCapture();
1641     }
1642 }
1643 #endif
1644 
1645 ///////////////////////////////////////////////////////////////////////////////
1646 
addResourceBarriers(sk_sp<GrManagedResource> resource,int numBarriers,D3D12_RESOURCE_TRANSITION_BARRIER * barriers) const1647 void GrD3DGpu::addResourceBarriers(sk_sp<GrManagedResource> resource,
1648                                    int numBarriers,
1649                                    D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const {
1650     SkASSERT(fCurrentDirectCommandList);
1651     SkASSERT(resource);
1652 
1653     fCurrentDirectCommandList->resourceBarrier(std::move(resource), numBarriers, barriers);
1654 }
1655 
addBufferResourceBarriers(GrD3DBuffer * buffer,int numBarriers,D3D12_RESOURCE_TRANSITION_BARRIER * barriers) const1656 void GrD3DGpu::addBufferResourceBarriers(GrD3DBuffer* buffer,
1657                                          int numBarriers,
1658                                          D3D12_RESOURCE_TRANSITION_BARRIER* barriers) const {
1659     SkASSERT(fCurrentDirectCommandList);
1660     SkASSERT(buffer);
1661 
1662     fCurrentDirectCommandList->resourceBarrier(nullptr, numBarriers, barriers);
1663     fCurrentDirectCommandList->addGrBuffer(sk_ref_sp<const GrBuffer>(buffer));
1664 }
1665 
1666 
prepareSurfacesForBackendAccessAndStateUpdates(SkSpan<GrSurfaceProxy * > proxies,SkSurface::BackendSurfaceAccess access,const GrBackendSurfaceMutableState * newState)1667 void GrD3DGpu::prepareSurfacesForBackendAccessAndStateUpdates(
1668         SkSpan<GrSurfaceProxy*> proxies,
1669         SkSurface::BackendSurfaceAccess access,
1670         const GrBackendSurfaceMutableState* newState) {
1671     // prepare proxies by transitioning to PRESENT renderState
1672     if (!proxies.empty() && access == SkSurface::BackendSurfaceAccess::kPresent) {
1673         GrD3DTextureResource* resource;
1674         for (GrSurfaceProxy* proxy : proxies) {
1675             SkASSERT(proxy->isInstantiated());
1676             if (GrTexture* tex = proxy->peekTexture()) {
1677                 resource = static_cast<GrD3DTexture*>(tex);
1678             } else {
1679                 GrRenderTarget* rt = proxy->peekRenderTarget();
1680                 SkASSERT(rt);
1681                 resource = static_cast<GrD3DRenderTarget*>(rt);
1682             }
1683             resource->prepareForPresent(this);
1684         }
1685     }
1686 }
1687 
takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer)1688 void GrD3DGpu::takeOwnershipOfBuffer(sk_sp<GrGpuBuffer> buffer) {
1689     fCurrentDirectCommandList->addGrBuffer(std::move(buffer));
1690 }
1691 
onSubmitToGpu(bool syncCpu)1692 bool GrD3DGpu::onSubmitToGpu(bool syncCpu) {
1693     if (syncCpu) {
1694         return this->submitDirectCommandList(SyncQueue::kForce);
1695     } else {
1696         return this->submitDirectCommandList(SyncQueue::kSkip);
1697     }
1698 }
1699 
makeSemaphore(bool)1700 std::unique_ptr<GrSemaphore> SK_WARN_UNUSED_RESULT GrD3DGpu::makeSemaphore(bool) {
1701     return GrD3DSemaphore::Make(this);
1702 }
wrapBackendSemaphore(const GrBackendSemaphore & semaphore,GrSemaphoreWrapType,GrWrapOwnership)1703 std::unique_ptr<GrSemaphore> GrD3DGpu::wrapBackendSemaphore(const GrBackendSemaphore& semaphore,
1704                                                             GrSemaphoreWrapType /* wrapType */,
1705                                                             GrWrapOwnership /* ownership */) {
1706     SkASSERT(this->caps()->semaphoreSupport());
1707     GrD3DFenceInfo fenceInfo;
1708     if (!semaphore.getD3DFenceInfo(&fenceInfo)) {
1709         return nullptr;
1710     }
1711     return GrD3DSemaphore::MakeWrapped(fenceInfo);
1712 }
1713 
insertSemaphore(GrSemaphore * semaphore)1714 void GrD3DGpu::insertSemaphore(GrSemaphore* semaphore) {
1715     SkASSERT(semaphore);
1716     GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore);
1717     // TODO: Do we need to track the lifetime of this? How do we know it's done?
1718     fQueue->Signal(d3dSem->fence(), d3dSem->value());
1719 }
1720 
waitSemaphore(GrSemaphore * semaphore)1721 void GrD3DGpu::waitSemaphore(GrSemaphore* semaphore) {
1722     SkASSERT(semaphore);
1723     GrD3DSemaphore* d3dSem = static_cast<GrD3DSemaphore*>(semaphore);
1724     // TODO: Do we need to track the lifetime of this?
1725     fQueue->Wait(d3dSem->fence(), d3dSem->value());
1726 }
1727 
insertFence()1728 GrFence SK_WARN_UNUSED_RESULT GrD3DGpu::insertFence() {
1729     GR_D3D_CALL_ERRCHECK(fQueue->Signal(fFence.get(), ++fCurrentFenceValue));
1730     return fCurrentFenceValue;
1731 }
1732 
waitFence(GrFence fence)1733 bool GrD3DGpu::waitFence(GrFence fence) {
1734     return (fFence->GetCompletedValue() >= fence);
1735 }
1736 
finishOutstandingGpuWork()1737 void GrD3DGpu::finishOutstandingGpuWork() {
1738     this->waitForQueueCompletion();
1739 }
1740