GrContext.h revision 757914d26b337b04cf270875bce28d7d1e2407de
1/* 2 * Copyright 2010 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#ifndef GrContext_DEFINED 9#define GrContext_DEFINED 10 11#include "GrCaps.h" 12#include "GrClip.h" 13#include "GrColor.h" 14#include "GrPaint.h" 15#include "GrRenderTarget.h" 16#include "GrTextureProvider.h" 17#include "SkMatrix.h" 18#include "SkPathEffect.h" 19#include "SkTypes.h" 20#include "../private/GrAuditTrail.h" 21#include "../private/GrSingleOwner.h" 22 23class GrAtlasGlyphCache; 24struct GrContextOptions; 25class GrContextPriv; 26class GrContextThreadSafeProxy; 27class GrDrawingManager; 28struct GrDrawOpAtlasConfig; 29class GrRenderTargetContext; 30class GrFragmentProcessor; 31class GrGpu; 32class GrIndexBuffer; 33class GrOvalRenderer; 34class GrPath; 35class GrPipelineBuilder; 36class GrResourceEntry; 37class GrResourceCache; 38class GrResourceProvider; 39class GrTextBlobCache; 40class GrTextContext; 41class GrSamplerParams; 42class GrVertexBuffer; 43class GrSwizzle; 44class SkTraceMemoryDump; 45 46class SK_API GrContext : public SkRefCnt { 47public: 48 /** 49 * Creates a GrContext for a backend context. 50 */ 51 static GrContext* Create(GrBackend, GrBackendContext, const GrContextOptions& options); 52 static GrContext* Create(GrBackend, GrBackendContext); 53 54 /** 55 * Only defined in test apps. 56 */ 57 static GrContext* CreateMockContext(); 58 59 virtual ~GrContext(); 60 61 sk_sp<GrContextThreadSafeProxy> threadSafeProxy(); 62 63 /** 64 * The GrContext normally assumes that no outsider is setting state 65 * within the underlying 3D API's context/device/whatever. This call informs 66 * the context that the state was modified and it should resend. Shouldn't 67 * be called frequently for good performance. 68 * The flag bits, state, is dpendent on which backend is used by the 69 * context, either GL or D3D (possible in future). 70 */ 71 void resetContext(uint32_t state = kAll_GrBackendState); 72 73 /** 74 * Callback function to allow classes to cleanup on GrContext destruction. 75 * The 'info' field is filled in with the 'info' passed to addCleanUp. 76 */ 77 typedef void (*PFCleanUpFunc)(const GrContext* context, void* info); 78 79 /** 80 * Add a function to be called from within GrContext's destructor. 81 * This gives classes a chance to free resources held on a per context basis. 82 * The 'info' parameter will be stored and passed to the callback function. 83 */ 84 void addCleanUp(PFCleanUpFunc cleanUp, void* info) { 85 CleanUpData* entry = fCleanUpData.push(); 86 87 entry->fFunc = cleanUp; 88 entry->fInfo = info; 89 } 90 91 /** 92 * Abandons all GPU resources and assumes the underlying backend 3D API context is not longer 93 * usable. Call this if you have lost the associated GPU context, and thus internal texture, 94 * buffer, etc. references/IDs are now invalid. Calling this ensures that the destructors of the 95 * GrContext and any of its created resource objects will not make backend 3D API calls. Content 96 * rendered but not previously flushed may be lost. After this function is called all subsequent 97 * calls on the GrContext will fail or be no-ops. 98 * 99 * The typical use case for this function is that the underlying 3D context was lost and further 100 * API calls may crash. 101 */ 102 void abandonContext(); 103 104 /** 105 * This is similar to abandonContext() however the underlying 3D context is not yet lost and 106 * the GrContext will cleanup all allocated resources before returning. After returning it will 107 * assume that the underlying context may no longer be valid. 108 * 109 * The typical use case for this function is that the client is going to destroy the 3D context 110 * but can't guarantee that GrContext will be destroyed first (perhaps because it may be ref'ed 111 * elsewhere by either the client or Skia objects). 112 */ 113 void releaseResourcesAndAbandonContext(); 114 115 /////////////////////////////////////////////////////////////////////////// 116 // Resource Cache 117 118 /** 119 * Return the current GPU resource cache limits. 120 * 121 * @param maxResources If non-null, returns maximum number of resources that 122 * can be held in the cache. 123 * @param maxResourceBytes If non-null, returns maximum number of bytes of 124 * video memory that can be held in the cache. 125 */ 126 void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const; 127 128 /** 129 * Gets the current GPU resource cache usage. 130 * 131 * @param resourceCount If non-null, returns the number of resources that are held in the 132 * cache. 133 * @param maxResourceBytes If non-null, returns the total number of bytes of video memory held 134 * in the cache. 135 */ 136 void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const; 137 138 /** 139 * Specify the GPU resource cache limits. If the current cache exceeds either 140 * of these, it will be purged (LRU) to keep the cache within these limits. 141 * 142 * @param maxResources The maximum number of resources that can be held in 143 * the cache. 144 * @param maxResourceBytes The maximum number of bytes of video memory 145 * that can be held in the cache. 146 */ 147 void setResourceCacheLimits(int maxResources, size_t maxResourceBytes); 148 149 GrTextureProvider* textureProvider() { return fTextureProvider; } 150 const GrTextureProvider* textureProvider() const { return fTextureProvider; } 151 152 /** 153 * Frees GPU created by the context. Can be called to reduce GPU memory 154 * pressure. 155 */ 156 void freeGpuResources(); 157 158 /** 159 * Purge all the unlocked resources from the cache. 160 * This entry point is mainly meant for timing texture uploads 161 * and is not defined in normal builds of Skia. 162 */ 163 void purgeAllUnlockedResources(); 164 165 /** Access the context capabilities */ 166 const GrCaps* caps() const { return fCaps; } 167 168 /** 169 * Returns the recommended sample count for a render target when using this 170 * context. 171 * 172 * @param config the configuration of the render target. 173 * @param dpi the display density in dots per inch. 174 * 175 * @return sample count that should be perform well and have good enough 176 * rendering quality for the display. Alternatively returns 0 if 177 * MSAA is not supported or recommended to be used by default. 178 */ 179 int getRecommendedSampleCount(GrPixelConfig config, SkScalar dpi) const; 180 181 /** 182 * Create both a GrRenderTarget and a matching GrRenderTargetContext to wrap it. 183 * We guarantee that "asTexture" will succeed for renderTargetContexts created 184 * via this entry point. 185 */ 186 sk_sp<GrRenderTargetContext> makeRenderTargetContext( 187 SkBackingFit fit, 188 int width, int height, 189 GrPixelConfig config, 190 sk_sp<SkColorSpace> colorSpace, 191 int sampleCnt = 0, 192 GrSurfaceOrigin origin = kDefault_GrSurfaceOrigin, 193 const SkSurfaceProps* surfaceProps = nullptr, 194 SkBudgeted = SkBudgeted::kYes); 195 196 // Create a new render target context as above but have it backed by a deferred-style 197 // GrRenderTargetProxy rather than one that is backed by an actual GrRenderTarget 198 sk_sp<GrRenderTargetContext> makeDeferredRenderTargetContext( 199 SkBackingFit fit, 200 int width, int height, 201 GrPixelConfig config, 202 sk_sp<SkColorSpace> colorSpace, 203 int sampleCnt = 0, 204 GrSurfaceOrigin origin = kDefault_GrSurfaceOrigin, 205 const SkSurfaceProps* surfaceProps = nullptr, 206 SkBudgeted = SkBudgeted::kYes); 207 /* 208 * This method will attempt to create a renderTargetContext that has, at least, the number of 209 * channels and precision per channel as requested in 'config' (e.g., A8 and 888 can be 210 * converted to 8888). It may also swizzle the channels (e.g., BGRA -> RGBA). 211 * SRGB-ness will be preserved. 212 */ 213 sk_sp<GrRenderTargetContext> makeRenderTargetContextWithFallback( 214 SkBackingFit fit, 215 int width, int height, 216 GrPixelConfig config, 217 sk_sp<SkColorSpace> colorSpace, 218 int sampleCnt = 0, 219 GrSurfaceOrigin origin = kDefault_GrSurfaceOrigin, 220 const SkSurfaceProps* surfaceProps = nullptr, 221 SkBudgeted budgeted = SkBudgeted::kYes); 222 223 // Create a new render target context as above but have it backed by a deferred-style 224 // GrRenderTargetProxy rather than one that is backed by an actual GrRenderTarget 225 sk_sp<GrRenderTargetContext> makeDeferredRenderTargetContextWithFallback( 226 SkBackingFit fit, 227 int width, int height, 228 GrPixelConfig config, 229 sk_sp<SkColorSpace> colorSpace, 230 int sampleCnt = 0, 231 GrSurfaceOrigin origin = kDefault_GrSurfaceOrigin, 232 const SkSurfaceProps* surfaceProps = nullptr, 233 SkBudgeted budgeted = SkBudgeted::kYes); 234 235 /////////////////////////////////////////////////////////////////////////// 236 // Misc. 237 238 /** 239 * Call to ensure all drawing to the context has been issued to the 240 * underlying 3D API. 241 */ 242 void flush(); 243 244 /** 245 * These flags can be used with the read/write pixels functions below. 246 */ 247 enum PixelOpsFlags { 248 /** The GrContext will not be flushed before the surface read or write. This means that 249 the read or write may occur before previous draws have executed. */ 250 kDontFlush_PixelOpsFlag = 0x1, 251 /** Any surface writes should be flushed to the backend 3D API after the surface operation 252 is complete */ 253 kFlushWrites_PixelOp = 0x2, 254 /** The src for write or dst read is unpremultiplied. This is only respected if both the 255 config src and dst configs are an RGBA/BGRA 8888 format. */ 256 kUnpremul_PixelOpsFlag = 0x4, 257 }; 258 259 /** 260 * Reads a rectangle of pixels from a surface. 261 * @param surface the surface to read from. 262 * @param srcColorSpace color space of the surface 263 * @param left left edge of the rectangle to read (inclusive) 264 * @param top top edge of the rectangle to read (inclusive) 265 * @param width width of rectangle to read in pixels. 266 * @param height height of rectangle to read in pixels. 267 * @param config the pixel config of the destination buffer 268 * @param dstColorSpace color space of the destination buffer 269 * @param buffer memory to read the rectangle into. 270 * @param rowBytes number of bytes bewtween consecutive rows. Zero means rows are tightly 271 * packed. 272 * @param pixelOpsFlags see PixelOpsFlags enum above. 273 * 274 * @return true if the read succeeded, false if not. The read can fail because of an unsupported 275 * pixel configs 276 */ 277 bool readSurfacePixels(GrSurface* surface, SkColorSpace* srcColorSpace, 278 int left, int top, int width, int height, 279 GrPixelConfig config, SkColorSpace* dstColorSpace, void* buffer, 280 size_t rowBytes = 0, 281 uint32_t pixelOpsFlags = 0); 282 283 /** 284 * Writes a rectangle of pixels to a surface. 285 * @param surface the surface to write to. 286 * @param dstColorSpace color space of the surface 287 * @param left left edge of the rectangle to write (inclusive) 288 * @param top top edge of the rectangle to write (inclusive) 289 * @param width width of rectangle to write in pixels. 290 * @param height height of rectangle to write in pixels. 291 * @param config the pixel config of the source buffer 292 * @param srcColorSpace color space of the source buffer 293 * @param buffer memory to read pixels from 294 * @param rowBytes number of bytes between consecutive rows. Zero 295 * means rows are tightly packed. 296 * @param pixelOpsFlags see PixelOpsFlags enum above. 297 * @return true if the write succeeded, false if not. The write can fail because of an 298 * unsupported combination of surface and src configs. 299 */ 300 bool writeSurfacePixels(GrSurface* surface, SkColorSpace* dstColorSpace, 301 int left, int top, int width, int height, 302 GrPixelConfig config, SkColorSpace* srcColorSpace, const void* buffer, 303 size_t rowBytes, 304 uint32_t pixelOpsFlags = 0); 305 306 /** 307 * After this returns any pending writes to the surface will have been issued to the backend 3D API. 308 */ 309 void flushSurfaceWrites(GrSurface* surface); 310 311 /** 312 * After this returns any pending reads or writes to the surface will have been issued to the 313 * backend 3D API. 314 */ 315 void flushSurfaceIO(GrSurface* surface); 316 317 /** 318 * Finalizes all pending reads and writes to the surface and also performs an MSAA resolve 319 * if necessary. 320 * 321 * It is not necessary to call this before reading the render target via Skia/GrContext. 322 * GrContext will detect when it must perform a resolve before reading pixels back from the 323 * surface or using it as a texture. 324 */ 325 void prepareSurfaceForExternalIO(GrSurface*); 326 327 /** 328 * An ID associated with this context, guaranteed to be unique. 329 */ 330 uint32_t uniqueID() { return fUniqueID; } 331 332 /////////////////////////////////////////////////////////////////////////// 333 // Functions intended for internal use only. 334 GrGpu* getGpu() { return fGpu; } 335 const GrGpu* getGpu() const { return fGpu; } 336 GrAtlasGlyphCache* getAtlasGlyphCache() { return fAtlasGlyphCache; } 337 GrTextBlobCache* getTextBlobCache() { return fTextBlobCache.get(); } 338 bool abandoned() const; 339 GrResourceProvider* resourceProvider() { return fResourceProvider; } 340 const GrResourceProvider* resourceProvider() const { return fResourceProvider; } 341 GrResourceCache* getResourceCache() { return fResourceCache; } 342 343 /** Reset GPU stats */ 344 void resetGpuStats() const ; 345 346 /** Prints cache stats to the string if GR_CACHE_STATS == 1. */ 347 void dumpCacheStats(SkString*) const; 348 void dumpCacheStatsKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) const; 349 void printCacheStats() const; 350 351 /** Prints GPU stats to the string if GR_GPU_STATS == 1. */ 352 void dumpGpuStats(SkString*) const; 353 void dumpGpuStatsKeyValuePairs(SkTArray<SkString>* keys, SkTArray<double>* values) const; 354 void printGpuStats() const; 355 356 /** Specify the TextBlob cache limit. If the current cache exceeds this limit it will purge. 357 this is for testing only */ 358 void setTextBlobCacheLimit_ForTesting(size_t bytes); 359 360 /** Specify the sizes of the GrAtlasTextContext atlases. The configs pointer below should be 361 to an array of 3 entries */ 362 void setTextContextAtlasSizes_ForTesting(const GrDrawOpAtlasConfig* configs); 363 364 /** Enumerates all cached GPU resources and dumps their memory to traceMemoryDump. */ 365 void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const; 366 367 /** Get pointer to atlas texture for given mask format. Note that this wraps an 368 actively mutating texture in an SkImage. This could yield unexpected results 369 if it gets cached or used more generally. */ 370 sk_sp<SkImage> getFontAtlasImage_ForTesting(GrMaskFormat format); 371 372 GrAuditTrail* getAuditTrail() { return &fAuditTrail; } 373 374 /** This is only useful for debug purposes */ 375 SkDEBUGCODE(GrSingleOwner* debugSingleOwner() const { return &fSingleOwner; } ) 376 377 // Provides access to functions that aren't part of the public API. 378 GrContextPriv contextPriv(); 379 const GrContextPriv contextPriv() const; 380 381private: 382 GrGpu* fGpu; 383 const GrCaps* fCaps; 384 GrResourceCache* fResourceCache; 385 // this union exists because the inheritance of GrTextureProvider->GrResourceProvider 386 // is in a private header. 387 union { 388 GrResourceProvider* fResourceProvider; 389 GrTextureProvider* fTextureProvider; 390 }; 391 392 sk_sp<GrContextThreadSafeProxy> fThreadSafeProxy; 393 394 GrAtlasGlyphCache* fAtlasGlyphCache; 395 std::unique_ptr<GrTextBlobCache> fTextBlobCache; 396 397 bool fDidTestPMConversions; 398 int fPMToUPMConversion; 399 int fUPMToPMConversion; 400 401 // In debug builds we guard against improper thread handling 402 // This guard is passed to the GrDrawingManager and, from there to all the 403 // GrRenderTargetContexts. It is also passed to the GrTextureProvider and SkGpuDevice. 404 mutable GrSingleOwner fSingleOwner; 405 406 struct CleanUpData { 407 PFCleanUpFunc fFunc; 408 void* fInfo; 409 }; 410 411 SkTDArray<CleanUpData> fCleanUpData; 412 413 const uint32_t fUniqueID; 414 415 std::unique_ptr<GrDrawingManager> fDrawingManager; 416 417 GrAuditTrail fAuditTrail; 418 419 // TODO: have the GrClipStackClip use renderTargetContexts and rm this friending 420 friend class GrContextPriv; 421 422 GrContext(); // init must be called after the constructor. 423 bool init(GrBackend, GrBackendContext, const GrContextOptions& options); 424 425 void initMockContext(); 426 void initCommon(const GrContextOptions&); 427 428 /** 429 * These functions create premul <-> unpremul effects if it is possible to generate a pair 430 * of effects that make a readToUPM->writeToPM->readToUPM cycle invariant. Otherwise, they 431 * return NULL. They also can perform a swizzle as part of the draw. 432 */ 433 sk_sp<GrFragmentProcessor> createPMToUPMEffect(GrTexture*, const GrSwizzle&, const SkMatrix&); 434 sk_sp<GrFragmentProcessor> createPMToUPMEffect(sk_sp<GrTextureProxy>, const GrSwizzle&, 435 const SkMatrix&); 436 sk_sp<GrFragmentProcessor> createUPMToPMEffect(sk_sp<GrTextureProxy>, const GrSwizzle&, 437 const SkMatrix&); 438 /** Called before either of the above two functions to determine the appropriate fragment 439 processors for conversions. */ 440 void testPMConversionsIfNecessary(uint32_t flags); 441 /** Returns true if we've already determined that createPMtoUPMEffect and createUPMToPMEffect 442 will fail. In such cases fall back to SW conversion. */ 443 bool didFailPMUPMConversionTest() const; 444 445 /** 446 * A callback similar to the above for use by the TextBlobCache 447 * TODO move textblob draw calls below context so we can use the call above. 448 */ 449 static void TextBlobCacheOverBudgetCB(void* data); 450 451 typedef SkRefCnt INHERITED; 452}; 453 454/** 455 * Can be used to perform actions related to the generating GrContext in a thread safe manner. The 456 * proxy does not access the 3D API (e.g. OpenGL) that backs the generating GrContext. 457 */ 458class GrContextThreadSafeProxy : public SkRefCnt { 459private: 460 GrContextThreadSafeProxy(sk_sp<const GrCaps> caps, uint32_t uniqueID) 461 : fCaps(std::move(caps)) 462 , fContextUniqueID(uniqueID) {} 463 464 sk_sp<const GrCaps> fCaps; 465 uint32_t fContextUniqueID; 466 467 friend class GrContext; 468 friend class SkImage; 469 470 typedef SkRefCnt INHERITED; 471}; 472 473#endif 474