GrContext.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. #ifndef GrContext_DEFINED
  8. #define GrContext_DEFINED
  9. #include "SkMatrix.h"
  10. #include "SkPathEffect.h"
  11. #include "SkTypes.h"
  12. #include "../private/GrAuditTrail.h"
  13. #include "../private/GrSingleOwner.h"
  14. #include "../private/GrSkSLFPFactoryCache.h"
  15. #include "GrContextOptions.h"
  16. // We shouldn't need this but currently Android is relying on this being include transitively.
  17. #include "SkUnPreMultiply.h"
  18. class GrAtlasManager;
  19. class GrBackendFormat;
  20. class GrBackendSemaphore;
  21. class GrCaps;
  22. class GrContextPriv;
  23. class GrContextThreadSafeProxy;
  24. class GrContextThreadSafeProxyPriv;
  25. class GrDrawingManager;
  26. class GrFragmentProcessor;
  27. struct GrGLInterface;
  28. class GrGlyphCache;
  29. class GrGpu;
  30. struct GrMockOptions;
  31. class GrOpMemoryPool;
  32. class GrPath;
  33. class GrProxyProvider;
  34. class GrRenderTargetContext;
  35. class GrResourceCache;
  36. class GrResourceProvider;
  37. class GrSamplerState;
  38. class GrSurfaceProxy;
  39. class GrSwizzle;
  40. class GrTextBlobCache;
  41. class GrTextContext;
  42. class GrTextureProxy;
  43. struct GrVkBackendContext;
  44. class SkImage;
  45. class SkSurfaceCharacterization;
  46. class SkSurfaceProps;
  47. class SkTaskGroup;
  48. class SkTraceMemoryDump;
  49. class SK_API GrContext : public SkRefCnt {
  50. public:
  51. /**
  52. * Creates a GrContext for a backend context. If no GrGLInterface is provided then the result of
  53. * GrGLMakeNativeInterface() is used if it succeeds.
  54. */
  55. static sk_sp<GrContext> MakeGL(sk_sp<const GrGLInterface>, const GrContextOptions&);
  56. static sk_sp<GrContext> MakeGL(sk_sp<const GrGLInterface>);
  57. static sk_sp<GrContext> MakeGL(const GrContextOptions&);
  58. static sk_sp<GrContext> MakeGL();
  59. static sk_sp<GrContext> MakeVulkan(const GrVkBackendContext&, const GrContextOptions&);
  60. static sk_sp<GrContext> MakeVulkan(const GrVkBackendContext&);
  61. #ifdef SK_METAL
  62. /**
  63. * Makes a GrContext which uses Metal as the backend. The device parameter is an MTLDevice
  64. * and queue is an MTLCommandQueue which should be used by the backend. These objects must
  65. * have a ref on them which can be transferred to Ganesh which will release the ref when the
  66. * GrContext is destroyed.
  67. */
  68. static sk_sp<GrContext> MakeMetal(void* device, void* queue, const GrContextOptions& options);
  69. static sk_sp<GrContext> MakeMetal(void* device, void* queue);
  70. #endif
  71. static sk_sp<GrContext> MakeMock(const GrMockOptions*, const GrContextOptions&);
  72. static sk_sp<GrContext> MakeMock(const GrMockOptions*);
  73. virtual ~GrContext();
  74. sk_sp<GrContextThreadSafeProxy> threadSafeProxy();
  75. /**
  76. * The GrContext normally assumes that no outsider is setting state
  77. * within the underlying 3D API's context/device/whatever. This call informs
  78. * the context that the state was modified and it should resend. Shouldn't
  79. * be called frequently for good performance.
  80. * The flag bits, state, is dpendent on which backend is used by the
  81. * context, either GL or D3D (possible in future).
  82. */
  83. void resetContext(uint32_t state = kAll_GrBackendState);
  84. /**
  85. * Abandons all GPU resources and assumes the underlying backend 3D API context is no longer
  86. * usable. Call this if you have lost the associated GPU context, and thus internal texture,
  87. * buffer, etc. references/IDs are now invalid. Calling this ensures that the destructors of the
  88. * GrContext and any of its created resource objects will not make backend 3D API calls. Content
  89. * rendered but not previously flushed may be lost. After this function is called all subsequent
  90. * calls on the GrContext will fail or be no-ops.
  91. *
  92. * The typical use case for this function is that the underlying 3D context was lost and further
  93. * API calls may crash.
  94. */
  95. virtual void abandonContext();
  96. /**
  97. * Returns true if the context was abandoned.
  98. */
  99. bool abandoned() const;
  100. /**
  101. * This is similar to abandonContext() however the underlying 3D context is not yet lost and
  102. * the GrContext will cleanup all allocated resources before returning. After returning it will
  103. * assume that the underlying context may no longer be valid.
  104. *
  105. * The typical use case for this function is that the client is going to destroy the 3D context
  106. * but can't guarantee that GrContext will be destroyed first (perhaps because it may be ref'ed
  107. * elsewhere by either the client or Skia objects).
  108. */
  109. virtual void releaseResourcesAndAbandonContext();
  110. ///////////////////////////////////////////////////////////////////////////
  111. // Resource Cache
  112. /**
  113. * Return the current GPU resource cache limits.
  114. *
  115. * @param maxResources If non-null, returns maximum number of resources that
  116. * can be held in the cache.
  117. * @param maxResourceBytes If non-null, returns maximum number of bytes of
  118. * video memory that can be held in the cache.
  119. */
  120. void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const;
  121. /**
  122. * Gets the current GPU resource cache usage.
  123. *
  124. * @param resourceCount If non-null, returns the number of resources that are held in the
  125. * cache.
  126. * @param maxResourceBytes If non-null, returns the total number of bytes of video memory held
  127. * in the cache.
  128. */
  129. void getResourceCacheUsage(int* resourceCount, size_t* resourceBytes) const;
  130. /**
  131. * Gets the number of bytes in the cache consumed by purgeable (e.g. unlocked) resources.
  132. */
  133. size_t getResourceCachePurgeableBytes() const;
  134. /**
  135. * Specify the GPU resource cache limits. If the current cache exceeds either
  136. * of these, it will be purged (LRU) to keep the cache within these limits.
  137. *
  138. * @param maxResources The maximum number of resources that can be held in
  139. * the cache.
  140. * @param maxResourceBytes The maximum number of bytes of video memory
  141. * that can be held in the cache.
  142. */
  143. void setResourceCacheLimits(int maxResources, size_t maxResourceBytes);
  144. /**
  145. * Frees GPU created by the context. Can be called to reduce GPU memory
  146. * pressure.
  147. */
  148. virtual void freeGpuResources();
  149. /**
  150. * Purge GPU resources that haven't been used in the past 'msNotUsed' milliseconds or are
  151. * otherwise marked for deletion, regardless of whether the context is under budget.
  152. */
  153. void performDeferredCleanup(std::chrono::milliseconds msNotUsed);
  154. // Temporary compatibility API for Android.
  155. void purgeResourcesNotUsedInMs(std::chrono::milliseconds msNotUsed) {
  156. this->performDeferredCleanup(msNotUsed);
  157. }
  158. /**
  159. * Purge unlocked resources from the cache until the the provided byte count has been reached
  160. * or we have purged all unlocked resources. The default policy is to purge in LRU order, but
  161. * can be overridden to prefer purging scratch resources (in LRU order) prior to purging other
  162. * resource types.
  163. *
  164. * @param maxBytesToPurge the desired number of bytes to be purged.
  165. * @param preferScratchResources If true scratch resources will be purged prior to other
  166. * resource types.
  167. */
  168. void purgeUnlockedResources(size_t bytesToPurge, bool preferScratchResources);
  169. /**
  170. * This entry point is intended for instances where an app has been backgrounded or
  171. * suspended.
  172. * If 'scratchResourcesOnly' is true all unlocked scratch resources will be purged but the
  173. * unlocked resources with persistent data will remain. If 'scratchResourcesOnly' is false
  174. * then all unlocked resources will be purged.
  175. * In either case, after the unlocked resources are purged a separate pass will be made to
  176. * ensure that resource usage is under budget (i.e., even if 'scratchResourcesOnly' is true
  177. * some resources with persistent data may be purged to be under budget).
  178. *
  179. * @param scratchResourcesOnly If true only unlocked scratch resources will be purged prior
  180. * enforcing the budget requirements.
  181. */
  182. void purgeUnlockedResources(bool scratchResourcesOnly);
  183. /**
  184. * Gets the maximum supported texture size.
  185. */
  186. int maxTextureSize() const;
  187. /**
  188. * Gets the maximum supported render target size.
  189. */
  190. int maxRenderTargetSize() const;
  191. /**
  192. * Can a SkImage be created with the given color type.
  193. */
  194. bool colorTypeSupportedAsImage(SkColorType) const;
  195. /**
  196. * Can a SkSurface be created with the given color type. To check whether MSAA is supported
  197. * use maxSurfaceSampleCountForColorType().
  198. */
  199. bool colorTypeSupportedAsSurface(SkColorType colorType) const {
  200. return this->maxSurfaceSampleCountForColorType(colorType) > 0;
  201. }
  202. /**
  203. * Gets the maximum supported sample count for a color type. 1 is returned if only non-MSAA
  204. * rendering is supported for the color type. 0 is returned if rendering to this color type
  205. * is not supported at all.
  206. */
  207. int maxSurfaceSampleCountForColorType(SkColorType) const;
  208. ///////////////////////////////////////////////////////////////////////////
  209. // Misc.
  210. /**
  211. * Call to ensure all drawing to the context has been issued to the underlying 3D API.
  212. */
  213. void flush();
  214. /**
  215. * Call to ensure all drawing to the context has been issued to the underlying 3D API. After
  216. * issuing all commands, numSemaphore semaphores will be signaled by the gpu. The client passes
  217. * in an array of numSemaphores GrBackendSemaphores. In general these GrBackendSemaphore's can
  218. * be either initialized or not. If they are initialized, the backend uses the passed in
  219. * semaphore. If it is not initialized, a new semaphore is created and the GrBackendSemaphore
  220. * object is initialized with that semaphore.
  221. *
  222. * The client will own and be responsible for deleting the underlying semaphores that are stored
  223. * and returned in initialized GrBackendSemaphore objects. The GrBackendSemaphore objects
  224. * themselves can be deleted as soon as this function returns.
  225. *
  226. * If the backend API is OpenGL only uninitialized GrBackendSemaphores are supported.
  227. * If the backend API is Vulkan either initialized or unitialized semaphores are supported.
  228. * If unitialized, the semaphores which are created will be valid for use only with the VkDevice
  229. * with which they were created.
  230. *
  231. * If this call returns GrSemaphoresSubmited::kNo, the GPU backend will not have created or
  232. * added any semaphores to signal on the GPU. Thus the client should not have the GPU wait on
  233. * any of the semaphores. However, any pending commands to the context will still be flushed.
  234. */
  235. GrSemaphoresSubmitted flushAndSignalSemaphores(int numSemaphores,
  236. GrBackendSemaphore signalSemaphores[]);
  237. /**
  238. * An ID associated with this context, guaranteed to be unique.
  239. */
  240. uint32_t uniqueID() { return fUniqueID; }
  241. // Provides access to functions that aren't part of the public API.
  242. GrContextPriv contextPriv();
  243. const GrContextPriv contextPriv() const;
  244. /** Enumerates all cached GPU resources and dumps their memory to traceMemoryDump. */
  245. // Chrome is using this!
  246. void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const;
  247. bool supportsDistanceFieldText() const;
  248. protected:
  249. GrContext(GrBackendApi, int32_t id = SK_InvalidGenID);
  250. bool initCommon(const GrContextOptions&);
  251. virtual bool init(const GrContextOptions&) = 0; // must be called after the ctor!
  252. virtual GrAtlasManager* onGetAtlasManager() = 0;
  253. const GrBackendApi fBackend;
  254. sk_sp<const GrCaps> fCaps;
  255. sk_sp<GrContextThreadSafeProxy> fThreadSafeProxy;
  256. sk_sp<GrSkSLFPFactoryCache> fFPFactoryCache;
  257. private:
  258. sk_sp<GrGpu> fGpu;
  259. GrResourceCache* fResourceCache;
  260. GrResourceProvider* fResourceProvider;
  261. GrProxyProvider* fProxyProvider;
  262. // All the GrOp-derived classes use this pool.
  263. sk_sp<GrOpMemoryPool> fOpMemoryPool;
  264. GrGlyphCache* fGlyphCache;
  265. std::unique_ptr<GrTextBlobCache> fTextBlobCache;
  266. bool fDisableGpuYUVConversion;
  267. bool fSharpenMipmappedTextures;
  268. bool fDidTestPMConversions;
  269. // true if the PM/UPM conversion succeeded; false otherwise
  270. bool fPMUPMConversionsRoundTrip;
  271. // In debug builds we guard against improper thread handling
  272. // This guard is passed to the GrDrawingManager and, from there to all the
  273. // GrRenderTargetContexts. It is also passed to the GrResourceProvider and SkGpuDevice.
  274. mutable GrSingleOwner fSingleOwner;
  275. std::unique_ptr<SkTaskGroup> fTaskGroup;
  276. const uint32_t fUniqueID;
  277. std::unique_ptr<GrDrawingManager> fDrawingManager;
  278. GrAuditTrail fAuditTrail;
  279. GrContextOptions::PersistentCache* fPersistentCache;
  280. // TODO: have the GrClipStackClip use renderTargetContexts and rm this friending
  281. friend class GrContextPriv;
  282. /**
  283. * These functions create premul <-> unpremul effects, using the specialized round-trip effects
  284. * from GrConfigConversionEffect.
  285. */
  286. std::unique_ptr<GrFragmentProcessor> createPMToUPMEffect(std::unique_ptr<GrFragmentProcessor>);
  287. std::unique_ptr<GrFragmentProcessor> createUPMToPMEffect(std::unique_ptr<GrFragmentProcessor>);
  288. /**
  289. * Returns true if createPMToUPMEffect and createUPMToPMEffect will succeed. In other words,
  290. * did we find a pair of round-trip preserving conversion effects?
  291. */
  292. bool validPMUPMConversionExists();
  293. /**
  294. * A callback similar to the above for use by the TextBlobCache
  295. * TODO move textblob draw calls below context so we can use the call above.
  296. */
  297. static void TextBlobCacheOverBudgetCB(void* data);
  298. typedef SkRefCnt INHERITED;
  299. };
  300. /**
  301. * Can be used to perform actions related to the generating GrContext in a thread safe manner. The
  302. * proxy does not access the 3D API (e.g. OpenGL) that backs the generating GrContext.
  303. */
  304. class SK_API GrContextThreadSafeProxy : public SkRefCnt {
  305. public:
  306. ~GrContextThreadSafeProxy();
  307. bool matches(GrContext* context) const { return context->uniqueID() == fContextUniqueID; }
  308. /**
  309. * Create a surface characterization for a DDL that will be replayed into the GrContext
  310. * that created this proxy. On failure the resulting characterization will be invalid (i.e.,
  311. * "!c.isValid()").
  312. *
  313. * @param cacheMaxResourceBytes The max resource bytes limit that will be in effect when the
  314. * DDL created with this characterization is replayed.
  315. * Note: the contract here is that the DDL will be created as
  316. * if it had a full 'cacheMaxResourceBytes' to use. If replayed
  317. * into a GrContext that already has locked GPU memory, the
  318. * replay can exceed the budget. To rephrase, all resource
  319. * allocation decisions are made at record time and at playback
  320. * time the budget limits will be ignored.
  321. * @param ii The image info specifying properties of the SkSurface that
  322. * the DDL created with this characterization will be replayed
  323. * into.
  324. * Note: Ganesh doesn't make use of the SkImageInfo's alphaType
  325. * @param backendFormat Information about the format of the GPU surface that will
  326. * back the SkSurface upon replay
  327. * @param sampleCount The sample count of the SkSurface that the DDL created with
  328. * this characterization will be replayed into
  329. * @param origin The origin of the SkSurface that the DDL created with this
  330. * characterization will be replayed into
  331. * @param surfaceProps The surface properties of the SkSurface that the DDL created
  332. * with this characterization will be replayed into
  333. * @param isMipMapped Will the surface the DDL will be replayed into have space
  334. * allocated for mipmaps?
  335. * @param willUseGLFBO0 Will the surface the DDL will be replayed into be backed by GL
  336. * FBO 0. This flag is only valid if using an GL backend.
  337. */
  338. SkSurfaceCharacterization createCharacterization(
  339. size_t cacheMaxResourceBytes,
  340. const SkImageInfo& ii, const GrBackendFormat& backendFormat,
  341. int sampleCount, GrSurfaceOrigin origin,
  342. const SkSurfaceProps& surfaceProps,
  343. bool isMipMapped, bool willUseGLFBO0 = false);
  344. bool operator==(const GrContextThreadSafeProxy& that) const {
  345. // Each GrContext should only ever have a single thread-safe proxy.
  346. SkASSERT((this == &that) == (fContextUniqueID == that.fContextUniqueID));
  347. return this == &that;
  348. }
  349. bool operator!=(const GrContextThreadSafeProxy& that) const { return !(*this == that); }
  350. // Provides access to functions that aren't part of the public API.
  351. GrContextThreadSafeProxyPriv priv();
  352. const GrContextThreadSafeProxyPriv priv() const;
  353. private:
  354. // DDL TODO: need to add unit tests for backend & maybe options
  355. GrContextThreadSafeProxy(sk_sp<const GrCaps> caps,
  356. uint32_t uniqueID,
  357. GrBackendApi backend,
  358. const GrContextOptions& options,
  359. sk_sp<GrSkSLFPFactoryCache> cache);
  360. sk_sp<const GrCaps> fCaps;
  361. const uint32_t fContextUniqueID;
  362. const GrBackendApi fBackend;
  363. const GrContextOptions fOptions;
  364. sk_sp<GrSkSLFPFactoryCache> fFPFactoryCache;
  365. friend class GrDirectContext; // To construct this object
  366. friend class GrContextThreadSafeProxyPriv;
  367. typedef SkRefCnt INHERITED;
  368. };
  369. #endif