1 /*
2 * Copyright 2015 Google Inc.
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/GrDrawingManager.h"
9
10 #include "include/gpu/GrBackendSemaphore.h"
11 #include "include/gpu/GrTexture.h"
12 #include "include/private/GrRecordingContext.h"
13 #include "include/private/SkDeferredDisplayList.h"
14 #include "src/core/SkTTopoSort.h"
15 #include "src/gpu/GrAuditTrail.h"
16 #include "src/gpu/GrClientMappedBufferManager.h"
17 #include "src/gpu/GrContextPriv.h"
18 #include "src/gpu/GrCopyRenderTask.h"
19 #include "src/gpu/GrGpu.h"
20 #include "src/gpu/GrMemoryPool.h"
21 #include "src/gpu/GrOnFlushResourceProvider.h"
22 #include "src/gpu/GrRecordingContextPriv.h"
23 #include "src/gpu/GrRenderTargetContext.h"
24 #include "src/gpu/GrRenderTargetProxy.h"
25 #include "src/gpu/GrRenderTask.h"
26 #include "src/gpu/GrResourceAllocator.h"
27 #include "src/gpu/GrResourceProvider.h"
28 #include "src/gpu/GrSoftwarePathRenderer.h"
29 #include "src/gpu/GrSurfaceContext.h"
30 #include "src/gpu/GrSurfaceProxyPriv.h"
31 #include "src/gpu/GrTexturePriv.h"
32 #include "src/gpu/GrTextureProxy.h"
33 #include "src/gpu/GrTextureProxyPriv.h"
34 #include "src/gpu/GrTextureResolveRenderTask.h"
35 #include "src/gpu/GrTracing.h"
36 #include "src/gpu/GrTransferFromRenderTask.h"
37 #include "src/gpu/GrWaitRenderTask.h"
38 #include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h"
39 #include "src/gpu/text/GrTextContext.h"
40 #include "src/image/SkSurface_Gpu.h"
41
RenderTaskDAG(bool sortRenderTasks)42 GrDrawingManager::RenderTaskDAG::RenderTaskDAG(bool sortRenderTasks)
43 : fSortRenderTasks(sortRenderTasks) {}
44
~RenderTaskDAG()45 GrDrawingManager::RenderTaskDAG::~RenderTaskDAG() {}
46
gatherIDs(SkSTArray<8,uint32_t,true> * idArray) const47 void GrDrawingManager::RenderTaskDAG::gatherIDs(SkSTArray<8, uint32_t, true>* idArray) const {
48 idArray->reset(fRenderTasks.count());
49 for (int i = 0; i < fRenderTasks.count(); ++i) {
50 if (fRenderTasks[i]) {
51 (*idArray)[i] = fRenderTasks[i]->uniqueID();
52 }
53 }
54 }
55
reset()56 void GrDrawingManager::RenderTaskDAG::reset() {
57 fRenderTasks.reset();
58 }
59
removeRenderTask(int index)60 void GrDrawingManager::RenderTaskDAG::removeRenderTask(int index) {
61 if (!fRenderTasks[index]->unique()) {
62 // TODO: Eventually this should be guaranteed unique: http://skbug.com/7111
63 fRenderTasks[index]->endFlush();
64 }
65
66 fRenderTasks[index] = nullptr;
67 }
68
removeRenderTasks(int startIndex,int stopIndex)69 void GrDrawingManager::RenderTaskDAG::removeRenderTasks(int startIndex, int stopIndex) {
70 for (int i = startIndex; i < stopIndex; ++i) {
71 if (!fRenderTasks[i]) {
72 continue;
73 }
74 this->removeRenderTask(i);
75 }
76 }
77
isUsed(GrSurfaceProxy * proxy) const78 bool GrDrawingManager::RenderTaskDAG::isUsed(GrSurfaceProxy* proxy) const {
79 for (int i = 0; i < fRenderTasks.count(); ++i) {
80 if (fRenderTasks[i] && fRenderTasks[i]->isUsed(proxy)) {
81 return true;
82 }
83 }
84
85 return false;
86 }
87
add(sk_sp<GrRenderTask> renderTask)88 GrRenderTask* GrDrawingManager::RenderTaskDAG::add(sk_sp<GrRenderTask> renderTask) {
89 if (renderTask) {
90 return fRenderTasks.emplace_back(std::move(renderTask)).get();
91 }
92 return nullptr;
93 }
94
addBeforeLast(sk_sp<GrRenderTask> renderTask)95 GrRenderTask* GrDrawingManager::RenderTaskDAG::addBeforeLast(sk_sp<GrRenderTask> renderTask) {
96 SkASSERT(!fRenderTasks.empty());
97 if (renderTask) {
98 // Release 'fRenderTasks.back()' and grab the raw pointer, in case the SkTArray grows
99 // and reallocates during emplace_back.
100 fRenderTasks.emplace_back(fRenderTasks.back().release());
101 return (fRenderTasks[fRenderTasks.count() - 2] = std::move(renderTask)).get();
102 }
103 return nullptr;
104 }
105
add(const SkTArray<sk_sp<GrRenderTask>> & renderTasks)106 void GrDrawingManager::RenderTaskDAG::add(const SkTArray<sk_sp<GrRenderTask>>& renderTasks) {
107 fRenderTasks.push_back_n(renderTasks.count(), renderTasks.begin());
108 }
109
swap(SkTArray<sk_sp<GrRenderTask>> * renderTasks)110 void GrDrawingManager::RenderTaskDAG::swap(SkTArray<sk_sp<GrRenderTask>>* renderTasks) {
111 SkASSERT(renderTasks->empty());
112 renderTasks->swap(fRenderTasks);
113 }
114
prepForFlush()115 void GrDrawingManager::RenderTaskDAG::prepForFlush() {
116 if (fSortRenderTasks) {
117 SkDEBUGCODE(bool result =) SkTTopoSort<GrRenderTask, GrRenderTask::TopoSortTraits>(
118 &fRenderTasks);
119 SkASSERT(result);
120 }
121
122 #ifdef SK_DEBUG
123 // This block checks for any unnecessary splits in the opsTasks. If two sequential opsTasks
124 // share the same backing GrSurfaceProxy it means the opsTask was artificially split.
125 if (fRenderTasks.count()) {
126 GrOpsTask* prevOpsTask = fRenderTasks[0]->asOpsTask();
127 for (int i = 1; i < fRenderTasks.count(); ++i) {
128 GrOpsTask* curOpsTask = fRenderTasks[i]->asOpsTask();
129
130 if (prevOpsTask && curOpsTask) {
131 SkASSERT(prevOpsTask->fTargetView != curOpsTask->fTargetView);
132 }
133
134 prevOpsTask = curOpsTask;
135 }
136 }
137 #endif
138 }
139
closeAll(const GrCaps * caps)140 void GrDrawingManager::RenderTaskDAG::closeAll(const GrCaps* caps) {
141 for (int i = 0; i < fRenderTasks.count(); ++i) {
142 if (fRenderTasks[i]) {
143 fRenderTasks[i]->makeClosed(*caps);
144 }
145 }
146 }
147
cleanup(const GrCaps * caps)148 void GrDrawingManager::RenderTaskDAG::cleanup(const GrCaps* caps) {
149 for (int i = 0; i < fRenderTasks.count(); ++i) {
150 if (!fRenderTasks[i]) {
151 continue;
152 }
153
154 // no renderTask should receive a dependency
155 fRenderTasks[i]->makeClosed(*caps);
156
157 // We shouldn't need to do this, but it turns out some clients still hold onto opsTasks
158 // after a cleanup.
159 // MDB TODO: is this still true?
160 if (!fRenderTasks[i]->unique()) {
161 // TODO: Eventually this should be guaranteed unique.
162 // https://bugs.chromium.org/p/skia/issues/detail?id=7111
163 fRenderTasks[i]->endFlush();
164 }
165 }
166
167 fRenderTasks.reset();
168 }
169
170 ///////////////////////////////////////////////////////////////////////////////////////////////////
GrDrawingManager(GrRecordingContext * context,const GrPathRendererChain::Options & optionsForPathRendererChain,const GrTextContext::Options & optionsForTextContext,bool sortRenderTasks,bool reduceOpsTaskSplitting)171 GrDrawingManager::GrDrawingManager(GrRecordingContext* context,
172 const GrPathRendererChain::Options& optionsForPathRendererChain,
173 const GrTextContext::Options& optionsForTextContext,
174 bool sortRenderTasks,
175 bool reduceOpsTaskSplitting)
176 : fContext(context)
177 , fOptionsForPathRendererChain(optionsForPathRendererChain)
178 , fOptionsForTextContext(optionsForTextContext)
179 , fDAG(sortRenderTasks)
180 , fTextContext(nullptr)
181 , fPathRendererChain(nullptr)
182 , fSoftwarePathRenderer(nullptr)
183 , fFlushing(false)
184 , fReduceOpsTaskSplitting(reduceOpsTaskSplitting) {
185 }
186
cleanup()187 void GrDrawingManager::cleanup() {
188 fDAG.cleanup(fContext->priv().caps());
189
190 fPathRendererChain = nullptr;
191 fSoftwarePathRenderer = nullptr;
192
193 fOnFlushCBObjects.reset();
194 }
195
~GrDrawingManager()196 GrDrawingManager::~GrDrawingManager() {
197 this->cleanup();
198 }
199
wasAbandoned() const200 bool GrDrawingManager::wasAbandoned() const {
201 return fContext->priv().abandoned();
202 }
203
freeGpuResources()204 void GrDrawingManager::freeGpuResources() {
205 for (int i = fOnFlushCBObjects.count() - 1; i >= 0; --i) {
206 if (!fOnFlushCBObjects[i]->retainOnFreeGpuResources()) {
207 // it's safe to just do this because we're iterating in reverse
208 fOnFlushCBObjects.removeShuffle(i);
209 }
210 }
211
212 // a path renderer may be holding onto resources
213 fPathRendererChain = nullptr;
214 fSoftwarePathRenderer = nullptr;
215 }
216
217 // MDB TODO: make use of the 'proxy' parameter.
flush(GrSurfaceProxy * proxies[],int numProxies,SkSurface::BackendSurfaceAccess access,const GrFlushInfo & info,const GrPrepareForExternalIORequests & externalRequests)218 GrSemaphoresSubmitted GrDrawingManager::flush(GrSurfaceProxy* proxies[], int numProxies,
219 SkSurface::BackendSurfaceAccess access, const GrFlushInfo& info,
220 const GrPrepareForExternalIORequests& externalRequests) {
221 SkASSERT(numProxies >= 0);
222 SkASSERT(!numProxies || proxies);
223 GR_CREATE_TRACE_MARKER_CONTEXT("GrDrawingManager", "flush", fContext);
224
225 if (fFlushing || this->wasAbandoned()) {
226 if (info.fFinishedProc) {
227 info.fFinishedProc(info.fFinishedContext);
228 }
229 return GrSemaphoresSubmitted::kNo;
230 }
231
232 SkDEBUGCODE(this->validate());
233
234 if (kNone_GrFlushFlags == info.fFlags && !info.fNumSemaphores && !info.fFinishedProc &&
235 !externalRequests.hasRequests()) {
236 bool canSkip = numProxies > 0;
237 for (int i = 0; i < numProxies && canSkip; ++i) {
238 canSkip = !fDAG.isUsed(proxies[i]) && !this->isDDLTarget(proxies[i]);
239 }
240 if (canSkip) {
241 return GrSemaphoresSubmitted::kNo;
242 }
243 }
244
245 auto direct = fContext->priv().asDirectContext();
246 if (!direct) {
247 if (info.fFinishedProc) {
248 info.fFinishedProc(info.fFinishedContext);
249 }
250 return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording
251 }
252 direct->priv().clientMappedBufferManager()->process();
253
254 GrGpu* gpu = direct->priv().getGpu();
255 if (!gpu) {
256 if (info.fFinishedProc) {
257 info.fFinishedProc(info.fFinishedContext);
258 }
259 return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording
260 }
261
262 fFlushing = true;
263
264 auto resourceProvider = direct->priv().resourceProvider();
265 auto resourceCache = direct->priv().getResourceCache();
266
267 // Semi-usually the GrRenderTasks are already closed at this point, but sometimes Ganesh needs
268 // to flush mid-draw. In that case, the SkGpuDevice's opsTasks won't be closed but need to be
269 // flushed anyway. Closing such opsTasks here will mean new ones will be created to replace them
270 // if the SkGpuDevice(s) write to them again.
271 fDAG.closeAll(fContext->priv().caps());
272 fActiveOpsTask = nullptr;
273
274 fDAG.prepForFlush();
275 if (!fCpuBufferCache) {
276 // We cache more buffers when the backend is using client side arrays. Otherwise, we
277 // expect each pool will use a CPU buffer as a staging buffer before uploading to a GPU
278 // buffer object. Each pool only requires one staging buffer at a time.
279 int maxCachedBuffers = fContext->priv().caps()->preferClientSideDynamicBuffers() ? 2 : 6;
280 fCpuBufferCache = GrBufferAllocPool::CpuBufferCache::Make(maxCachedBuffers);
281 }
282
283 GrOpFlushState flushState(gpu, resourceProvider, &fTokenTracker, fCpuBufferCache);
284
285 GrOnFlushResourceProvider onFlushProvider(this);
286 // TODO: AFAICT the only reason fFlushState is on GrDrawingManager rather than on the
287 // stack here is to preserve the flush tokens.
288
289 // Prepare any onFlush op lists (e.g. atlases).
290 if (!fOnFlushCBObjects.empty()) {
291 fDAG.gatherIDs(&fFlushingRenderTaskIDs);
292
293 for (GrOnFlushCallbackObject* onFlushCBObject : fOnFlushCBObjects) {
294 onFlushCBObject->preFlush(&onFlushProvider, fFlushingRenderTaskIDs.begin(),
295 fFlushingRenderTaskIDs.count());
296 }
297 for (const auto& onFlushRenderTask : fOnFlushRenderTasks) {
298 onFlushRenderTask->makeClosed(*fContext->priv().caps());
299 #ifdef SK_DEBUG
300 // OnFlush callbacks are invoked during flush, and are therefore expected to handle
301 // resource allocation & usage on their own. (No deferred or lazy proxies!)
302 onFlushRenderTask->visitTargetAndSrcProxies_debugOnly(
303 [](GrSurfaceProxy* p, GrMipMapped mipMapped) {
304 SkASSERT(!p->asTextureProxy() || !p->asTextureProxy()->texPriv().isDeferred());
305 SkASSERT(!p->isLazy());
306 if (p->requiresManualMSAAResolve()) {
307 // The onFlush callback is responsible for ensuring MSAA gets resolved.
308 SkASSERT(p->asRenderTargetProxy() && !p->asRenderTargetProxy()->isMSAADirty());
309 }
310 if (GrMipMapped::kYes == mipMapped) {
311 // The onFlush callback is responsible for regenerating mips if needed.
312 SkASSERT(p->asTextureProxy() && !p->asTextureProxy()->mipMapsAreDirty());
313 }
314 });
315 #endif
316 onFlushRenderTask->prepare(&flushState);
317 }
318 }
319
320 #if 0
321 // Enable this to print out verbose GrOp information
322 SkDEBUGCODE(SkDebugf("onFlush renderTasks:"));
323 for (const auto& onFlushRenderTask : fOnFlushRenderTasks) {
324 SkDEBUGCODE(onFlushRenderTask->dump();)
325 }
326 SkDEBUGCODE(SkDebugf("Normal renderTasks:"));
327 for (int i = 0; i < fRenderTasks.count(); ++i) {
328 SkDEBUGCODE(fRenderTasks[i]->dump();)
329 }
330 #endif
331
332 int startIndex, stopIndex;
333 bool flushed = false;
334
335 {
336 GrResourceAllocator alloc(resourceProvider SkDEBUGCODE(, fDAG.numRenderTasks()));
337 for (int i = 0; i < fDAG.numRenderTasks(); ++i) {
338 if (fDAG.renderTask(i)) {
339 fDAG.renderTask(i)->gatherProxyIntervals(&alloc);
340 }
341 alloc.markEndOfOpsTask(i);
342 }
343 alloc.determineRecyclability();
344
345 GrResourceAllocator::AssignError error = GrResourceAllocator::AssignError::kNoError;
346 int numRenderTasksExecuted = 0;
347 while (alloc.assign(&startIndex, &stopIndex, &error)) {
348 if (GrResourceAllocator::AssignError::kFailedProxyInstantiation == error) {
349 for (int i = startIndex; i < stopIndex; ++i) {
350 GrRenderTask* renderTask = fDAG.renderTask(i);
351 if (!renderTask) {
352 continue;
353 }
354 if (!renderTask->isInstantiated()) {
355 // No need to call the renderTask's handleInternalAllocationFailure
356 // since we will already skip executing the renderTask since it is not
357 // instantiated.
358 continue;
359 }
360 renderTask->handleInternalAllocationFailure();
361 }
362 }
363
364 if (this->executeRenderTasks(
365 startIndex, stopIndex, &flushState, &numRenderTasksExecuted)) {
366 flushed = true;
367 }
368 }
369 }
370
371 #ifdef SK_DEBUG
372 for (int i = 0; i < fDAG.numRenderTasks(); ++i) {
373 // If there are any remaining opsTaskss at this point, make sure they will not survive the
374 // flush. Otherwise we need to call endFlush() on them.
375 // http://skbug.com/7111
376 SkASSERT(!fDAG.renderTask(i) || fDAG.renderTask(i)->unique());
377 }
378 #endif
379 fDAG.reset();
380 this->clearDDLTargets();
381
382 #ifdef SK_DEBUG
383 // In non-DDL mode this checks that all the flushed ops have been freed from the memory pool.
384 // When we move to partial flushes this assert will no longer be valid.
385 // In DDL mode this check is somewhat superfluous since the memory for most of the ops/opsTasks
386 // will be stored in the DDL's GrOpMemoryPools.
387 GrOpMemoryPool* opMemoryPool = fContext->priv().opMemoryPool();
388 opMemoryPool->isEmpty();
389 #endif
390
391 GrSemaphoresSubmitted result = gpu->finishFlush(proxies, numProxies, access, info,
392 externalRequests);
393
394 // Give the cache a chance to purge resources that become purgeable due to flushing.
395 if (flushed) {
396 resourceCache->purgeAsNeeded();
397 flushed = false;
398 }
399 for (GrOnFlushCallbackObject* onFlushCBObject : fOnFlushCBObjects) {
400 onFlushCBObject->postFlush(fTokenTracker.nextTokenToFlush(), fFlushingRenderTaskIDs.begin(),
401 fFlushingRenderTaskIDs.count());
402 flushed = true;
403 }
404 if (flushed) {
405 resourceCache->purgeAsNeeded();
406 }
407 fFlushingRenderTaskIDs.reset();
408 fFlushing = false;
409
410 return result;
411 }
412
executeRenderTasks(int startIndex,int stopIndex,GrOpFlushState * flushState,int * numRenderTasksExecuted)413 bool GrDrawingManager::executeRenderTasks(int startIndex, int stopIndex, GrOpFlushState* flushState,
414 int* numRenderTasksExecuted) {
415 SkASSERT(startIndex <= stopIndex && stopIndex <= fDAG.numRenderTasks());
416
417 #if GR_FLUSH_TIME_OP_SPEW
418 SkDebugf("Flushing opsTask: %d to %d out of [%d, %d]\n",
419 startIndex, stopIndex, 0, fDAG.numRenderTasks());
420 for (int i = startIndex; i < stopIndex; ++i) {
421 if (fDAG.renderTask(i)) {
422 fDAG.renderTask(i)->dump(true);
423 }
424 }
425 #endif
426
427 bool anyRenderTasksExecuted = false;
428
429 for (int i = startIndex; i < stopIndex; ++i) {
430 GrRenderTask* renderTask = fDAG.renderTask(i);
431 if (!renderTask || !renderTask->isInstantiated()) {
432 continue;
433 }
434
435 SkASSERT(renderTask->deferredProxiesAreInstantiated());
436
437 renderTask->prepare(flushState);
438 }
439
440 // Upload all data to the GPU
441 flushState->preExecuteDraws();
442
443 // For Vulkan, if we have too many oplists to be flushed we end up allocating a lot of resources
444 // for each command buffer associated with the oplists. If this gets too large we can cause the
445 // devices to go OOM. In practice we usually only hit this case in our tests, but to be safe we
446 // put a cap on the number of oplists we will execute before flushing to the GPU to relieve some
447 // memory pressure.
448 static constexpr int kMaxRenderTasksBeforeFlush = 100;
449
450 // Execute the onFlush renderTasks first, if any.
451 for (sk_sp<GrRenderTask>& onFlushRenderTask : fOnFlushRenderTasks) {
452 if (!onFlushRenderTask->execute(flushState)) {
453 SkDebugf("WARNING: onFlushRenderTask failed to execute.\n");
454 }
455 SkASSERT(onFlushRenderTask->unique());
456 onFlushRenderTask = nullptr;
457 (*numRenderTasksExecuted)++;
458 if (*numRenderTasksExecuted >= kMaxRenderTasksBeforeFlush) {
459 flushState->gpu()->finishFlush(nullptr, 0, SkSurface::BackendSurfaceAccess::kNoAccess,
460 GrFlushInfo(), GrPrepareForExternalIORequests());
461 *numRenderTasksExecuted = 0;
462 }
463 }
464 fOnFlushRenderTasks.reset();
465
466 // Execute the normal op lists.
467 for (int i = startIndex; i < stopIndex; ++i) {
468 GrRenderTask* renderTask = fDAG.renderTask(i);
469 if (!renderTask || !renderTask->isInstantiated()) {
470 continue;
471 }
472
473 if (renderTask->execute(flushState)) {
474 anyRenderTasksExecuted = true;
475 }
476 (*numRenderTasksExecuted)++;
477 if (*numRenderTasksExecuted >= kMaxRenderTasksBeforeFlush) {
478 flushState->gpu()->finishFlush(nullptr, 0, SkSurface::BackendSurfaceAccess::kNoAccess,
479 GrFlushInfo(), GrPrepareForExternalIORequests());
480 *numRenderTasksExecuted = 0;
481 }
482 }
483
484 SkASSERT(!flushState->opsRenderPass());
485 SkASSERT(fTokenTracker.nextDrawToken() == fTokenTracker.nextTokenToFlush());
486
487 // We reset the flush state before the RenderTasks so that the last resources to be freed are
488 // those that are written to in the RenderTasks. This helps to make sure the most recently used
489 // resources are the last to be purged by the resource cache.
490 flushState->reset();
491
492 fDAG.removeRenderTasks(startIndex, stopIndex);
493
494 return anyRenderTasksExecuted;
495 }
496
flushSurfaces(GrSurfaceProxy * proxies[],int numProxies,SkSurface::BackendSurfaceAccess access,const GrFlushInfo & info)497 GrSemaphoresSubmitted GrDrawingManager::flushSurfaces(GrSurfaceProxy* proxies[], int numProxies,
498 SkSurface::BackendSurfaceAccess access,
499 const GrFlushInfo& info) {
500 if (this->wasAbandoned()) {
501 return GrSemaphoresSubmitted::kNo;
502 }
503 SkDEBUGCODE(this->validate());
504 SkASSERT(numProxies >= 0);
505 SkASSERT(!numProxies || proxies);
506
507 auto direct = fContext->priv().asDirectContext();
508 if (!direct) {
509 return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording
510 }
511
512 GrGpu* gpu = direct->priv().getGpu();
513 if (!gpu) {
514 return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording
515 }
516
517 // TODO: It is important to upgrade the drawingmanager to just flushing the
518 // portion of the DAG required by 'proxies' in order to restore some of the
519 // semantics of this method.
520 GrSemaphoresSubmitted result = this->flush(proxies, numProxies, access, info,
521 GrPrepareForExternalIORequests());
522 for (int i = 0; i < numProxies; ++i) {
523 GrSurfaceProxy* proxy = proxies[i];
524 if (!proxy->isInstantiated()) {
525 return result;
526 }
527 // In the flushSurfaces case, we need to resolve MSAA immediately after flush. This is
528 // because the client will call through to this method when drawing into a target created by
529 // wrapBackendTextureAsRenderTarget, and will expect the original texture to be fully
530 // resolved upon return.
531 if (proxy->requiresManualMSAAResolve()) {
532 auto* rtProxy = proxy->asRenderTargetProxy();
533 SkASSERT(rtProxy);
534 if (rtProxy->isMSAADirty()) {
535 SkASSERT(rtProxy->peekRenderTarget());
536 gpu->resolveRenderTarget(rtProxy->peekRenderTarget(), rtProxy->msaaDirtyRect(),
537 GrGpu::ForExternalIO::kYes);
538 rtProxy->markMSAAResolved();
539 }
540 }
541 // If, after a flush, any of the proxies of interest have dirty mipmaps, regenerate them in
542 // case their backend textures are being stolen.
543 // (This special case is exercised by the ReimportImageTextureWithMipLevels test.)
544 // FIXME: It may be more ideal to plumb down a "we're going to steal the backends" flag.
545 if (auto* textureProxy = proxy->asTextureProxy()) {
546 if (textureProxy->mipMapsAreDirty()) {
547 SkASSERT(textureProxy->peekTexture());
548 gpu->regenerateMipMapLevels(textureProxy->peekTexture());
549 textureProxy->markMipMapsClean();
550 }
551 }
552 }
553
554 SkDEBUGCODE(this->validate());
555 return result;
556 }
557
addOnFlushCallbackObject(GrOnFlushCallbackObject * onFlushCBObject)558 void GrDrawingManager::addOnFlushCallbackObject(GrOnFlushCallbackObject* onFlushCBObject) {
559 fOnFlushCBObjects.push_back(onFlushCBObject);
560 }
561
562 #if GR_TEST_UTILS
testingOnly_removeOnFlushCallbackObject(GrOnFlushCallbackObject * cb)563 void GrDrawingManager::testingOnly_removeOnFlushCallbackObject(GrOnFlushCallbackObject* cb) {
564 int n = std::find(fOnFlushCBObjects.begin(), fOnFlushCBObjects.end(), cb) -
565 fOnFlushCBObjects.begin();
566 SkASSERT(n < fOnFlushCBObjects.count());
567 fOnFlushCBObjects.removeShuffle(n);
568 }
569 #endif
570
moveRenderTasksToDDL(SkDeferredDisplayList * ddl)571 void GrDrawingManager::moveRenderTasksToDDL(SkDeferredDisplayList* ddl) {
572 SkDEBUGCODE(this->validate());
573
574 // no renderTask should receive a new command after this
575 fDAG.closeAll(fContext->priv().caps());
576 fActiveOpsTask = nullptr;
577
578 fDAG.swap(&ddl->fRenderTasks);
579
580 for (auto renderTask : ddl->fRenderTasks) {
581 renderTask->prePrepare(fContext);
582 }
583
584 ddl->fArenas = std::move(fContext->priv().detachArenas());
585
586 fContext->priv().detachProgramData(&ddl->fProgramData);
587
588 if (fPathRendererChain) {
589 if (auto ccpr = fPathRendererChain->getCoverageCountingPathRenderer()) {
590 ddl->fPendingPaths = ccpr->detachPendingPaths();
591 }
592 }
593
594 SkDEBUGCODE(this->validate());
595 }
596
copyRenderTasksFromDDL(const SkDeferredDisplayList * ddl,GrRenderTargetProxy * newDest)597 void GrDrawingManager::copyRenderTasksFromDDL(const SkDeferredDisplayList* ddl,
598 GrRenderTargetProxy* newDest) {
599 SkDEBUGCODE(this->validate());
600
601 if (fActiveOpsTask) {
602 // This is a temporary fix for the partial-MDB world. In that world we're not
603 // reordering so ops that (in the single opsTask world) would've just glommed onto the
604 // end of the single opsTask but referred to a far earlier RT need to appear in their
605 // own opsTask.
606 fActiveOpsTask->makeClosed(*fContext->priv().caps());
607 fActiveOpsTask = nullptr;
608 }
609
610 this->addDDLTarget(newDest);
611
612 // Here we jam the proxy that backs the current replay SkSurface into the LazyProxyData.
613 // The lazy proxy that references it (in the copied opsTasks) will steal its GrTexture.
614 ddl->fLazyProxyData->fReplayDest = newDest;
615
616 if (ddl->fPendingPaths.size()) {
617 GrCoverageCountingPathRenderer* ccpr = this->getCoverageCountingPathRenderer();
618
619 ccpr->mergePendingPaths(ddl->fPendingPaths);
620 }
621
622 fDAG.add(ddl->fRenderTasks);
623
624 SkDEBUGCODE(this->validate());
625 }
626
627 #ifdef SK_DEBUG
validate() const628 void GrDrawingManager::validate() const {
629 if (fDAG.sortingRenderTasks() && fReduceOpsTaskSplitting) {
630 SkASSERT(!fActiveOpsTask);
631 } else {
632 if (fActiveOpsTask) {
633 SkASSERT(!fDAG.empty());
634 SkASSERT(!fActiveOpsTask->isClosed());
635 SkASSERT(fActiveOpsTask == fDAG.back());
636 }
637
638 for (int i = 0; i < fDAG.numRenderTasks(); ++i) {
639 if (fActiveOpsTask != fDAG.renderTask(i)) {
640 // The resolveTask associated with the activeTask remains open for as long as the
641 // activeTask does.
642 bool isActiveResolveTask =
643 fActiveOpsTask && fActiveOpsTask->fTextureResolveTask == fDAG.renderTask(i);
644 SkASSERT(isActiveResolveTask || fDAG.renderTask(i)->isClosed());
645 }
646 }
647
648 if (!fDAG.empty() && !fDAG.back()->isClosed()) {
649 SkASSERT(fActiveOpsTask == fDAG.back());
650 }
651 }
652 }
653 #endif
654
closeRenderTasksForNewRenderTask(GrSurfaceProxy * target)655 void GrDrawingManager::closeRenderTasksForNewRenderTask(GrSurfaceProxy* target) {
656 if (target && fDAG.sortingRenderTasks() && fReduceOpsTaskSplitting) {
657 // In this case we need to close all the renderTasks that rely on the current contents of
658 // 'target'. That is bc we're going to update the content of the proxy so they need to be
659 // split in case they use both the old and new content. (This is a bit of an overkill: they
660 // really only need to be split if they ever reference proxy's contents again but that is
661 // hard to predict/handle).
662 if (GrRenderTask* lastRenderTask = target->getLastRenderTask()) {
663 lastRenderTask->closeThoseWhoDependOnMe(*fContext->priv().caps());
664 }
665 } else if (fActiveOpsTask) {
666 // This is a temporary fix for the partial-MDB world. In that world we're not
667 // reordering so ops that (in the single opsTask world) would've just glommed onto the
668 // end of the single opsTask but referred to a far earlier RT need to appear in their
669 // own opsTask.
670 fActiveOpsTask->makeClosed(*fContext->priv().caps());
671 fActiveOpsTask = nullptr;
672 }
673 }
674
newOpsTask(GrSurfaceProxyView surfaceView,bool managedOpsTask)675 sk_sp<GrOpsTask> GrDrawingManager::newOpsTask(GrSurfaceProxyView surfaceView,
676 bool managedOpsTask) {
677 SkDEBUGCODE(this->validate());
678 SkASSERT(fContext);
679
680 GrSurfaceProxy* proxy = surfaceView.proxy();
681 this->closeRenderTasksForNewRenderTask(proxy);
682
683 sk_sp<GrOpsTask> opsTask(new GrOpsTask(fContext->priv().arenas(),
684 std::move(surfaceView),
685 fContext->priv().auditTrail()));
686 SkASSERT(proxy->getLastRenderTask() == opsTask.get());
687
688 if (managedOpsTask) {
689 fDAG.add(opsTask);
690
691 if (!fDAG.sortingRenderTasks() || !fReduceOpsTaskSplitting) {
692 fActiveOpsTask = opsTask.get();
693 }
694 }
695
696 SkDEBUGCODE(this->validate());
697 return opsTask;
698 }
699
newTextureResolveRenderTask(const GrCaps & caps)700 GrTextureResolveRenderTask* GrDrawingManager::newTextureResolveRenderTask(const GrCaps& caps) {
701 // Unlike in the "new opsTask" case, we do not want to close the active opsTask, nor (if we are
702 // in sorting and opsTask reduction mode) the render tasks that depend on any proxy's current
703 // state. This is because those opsTasks can still receive new ops and because if they refer to
704 // the mipmapped version of 'proxy', they will then come to depend on the render task being
705 // created here.
706 //
707 // Add the new textureResolveTask before the fActiveOpsTask (if not in
708 // sorting/opsTask-splitting-reduction mode) because it will depend upon this resolve task.
709 // NOTE: Putting it here will also reduce the amount of work required by the topological sort.
710 return static_cast<GrTextureResolveRenderTask*>(fDAG.addBeforeLast(
711 sk_make_sp<GrTextureResolveRenderTask>()));
712 }
713
newWaitRenderTask(sk_sp<GrSurfaceProxy> proxy,std::unique_ptr<std::unique_ptr<GrSemaphore>[]> semaphores,int numSemaphores)714 void GrDrawingManager::newWaitRenderTask(sk_sp<GrSurfaceProxy> proxy,
715 std::unique_ptr<std::unique_ptr<GrSemaphore>[]> semaphores,
716 int numSemaphores) {
717 SkDEBUGCODE(this->validate());
718 SkASSERT(fContext);
719
720 const GrCaps& caps = *fContext->priv().caps();
721
722 sk_sp<GrWaitRenderTask> waitTask = sk_make_sp<GrWaitRenderTask>(GrSurfaceProxyView(proxy),
723 std::move(semaphores),
724 numSemaphores);
725 if (fReduceOpsTaskSplitting) {
726 GrRenderTask* lastTask = proxy->getLastRenderTask();
727 if (lastTask && !lastTask->isClosed()) {
728 // We directly make the currently open renderTask depend on waitTask instead of using
729 // the proxy version of addDependency. The waitTask will never need to trigger any
730 // resolves or mip map generation which is the main advantage of going through the proxy
731 // version. Additionally we would've had to temporarily set the wait task as the
732 // lastRenderTask on the proxy, add the dependency, and then reset the lastRenderTask to
733 // lastTask. Additionally we add all dependencies of lastTask to waitTask so that the
734 // waitTask doesn't get reordered before them and unnecessarily block those tasks.
735 // Note: Any previous Ops already in lastTask will get blocked by the wait semaphore
736 // even though they don't need to be for correctness.
737
738 // Make sure we add the dependencies of lastTask to waitTask first or else we'll get a
739 // circular self dependency of waitTask on waitTask.
740 waitTask->addDependenciesFromOtherTask(lastTask);
741 lastTask->addDependency(waitTask.get());
742 } else {
743 // If there is a last task we set the waitTask to depend on it so that it doesn't get
744 // reordered in front of the lastTask causing the lastTask to be blocked by the
745 // semaphore. Again we directly just go through adding the dependency to the task and
746 // not the proxy since we don't need to worry about resolving anything.
747 if (lastTask) {
748 waitTask->addDependency(lastTask);
749 }
750 proxy->setLastRenderTask(waitTask.get());
751 }
752 fDAG.add(waitTask);
753 } else {
754 if (fActiveOpsTask && (fActiveOpsTask->fTargetView.proxy() == proxy.get())) {
755 SkASSERT(proxy->getLastRenderTask() == fActiveOpsTask);
756 fDAG.addBeforeLast(waitTask);
757 // In this case we keep the current renderTask open but just insert the new waitTask
758 // before it in the list. The waitTask will never need to trigger any resolves or mip
759 // map generation which is the main advantage of going through the proxy version.
760 // Additionally we would've had to temporarily set the wait task as the lastRenderTask
761 // on the proxy, add the dependency, and then reset the lastRenderTask to
762 // fActiveOpsTask. Additionally we make the waitTask depend on all of fActiveOpsTask
763 // dependencies so that we don't unnecessarily reorder the waitTask before them.
764 // Note: Any previous Ops already in fActiveOpsTask will get blocked by the wait
765 // semaphore even though they don't need to be for correctness.
766
767 // Make sure we add the dependencies of fActiveOpsTask to waitTask first or else we'll
768 // get a circular self dependency of waitTask on waitTask.
769 waitTask->addDependenciesFromOtherTask(fActiveOpsTask);
770 fActiveOpsTask->addDependency(waitTask.get());
771 } else {
772 // In this case we just close the previous RenderTask and start and append the waitTask
773 // to the DAG. Since it is the last task now we call setLastRenderTask on the proxy. If
774 // there is a lastTask on the proxy we make waitTask depend on that task. This
775 // dependency isn't strictly needed but it does keep the DAG from reordering the
776 // waitTask earlier and blocking more tasks.
777 if (GrRenderTask* lastTask = proxy->getLastRenderTask()) {
778 waitTask->addDependency(lastTask);
779 }
780 proxy->setLastRenderTask(waitTask.get());
781 this->closeRenderTasksForNewRenderTask(proxy.get());
782 fDAG.add(waitTask);
783 }
784 }
785 waitTask->makeClosed(caps);
786
787 SkDEBUGCODE(this->validate());
788 }
789
newTransferFromRenderTask(sk_sp<GrSurfaceProxy> srcProxy,const SkIRect & srcRect,GrColorType surfaceColorType,GrColorType dstColorType,sk_sp<GrGpuBuffer> dstBuffer,size_t dstOffset)790 void GrDrawingManager::newTransferFromRenderTask(sk_sp<GrSurfaceProxy> srcProxy,
791 const SkIRect& srcRect,
792 GrColorType surfaceColorType,
793 GrColorType dstColorType,
794 sk_sp<GrGpuBuffer> dstBuffer,
795 size_t dstOffset) {
796 SkDEBUGCODE(this->validate());
797 SkASSERT(fContext);
798 // This copies from srcProxy to dstBuffer so it doesn't have a real target.
799 this->closeRenderTasksForNewRenderTask(nullptr);
800
801 GrRenderTask* task = fDAG.add(sk_make_sp<GrTransferFromRenderTask>(
802 srcProxy, srcRect, surfaceColorType, dstColorType, std::move(dstBuffer), dstOffset));
803
804 const GrCaps& caps = *fContext->priv().caps();
805
806 // We always say GrMipMapped::kNo here since we are always just copying from the base layer. We
807 // don't need to make sure the whole mip map chain is valid.
808 task->addDependency(srcProxy.get(), GrMipMapped::kNo, GrTextureResolveManager(this), caps);
809 task->makeClosed(caps);
810
811 // We have closed the previous active oplist but since a new oplist isn't being added there
812 // shouldn't be an active one.
813 SkASSERT(!fActiveOpsTask);
814 SkDEBUGCODE(this->validate());
815 }
816
newCopyRenderTask(GrSurfaceProxyView srcView,const SkIRect & srcRect,GrSurfaceProxyView dstView,const SkIPoint & dstPoint)817 bool GrDrawingManager::newCopyRenderTask(GrSurfaceProxyView srcView,
818 const SkIRect& srcRect,
819 GrSurfaceProxyView dstView,
820 const SkIPoint& dstPoint) {
821 SkDEBUGCODE(this->validate());
822 SkASSERT(fContext);
823
824 this->closeRenderTasksForNewRenderTask(dstView.proxy());
825 const GrCaps& caps = *fContext->priv().caps();
826
827 GrSurfaceProxy* srcProxy = srcView.proxy();
828
829 GrRenderTask* task =
830 fDAG.add(GrCopyRenderTask::Make(std::move(srcView), srcRect, std::move(dstView),
831 dstPoint, &caps));
832 if (!task) {
833 return false;
834 }
835
836 // We always say GrMipMapped::kNo here since we are always just copying from the base layer to
837 // another base layer. We don't need to make sure the whole mip map chain is valid.
838 task->addDependency(srcProxy, GrMipMapped::kNo, GrTextureResolveManager(this), caps);
839 task->makeClosed(caps);
840
841 // We have closed the previous active oplist but since a new oplist isn't being added there
842 // shouldn't be an active one.
843 SkASSERT(!fActiveOpsTask);
844 SkDEBUGCODE(this->validate());
845 return true;
846 }
847
getTextContext()848 GrTextContext* GrDrawingManager::getTextContext() {
849 if (!fTextContext) {
850 fTextContext = GrTextContext::Make(fOptionsForTextContext);
851 }
852
853 return fTextContext.get();
854 }
855
856 /*
857 * This method finds a path renderer that can draw the specified path on
858 * the provided target.
859 * Due to its expense, the software path renderer has split out so it can
860 * can be individually allowed/disallowed via the "allowSW" boolean.
861 */
getPathRenderer(const GrPathRenderer::CanDrawPathArgs & args,bool allowSW,GrPathRendererChain::DrawType drawType,GrPathRenderer::StencilSupport * stencilSupport)862 GrPathRenderer* GrDrawingManager::getPathRenderer(const GrPathRenderer::CanDrawPathArgs& args,
863 bool allowSW,
864 GrPathRendererChain::DrawType drawType,
865 GrPathRenderer::StencilSupport* stencilSupport) {
866
867 if (!fPathRendererChain) {
868 fPathRendererChain.reset(new GrPathRendererChain(fContext, fOptionsForPathRendererChain));
869 }
870
871 GrPathRenderer* pr = fPathRendererChain->getPathRenderer(args, drawType, stencilSupport);
872 if (!pr && allowSW) {
873 auto swPR = this->getSoftwarePathRenderer();
874 if (GrPathRenderer::CanDrawPath::kNo != swPR->canDrawPath(args)) {
875 pr = swPR;
876 }
877 }
878
879 return pr;
880 }
881
getSoftwarePathRenderer()882 GrPathRenderer* GrDrawingManager::getSoftwarePathRenderer() {
883 if (!fSoftwarePathRenderer) {
884 fSoftwarePathRenderer.reset(
885 new GrSoftwarePathRenderer(fContext->priv().proxyProvider(),
886 fOptionsForPathRendererChain.fAllowPathMaskCaching));
887 }
888 return fSoftwarePathRenderer.get();
889 }
890
getCoverageCountingPathRenderer()891 GrCoverageCountingPathRenderer* GrDrawingManager::getCoverageCountingPathRenderer() {
892 if (!fPathRendererChain) {
893 fPathRendererChain.reset(new GrPathRendererChain(fContext, fOptionsForPathRendererChain));
894 }
895 return fPathRendererChain->getCoverageCountingPathRenderer();
896 }
897
flushIfNecessary()898 void GrDrawingManager::flushIfNecessary() {
899 auto direct = fContext->priv().asDirectContext();
900 if (!direct) {
901 return;
902 }
903
904 auto resourceCache = direct->priv().getResourceCache();
905 if (resourceCache && resourceCache->requestsFlush()) {
906 this->flush(nullptr, 0, SkSurface::BackendSurfaceAccess::kNoAccess, GrFlushInfo(),
907 GrPrepareForExternalIORequests());
908 resourceCache->purgeAsNeeded();
909 }
910 }
911
912