GrContext.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 "include/core/SkMatrix.h"
  10. #include "include/core/SkPathEffect.h"
  11. #include "include/core/SkTypes.h"
  12. #include "include/gpu/GrBackendSurface.h"
  13. #include "include/gpu/GrContextOptions.h"
  14. #include "include/private/GrRecordingContext.h"
  15. // We shouldn't need this but currently Android is relying on this being include transitively.
  16. #include "include/core/SkUnPreMultiply.h"
  17. class GrAtlasManager;
  18. class GrBackendSemaphore;
  19. class GrCaps;
  20. class GrContextPriv;
  21. class GrContextThreadSafeProxy;
  22. class GrFragmentProcessor;
  23. struct GrGLInterface;
  24. class GrGpu;
  25. struct GrMockOptions;
  26. class GrPath;
  27. class GrRenderTargetContext;
  28. class GrResourceCache;
  29. class GrResourceProvider;
  30. class GrSamplerState;
  31. class GrSkSLFPFactoryCache;
  32. class GrSurfaceProxy;
  33. class GrSwizzle;
  34. class GrTextContext;
  35. class GrTextureProxy;
  36. struct GrVkBackendContext;
  37. class SkImage;
  38. class SkSurfaceCharacterization;
  39. class SkSurfaceProps;
  40. class SkTaskGroup;
  41. class SkTraceMemoryDump;
  42. class SK_API GrContext : public GrRecordingContext {
  43. public:
  44. /**
  45. * Creates a GrContext for a backend context. If no GrGLInterface is provided then the result of
  46. * GrGLMakeNativeInterface() is used if it succeeds.
  47. */
  48. static sk_sp<GrContext> MakeGL(sk_sp<const GrGLInterface>, const GrContextOptions&);
  49. static sk_sp<GrContext> MakeGL(sk_sp<const GrGLInterface>);
  50. static sk_sp<GrContext> MakeGL(const GrContextOptions&);
  51. static sk_sp<GrContext> MakeGL();
  52. static sk_sp<GrContext> MakeVulkan(const GrVkBackendContext&, const GrContextOptions&);
  53. static sk_sp<GrContext> MakeVulkan(const GrVkBackendContext&);
  54. #ifdef SK_METAL
  55. /**
  56. * Makes a GrContext which uses Metal as the backend. The device parameter is an MTLDevice
  57. * and queue is an MTLCommandQueue which should be used by the backend. These objects must
  58. * have a ref on them which can be transferred to Ganesh which will release the ref when the
  59. * GrContext is destroyed.
  60. */
  61. static sk_sp<GrContext> MakeMetal(void* device, void* queue, const GrContextOptions& options);
  62. static sk_sp<GrContext> MakeMetal(void* device, void* queue);
  63. #endif
  64. #ifdef SK_DAWN
  65. static sk_sp<GrContext> MakeDawn(const dawn::Device& device, const GrContextOptions& options);
  66. static sk_sp<GrContext> MakeDawn(const dawn::Device& device);
  67. #endif
  68. static sk_sp<GrContext> MakeMock(const GrMockOptions*, const GrContextOptions&);
  69. static sk_sp<GrContext> MakeMock(const GrMockOptions*);
  70. ~GrContext() override;
  71. sk_sp<GrContextThreadSafeProxy> threadSafeProxy();
  72. /**
  73. * The GrContext normally assumes that no outsider is setting state
  74. * within the underlying 3D API's context/device/whatever. This call informs
  75. * the context that the state was modified and it should resend. Shouldn't
  76. * be called frequently for good performance.
  77. * The flag bits, state, is dpendent on which backend is used by the
  78. * context, either GL or D3D (possible in future).
  79. */
  80. void resetContext(uint32_t state = kAll_GrBackendState);
  81. /**
  82. * If the backend is GrBackendApi::kOpenGL, then all texture unit/target combinations for which
  83. * the GrContext has modified the bound texture will have texture id 0 bound. This does not
  84. * flush the GrContext. Calling resetContext() does not change the set that will be bound
  85. * to texture id 0 on the next call to resetGLTextureBindings(). After this is called
  86. * all unit/target combinations are considered to have unmodified bindings until the GrContext
  87. * subsequently modifies them (meaning if this is called twice in a row with no intervening
  88. * GrContext usage then the second call is a no-op.)
  89. */
  90. void resetGLTextureBindings();
  91. /**
  92. * Abandons all GPU resources and assumes the underlying backend 3D API context is no 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() override;
  103. /**
  104. * Returns true if the context was abandoned.
  105. */
  106. using GrImageContext::abandoned;
  107. /**
  108. * This is similar to abandonContext() however the underlying 3D context is not yet lost and
  109. * the GrContext will cleanup all allocated resources before returning. After returning it will
  110. * assume that the underlying context may no longer be valid.
  111. *
  112. * The typical use case for this function is that the client is going to destroy the 3D context
  113. * but can't guarantee that GrContext will be destroyed first (perhaps because it may be ref'ed
  114. * elsewhere by either the client or Skia objects).
  115. */
  116. virtual void releaseResourcesAndAbandonContext();
  117. ///////////////////////////////////////////////////////////////////////////
  118. // Resource Cache
  119. /**
  120. * Return the current GPU resource cache limits.
  121. *
  122. * @param maxResources If non-null, returns maximum number of resources that
  123. * can be held in the cache.
  124. * @param maxResourceBytes If non-null, returns maximum number of bytes of
  125. * video memory that can be held in the cache.
  126. */
  127. void getResourceCacheLimits(int* maxResources, size_t* maxResourceBytes) const;
  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. * Gets the number of bytes in the cache consumed by purgeable (e.g. unlocked) resources.
  139. */
  140. size_t getResourceCachePurgeableBytes() const;
  141. /**
  142. * Specify the GPU resource cache limits. If the current cache exceeds either
  143. * of these, it will be purged (LRU) to keep the cache within these limits.
  144. *
  145. * @param maxResources The maximum number of resources that can be held in
  146. * the cache.
  147. * @param maxResourceBytes The maximum number of bytes of video memory
  148. * that can be held in the cache.
  149. */
  150. void setResourceCacheLimits(int maxResources, size_t maxResourceBytes);
  151. /**
  152. * Frees GPU created by the context. Can be called to reduce GPU memory
  153. * pressure.
  154. */
  155. virtual void freeGpuResources();
  156. /**
  157. * Purge GPU resources that haven't been used in the past 'msNotUsed' milliseconds or are
  158. * otherwise marked for deletion, regardless of whether the context is under budget.
  159. */
  160. void performDeferredCleanup(std::chrono::milliseconds msNotUsed);
  161. // Temporary compatibility API for Android.
  162. void purgeResourcesNotUsedInMs(std::chrono::milliseconds msNotUsed) {
  163. this->performDeferredCleanup(msNotUsed);
  164. }
  165. /**
  166. * Purge unlocked resources from the cache until the the provided byte count has been reached
  167. * or we have purged all unlocked resources. The default policy is to purge in LRU order, but
  168. * can be overridden to prefer purging scratch resources (in LRU order) prior to purging other
  169. * resource types.
  170. *
  171. * @param maxBytesToPurge the desired number of bytes to be purged.
  172. * @param preferScratchResources If true scratch resources will be purged prior to other
  173. * resource types.
  174. */
  175. void purgeUnlockedResources(size_t bytesToPurge, bool preferScratchResources);
  176. /**
  177. * This entry point is intended for instances where an app has been backgrounded or
  178. * suspended.
  179. * If 'scratchResourcesOnly' is true all unlocked scratch resources will be purged but the
  180. * unlocked resources with persistent data will remain. If 'scratchResourcesOnly' is false
  181. * then all unlocked resources will be purged.
  182. * In either case, after the unlocked resources are purged a separate pass will be made to
  183. * ensure that resource usage is under budget (i.e., even if 'scratchResourcesOnly' is true
  184. * some resources with persistent data may be purged to be under budget).
  185. *
  186. * @param scratchResourcesOnly If true only unlocked scratch resources will be purged prior
  187. * enforcing the budget requirements.
  188. */
  189. void purgeUnlockedResources(bool scratchResourcesOnly);
  190. /**
  191. * Gets the maximum supported texture size.
  192. */
  193. int maxTextureSize() const;
  194. /**
  195. * Gets the maximum supported render target size.
  196. */
  197. int maxRenderTargetSize() const;
  198. /**
  199. * Can a SkImage be created with the given color type.
  200. */
  201. bool colorTypeSupportedAsImage(SkColorType) const;
  202. /**
  203. * Can a SkSurface be created with the given color type. To check whether MSAA is supported
  204. * use maxSurfaceSampleCountForColorType().
  205. */
  206. bool colorTypeSupportedAsSurface(SkColorType colorType) const {
  207. return this->maxSurfaceSampleCountForColorType(colorType) > 0;
  208. }
  209. /**
  210. * Gets the maximum supported sample count for a color type. 1 is returned if only non-MSAA
  211. * rendering is supported for the color type. 0 is returned if rendering to this color type
  212. * is not supported at all.
  213. */
  214. int maxSurfaceSampleCountForColorType(SkColorType) const;
  215. ///////////////////////////////////////////////////////////////////////////
  216. // Misc.
  217. /**
  218. * Inserts a list of GPU semaphores that the current GPU-backed API must wait on before
  219. * executing any more commands on the GPU. Skia will take ownership of the underlying semaphores
  220. * and delete them once they have been signaled and waited on. If this call returns false, then
  221. * the GPU back-end will not wait on any passed in semaphores, and the client will still own the
  222. * semaphores.
  223. */
  224. bool wait(int numSemaphores, const GrBackendSemaphore* waitSemaphores);
  225. /**
  226. * Call to ensure all drawing to the context has been issued to the underlying 3D API.
  227. */
  228. void flush() {
  229. this->flush(GrFlushInfo(), GrPrepareForExternalIORequests());
  230. }
  231. /**
  232. * Call to ensure all drawing to the context has been issued to the underlying 3D API.
  233. *
  234. * If this call returns GrSemaphoresSubmitted::kNo, the GPU backend will not have created or
  235. * added any semaphores to signal on the GPU. Thus the client should not have the GPU wait on
  236. * any of the semaphores passed in with the GrFlushInfo. However, any pending commands to the
  237. * context will still be flushed. It should be emphasized that a return value of
  238. * GrSemaphoresSubmitted::kNo does not mean the flush did not happen. It simply means there were
  239. * no semaphores submitted to the GPU. A caller should only take this as a failure if they
  240. * passed in semaphores to be submitted.
  241. */
  242. GrSemaphoresSubmitted flush(const GrFlushInfo& info) {
  243. return this->flush(info, GrPrepareForExternalIORequests());
  244. }
  245. /**
  246. * Call to ensure all drawing to the context has been issued to the underlying 3D API.
  247. *
  248. * If this call returns GrSemaphoresSubmitted::kNo, the GPU backend will not have created or
  249. * added any semaphores to signal on the GPU. Thus the client should not have the GPU wait on
  250. * any of the semaphores passed in with the GrFlushInfo. However, any pending commands to the
  251. * context will still be flushed. It should be emphasized that a return value of
  252. * GrSemaphoresSubmitted::kNo does not mean the flush did not happen. It simply means there were
  253. * no semaphores submitted to the GPU. A caller should only take this as a failure if they
  254. * passed in semaphores to be submitted.
  255. *
  256. * If the GrPrepareForExternalIORequests contains valid gpu backed SkSurfaces or SkImages, Skia
  257. * will put the underlying backend objects into a state that is ready for external uses. See
  258. * declaration of GrPreopareForExternalIORequests for more details.
  259. */
  260. GrSemaphoresSubmitted flush(const GrFlushInfo&, const GrPrepareForExternalIORequests&);
  261. /**
  262. * Deprecated.
  263. */
  264. GrSemaphoresSubmitted flush(GrFlushFlags flags, int numSemaphores,
  265. GrBackendSemaphore signalSemaphores[],
  266. GrGpuFinishedProc finishedProc = nullptr,
  267. GrGpuFinishedContext finishedContext = nullptr) {
  268. GrFlushInfo info;
  269. info.fFlags = flags;
  270. info.fNumSemaphores = numSemaphores;
  271. info.fSignalSemaphores = signalSemaphores;
  272. info.fFinishedProc = finishedProc;
  273. info.fFinishedContext = finishedContext;
  274. return this->flush(info);
  275. }
  276. /**
  277. * Deprecated.
  278. */
  279. GrSemaphoresSubmitted flushAndSignalSemaphores(int numSemaphores,
  280. GrBackendSemaphore signalSemaphores[]) {
  281. GrFlushInfo info;
  282. info.fNumSemaphores = numSemaphores;
  283. info.fSignalSemaphores = signalSemaphores;
  284. return this->flush(info);
  285. }
  286. /**
  287. * Checks whether any asynchronous work is complete and if so calls related callbacks.
  288. */
  289. void checkAsyncWorkCompletion();
  290. // Provides access to functions that aren't part of the public API.
  291. GrContextPriv priv();
  292. const GrContextPriv priv() const;
  293. /** Enumerates all cached GPU resources and dumps their memory to traceMemoryDump. */
  294. // Chrome is using this!
  295. void dumpMemoryStatistics(SkTraceMemoryDump* traceMemoryDump) const;
  296. bool supportsDistanceFieldText() const;
  297. void storeVkPipelineCacheData();
  298. static size_t ComputeTextureSize(SkColorType type, int width, int height, GrMipMapped,
  299. bool useNextPow2 = false);
  300. /*
  301. * The explicitly allocated backend texture API allows clients to use Skia to create backend
  302. * objects outside of Skia proper (i.e., Skia's caching system will not know about them.)
  303. *
  304. * It is the client's responsibility to delete all these objects (using deleteBackendTexture)
  305. * before deleting the GrContext used to create them. Additionally, clients should only
  306. * delete these objects on the thread for which that GrContext is active.
  307. *
  308. * The client is responsible for ensuring synchronization between different uses
  309. * of the backend object (i.e., wrapping it in a surface, rendering to it, deleting the
  310. * surface, rewrapping it in a image and drawing the image will require explicit
  311. * sychronization on the client's part).
  312. */
  313. // If possible, create an uninitialized backend texture. The client should ensure that the
  314. // returned backend texture is valid.
  315. // For the Vulkan backend the layout of the created VkImage will be:
  316. // VK_IMAGE_LAYOUT_UNDEFINED.
  317. GrBackendTexture createBackendTexture(int width, int height,
  318. const GrBackendFormat&,
  319. GrMipMapped,
  320. GrRenderable,
  321. GrProtected = GrProtected::kNo);
  322. // If possible, create an uninitialized backend texture. The client should ensure that the
  323. // returned backend texture is valid.
  324. // If successful, the created backend texture will be compatible with the provided
  325. // SkColorType.
  326. // For the Vulkan backend the layout of the created VkImage will be:
  327. // VK_IMAGE_LAYOUT_UNDEFINED.
  328. GrBackendTexture createBackendTexture(int width, int height,
  329. SkColorType,
  330. GrMipMapped,
  331. GrRenderable,
  332. GrProtected = GrProtected::kNo);
  333. // If possible, create an uninitialized backend texture that is compatible with the
  334. // provided characterization. The client should ensure that the returned backend texture
  335. // is valid.
  336. // For the Vulkan backend the layout of the created VkImage will be:
  337. // VK_IMAGE_LAYOUT_UNDEFINED.
  338. GrBackendTexture createBackendTexture(const SkSurfaceCharacterization& characterization);
  339. // If possible, create a backend texture initialized to a particular color. The client should
  340. // ensure that the returned backend texture is valid.
  341. // For the Vulkan backend the layout of the created VkImage will be:
  342. // VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL if renderable is kNo
  343. // and VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL if renderable is kYes
  344. GrBackendTexture createBackendTexture(int width, int height,
  345. const GrBackendFormat&,
  346. const SkColor4f& color,
  347. GrMipMapped,
  348. GrRenderable,
  349. GrProtected = GrProtected::kNo);
  350. // If possible, create a backend texture initialized to a particular color. The client should
  351. // ensure that the returned backend texture is valid.
  352. // If successful, the created backend texture will be compatible with the provided
  353. // SkColorType.
  354. // For the Vulkan backend the layout of the created VkImage will be:
  355. // VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL if renderable is kNo
  356. // and VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL if renderable is kYes
  357. GrBackendTexture createBackendTexture(int width, int height,
  358. SkColorType,
  359. const SkColor4f& color,
  360. GrMipMapped,
  361. GrRenderable,
  362. GrProtected = GrProtected::kNo);
  363. // If possible, create a backend texture initialized to a particular color that is
  364. // compatible with the provided characterization. The client should ensure that the
  365. // returned backend texture is valid.
  366. // For the Vulkan backend the layout of the created VkImage will be:
  367. // VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
  368. GrBackendTexture createBackendTexture(const SkSurfaceCharacterization& characterization,
  369. const SkColor4f& color);
  370. void deleteBackendTexture(GrBackendTexture);
  371. protected:
  372. GrContext(GrBackendApi, const GrContextOptions&, int32_t contextID = SK_InvalidGenID);
  373. bool init(sk_sp<const GrCaps>, sk_sp<GrSkSLFPFactoryCache>) override;
  374. GrContext* asDirectContext() override { return this; }
  375. virtual GrAtlasManager* onGetAtlasManager() = 0;
  376. sk_sp<GrContextThreadSafeProxy> fThreadSafeProxy;
  377. private:
  378. // fTaskGroup must appear before anything that uses it (e.g. fGpu), so that it is destroyed
  379. // after all of its users. Clients of fTaskGroup will generally want to ensure that they call
  380. // wait() on it as they are being destroyed, to avoid the possibility of pending tasks being
  381. // invoked after objects they depend upon have already been destroyed.
  382. std::unique_ptr<SkTaskGroup> fTaskGroup;
  383. sk_sp<GrGpu> fGpu;
  384. GrResourceCache* fResourceCache;
  385. GrResourceProvider* fResourceProvider;
  386. bool fDidTestPMConversions;
  387. // true if the PM/UPM conversion succeeded; false otherwise
  388. bool fPMUPMConversionsRoundTrip;
  389. GrContextOptions::PersistentCache* fPersistentCache;
  390. GrContextOptions::ShaderErrorHandler* fShaderErrorHandler;
  391. // TODO: have the GrClipStackClip use renderTargetContexts and rm this friending
  392. friend class GrContextPriv;
  393. /**
  394. * These functions create premul <-> unpremul effects, using the specialized round-trip effects
  395. * from GrConfigConversionEffect.
  396. */
  397. std::unique_ptr<GrFragmentProcessor> createPMToUPMEffect(std::unique_ptr<GrFragmentProcessor>);
  398. std::unique_ptr<GrFragmentProcessor> createUPMToPMEffect(std::unique_ptr<GrFragmentProcessor>);
  399. typedef GrRecordingContext INHERITED;
  400. };
  401. #endif