GrGpu.h revision 4b68ec08c69ee9f17e13fce2094bb04b12b54856
1/* 2 * Copyright 2011 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 GrGpu_DEFINED 9#define GrGpu_DEFINED 10 11#include "GrDrawTarget.h" 12#include "GrPathRendering.h" 13#include "GrProgramDesc.h" 14#include "SkPath.h" 15 16class GrContext; 17class GrIndexBufferAllocPool; 18class GrPath; 19class GrPathRange; 20class GrPathRenderer; 21class GrPathRendererChain; 22class GrStencilBuffer; 23class GrVertexBufferAllocPool; 24 25class GrGpu : public SkRefCnt { 26public: 27 28 /** 29 * Additional blend coefficients for dual source blending, not exposed 30 * through GrPaint/GrContext. 31 */ 32 enum ExtendedBlendCoeffs { 33 // source 2 refers to second output color when 34 // using dual source blending. 35 kS2C_GrBlendCoeff = kPublicGrBlendCoeffCount, 36 kIS2C_GrBlendCoeff, 37 kS2A_GrBlendCoeff, 38 kIS2A_GrBlendCoeff, 39 40 kTotalGrBlendCoeffCount 41 }; 42 43 /** 44 * Create an instance of GrGpu that matches the specified backend. If the requested backend is 45 * not supported (at compile-time or run-time) this returns NULL. The context will not be 46 * fully constructed and should not be used by GrGpu until after this function returns. 47 */ 48 static GrGpu* Create(GrBackend, GrBackendContext, GrContext* context); 49 50 //////////////////////////////////////////////////////////////////////////// 51 52 GrGpu(GrContext* context); 53 virtual ~GrGpu(); 54 55 GrContext* getContext() { return fContext; } 56 const GrContext* getContext() const { return fContext; } 57 58 /** 59 * Gets the capabilities of the draw target. 60 */ 61 const GrDrawTargetCaps* caps() const { return fCaps.get(); } 62 63 /** 64 * Sets the draw state object for the gpu. Note that this does not 65 * make a copy. The GrGpu will take a reference to passed object. 66 * Passing NULL will cause the GrGpu to use its own internal draw 67 * state object rather than an externally provided one. 68 */ 69 void setDrawState(GrDrawState* drawState); 70 71 /** 72 * Read-only access to the GrGpu current draw state. 73 */ 74 const GrDrawState& getDrawState() const { return *fDrawState; } 75 76 /** 77 * Read-write access to the GrGpu current draw state. Note that 78 * this doesn't ref. 79 */ 80 GrDrawState* drawState() { return fDrawState; } 81 82 GrPathRendering* pathRendering() { 83 return fPathRendering.get(); 84 } 85 86 // Called by GrContext when the underlying backend context has been destroyed. 87 // GrGpu should use this to ensure that no backend API calls will be made from 88 // here onward, including in its destructor. Subclasses should call 89 // INHERITED::contextAbandoned() if they override this. 90 virtual void contextAbandoned(); 91 92 /** 93 * The GrGpu object normally assumes that no outsider is setting state 94 * within the underlying 3D API's context/device/whatever. This call informs 95 * the GrGpu that the state was modified and it shouldn't make assumptions 96 * about the state. 97 */ 98 void markContextDirty(uint32_t state = kAll_GrBackendState) { 99 fResetBits |= state; 100 } 101 102 void unimpl(const char[]); 103 104 /** 105 * Creates a texture object. If desc width or height is not a power of 106 * two but underlying API requires a power of two texture then srcData 107 * will be embedded in a power of two texture. The extra width and height 108 * is filled as though srcData were rendered clamped into the texture. 109 * The exception is when using compressed data formats. In this case, the 110 * desc width and height must be a multiple of the compressed format block 111 * size otherwise this function returns NULL. Similarly, if the underlying 112 * API requires a power of two texture and the source width and height are not 113 * a power of two, then this function returns NULL. 114 * 115 * If kRenderTarget_TextureFlag is specified the GrRenderTarget is 116 * accessible via GrTexture::asRenderTarget(). The texture will hold a ref 117 * on the render target until the texture is destroyed. Compressed textures 118 * cannot have the kRenderTarget_TextureFlag set. 119 * 120 * @param desc describes the texture to be created. 121 * @param srcData texel data to load texture. Begins with full-size 122 * palette data for paletted textures. For compressed 123 * formats it contains the compressed pixel data. Otherwise, 124 * it contains width*height texels. If NULL texture data 125 * is uninitialized. 126 * @param rowBytes the number of bytes between consecutive rows. Zero 127 * means rows are tightly packed. This field is ignored 128 * for compressed formats. 129 * 130 * @return The texture object if successful, otherwise NULL. 131 */ 132 GrTexture* createTexture(const GrSurfaceDesc& desc, 133 const void* srcData, size_t rowBytes); 134 135 /** 136 * Implements GrContext::wrapBackendTexture 137 */ 138 GrTexture* wrapBackendTexture(const GrBackendTextureDesc&); 139 140 /** 141 * Implements GrContext::wrapBackendTexture 142 */ 143 GrRenderTarget* wrapBackendRenderTarget(const GrBackendRenderTargetDesc&); 144 145 /** 146 * Creates a vertex buffer. 147 * 148 * @param size size in bytes of the vertex buffer 149 * @param dynamic hints whether the data will be frequently changed 150 * by either GrVertexBuffer::map() or 151 * GrVertexBuffer::updateData(). 152 * 153 * @return The vertex buffer if successful, otherwise NULL. 154 */ 155 GrVertexBuffer* createVertexBuffer(size_t size, bool dynamic); 156 157 /** 158 * Creates an index buffer. 159 * 160 * @param size size in bytes of the index buffer 161 * @param dynamic hints whether the data will be frequently changed 162 * by either GrIndexBuffer::map() or 163 * GrIndexBuffer::updateData(). 164 * 165 * @return The index buffer if successful, otherwise NULL. 166 */ 167 GrIndexBuffer* createIndexBuffer(size_t size, bool dynamic); 168 169 /** 170 * Creates an index buffer for instance drawing with a specific pattern. 171 * 172 * @param pattern the pattern to repeat 173 * @param patternSize size in bytes of the pattern 174 * @param reps number of times to repeat the pattern 175 * @param vertCount number of vertices the pattern references 176 * @param dynamic hints whether the data will be frequently changed 177 * by either GrIndexBuffer::map() or 178 * GrIndexBuffer::updateData(). 179 * 180 * @return The index buffer if successful, otherwise NULL. 181 */ 182 GrIndexBuffer* createInstancedIndexBuffer(const uint16_t* pattern, 183 int patternSize, 184 int reps, 185 int vertCount, 186 bool isDynamic = false); 187 188 /** 189 * Returns an index buffer that can be used to render quads. 190 * Six indices per quad: 0, 1, 2, 0, 2, 3, etc. 191 * The max number of quads can be queried using GrIndexBuffer::maxQuads(). 192 * Draw with kTriangles_GrPrimitiveType 193 * @ return the quad index buffer 194 */ 195 const GrIndexBuffer* getQuadIndexBuffer() const; 196 197 /** 198 * Resolves MSAA. 199 */ 200 void resolveRenderTarget(GrRenderTarget* target); 201 202 /** 203 * Gets a preferred 8888 config to use for writing/reading pixel data to/from a surface with 204 * config surfaceConfig. The returned config must have at least as many bits per channel as the 205 * readConfig or writeConfig param. 206 */ 207 virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig readConfig, 208 GrPixelConfig surfaceConfig) const { 209 return readConfig; 210 } 211 virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig writeConfig, 212 GrPixelConfig surfaceConfig) const { 213 return writeConfig; 214 } 215 216 /** 217 * Called before uploading writing pixels to a GrTexture when the src pixel config doesn't 218 * match the texture's config. 219 */ 220 virtual bool canWriteTexturePixels(const GrTexture*, GrPixelConfig srcConfig) const = 0; 221 222 /** 223 * OpenGL's readPixels returns the result bottom-to-top while the skia 224 * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious 225 * solution is to have the subclass do the flip using either the CPU or GPU. 226 * However, the caller (GrContext) may have transformations to apply and can 227 * simply fold in the y-flip for free. On the other hand, the subclass may 228 * be able to do it for free itself. For example, the subclass may have to 229 * do memcpys to handle rowBytes that aren't tight. It could do the y-flip 230 * concurrently. 231 * 232 * This function returns true if a y-flip is required to put the pixels in 233 * top-to-bottom order and the subclass cannot do it for free. 234 * 235 * See read pixels for the params 236 * @return true if calling readPixels with the same set of params will 237 * produce bottom-to-top data 238 */ 239 virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget, 240 int left, int top, 241 int width, int height, 242 GrPixelConfig config, 243 size_t rowBytes) const = 0; 244 /** 245 * This should return true if reading a NxM rectangle of pixels from a 246 * render target is faster if the target has dimensons N and M and the read 247 * rectangle has its top-left at 0,0. 248 */ 249 virtual bool fullReadPixelsIsFasterThanPartial() const { return false; }; 250 251 /** 252 * Reads a rectangle of pixels from a render target. 253 * 254 * @param renderTarget the render target to read from. NULL means the 255 * current render target. 256 * @param left left edge of the rectangle to read (inclusive) 257 * @param top top edge of the rectangle to read (inclusive) 258 * @param width width of rectangle to read in pixels. 259 * @param height height of rectangle to read in pixels. 260 * @param config the pixel config of the destination buffer 261 * @param buffer memory to read the rectangle into. 262 * @param rowBytes the number of bytes between consecutive rows. Zero 263 * means rows are tightly packed. 264 * @param invertY buffer should be populated bottom-to-top as opposed 265 * to top-to-bottom (skia's usual order) 266 * 267 * @return true if the read succeeded, false if not. The read can fail 268 * because of a unsupported pixel config or because no render 269 * target is currently set. 270 */ 271 bool readPixels(GrRenderTarget* renderTarget, 272 int left, int top, int width, int height, 273 GrPixelConfig config, void* buffer, size_t rowBytes); 274 275 /** 276 * Updates the pixels in a rectangle of a texture. 277 * 278 * @param left left edge of the rectangle to write (inclusive) 279 * @param top top edge of the rectangle to write (inclusive) 280 * @param width width of rectangle to write in pixels. 281 * @param height height of rectangle to write in pixels. 282 * @param config the pixel config of the source buffer 283 * @param buffer memory to read pixels from 284 * @param rowBytes number of bytes between consecutive rows. Zero 285 * means rows are tightly packed. 286 */ 287 bool writeTexturePixels(GrTexture* texture, 288 int left, int top, int width, int height, 289 GrPixelConfig config, const void* buffer, 290 size_t rowBytes); 291 292 /** 293 * Clear the passed in render target. Ignores the draw state and clip. Clears the whole thing if 294 * rect is NULL, otherwise just the rect. If canIgnoreRect is set then the entire render target 295 * can be optionally cleared. 296 */ 297 void clear(const SkIRect* rect, 298 GrColor color, 299 bool canIgnoreRect, 300 GrRenderTarget* renderTarget); 301 302 303 void clearStencilClip(const SkIRect& rect, 304 bool insideClip, 305 GrRenderTarget* renderTarget = NULL); 306 307 /** 308 * Discards the contents render target. NULL indicates that the current render target should 309 * be discarded. 310 **/ 311 virtual void discard(GrRenderTarget* = NULL) = 0; 312 313 /** 314 * This is can be called before allocating a texture to be a dst for copySurface. It will 315 * populate the origin, config, and flags fields of the desc such that copySurface is more 316 * likely to succeed and be efficient. 317 */ 318 virtual void initCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* desc); 319 320 // After the client interacts directly with the 3D context state the GrGpu 321 // must resync its internal state and assumptions about 3D context state. 322 // Each time this occurs the GrGpu bumps a timestamp. 323 // state of the 3D context 324 // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about 325 // a billion years. 326 typedef uint64_t ResetTimestamp; 327 328 // This timestamp is always older than the current timestamp 329 static const ResetTimestamp kExpiredTimestamp = 0; 330 // Returns a timestamp based on the number of times the context was reset. 331 // This timestamp can be used to lazily detect when cached 3D context state 332 // is dirty. 333 ResetTimestamp getResetTimestamp() const { 334 return fResetTimestamp; 335 } 336 337 enum DrawType { 338 kDrawPoints_DrawType, 339 kDrawLines_DrawType, 340 kDrawTriangles_DrawType, 341 kStencilPath_DrawType, 342 kDrawPath_DrawType, 343 kDrawPaths_DrawType, 344 }; 345 346 static bool IsPathRenderingDrawType(DrawType type) { 347 return kDrawPath_DrawType == type || kDrawPaths_DrawType == type; 348 } 349 350 GrContext::GPUStats* gpuStats() { return &fGPUStats; } 351 352 virtual void buildProgramDesc(const GrOptDrawState&, 353 const GrProgramDesc::DescInfo&, 354 GrGpu::DrawType, 355 const GrDeviceCoordTexture* dstCopy, 356 GrProgramDesc*) = 0; 357 358 /** 359 * Called at start and end of gpu trace marking 360 * GR_CREATE_GPU_TRACE_MARKER(marker_str, target) will automatically call these at the start 361 * and end of a code block respectively 362 */ 363 void addGpuTraceMarker(const GrGpuTraceMarker* marker); 364 void removeGpuTraceMarker(const GrGpuTraceMarker* marker); 365 366 /** 367 * Takes the current active set of markers and stores them for later use. Any current marker 368 * in the active set is removed from the active set and the targets remove function is called. 369 * These functions do not work as a stack so you cannot call save a second time before calling 370 * restore. Also, it is assumed that when restore is called the current active set of markers 371 * is empty. When the stored markers are added back into the active set, the targets add marker 372 * is called. 373 */ 374 void saveActiveTraceMarkers(); 375 void restoreActiveTraceMarkers(); 376 377 // Called to determine whether an onCopySurface call would succeed or not. This is useful for 378 // proxy subclasses to test whether the copy would succeed without executing it yet. Derived 379 // classes must keep this consistent with their implementation of onCopySurface(). The inputs 380 // are the same as onCopySurface(), i.e. srcRect and dstPoint are clipped to be inside the src 381 // and dst bounds. 382 virtual bool canCopySurface(GrSurface* dst, 383 GrSurface* src, 384 const SkIRect& srcRect, 385 const SkIPoint& dstPoint) = 0; 386 387 // This method is called by copySurface The srcRect is guaranteed to be entirely within the 388 // src bounds. Likewise, the dst rect implied by dstPoint and srcRect's width and height falls 389 // entirely within the dst. The default implementation will draw a rect from the src to the 390 // dst if the src is a texture and the dst is a render target and fail otherwise. 391 virtual bool copySurface(GrSurface* dst, 392 GrSurface* src, 393 const SkIRect& srcRect, 394 const SkIPoint& dstPoint) = 0; 395 396 /** 397 * Sets source of vertex data for the next draw. Data does not have to be 398 * in the buffer until drawIndexed, drawNonIndexed, or drawIndexedInstances. 399 * 400 * @param buffer vertex buffer containing vertex data. Must be 401 * unlocked before draw call. Vertex size is queried 402 * from current GrDrawState. 403 */ 404 void setVertexSourceToBuffer(const GrVertexBuffer* buffer); 405 406 /** 407 * Sets source of index data for the next indexed draw. Data does not have 408 * to be in the buffer until drawIndexed. 409 * 410 * @param buffer index buffer containing indices. Must be unlocked 411 * before indexed draw call. 412 */ 413 void setIndexSourceToBuffer(const GrIndexBuffer* buffer); 414 415 virtual void draw(const GrDrawTarget::DrawInfo&, 416 const GrClipMaskManager::ScissorState&); 417 virtual void stencilPath(const GrPath*, 418 const GrClipMaskManager::ScissorState&, 419 const GrStencilSettings&); 420 virtual void drawPath(const GrPath*, 421 const GrClipMaskManager::ScissorState&, 422 const GrStencilSettings&, 423 const GrDeviceCoordTexture* dstCopy); 424 virtual void drawPaths(const GrPathRange*, 425 const uint32_t indices[], 426 int count, 427 const float transforms[], 428 GrDrawTarget::PathTransformType, 429 const GrClipMaskManager::ScissorState&, 430 const GrStencilSettings&, 431 const GrDeviceCoordTexture*); 432 433protected: 434 DrawType PrimTypeToDrawType(GrPrimitiveType type) { 435 switch (type) { 436 case kTriangles_GrPrimitiveType: 437 case kTriangleStrip_GrPrimitiveType: 438 case kTriangleFan_GrPrimitiveType: 439 return kDrawTriangles_DrawType; 440 case kPoints_GrPrimitiveType: 441 return kDrawPoints_DrawType; 442 case kLines_GrPrimitiveType: 443 case kLineStrip_GrPrimitiveType: 444 return kDrawLines_DrawType; 445 default: 446 SkFAIL("Unexpected primitive type"); 447 return kDrawTriangles_DrawType; 448 } 449 } 450 451 // Functions used to map clip-respecting stencil tests into normal 452 // stencil funcs supported by GPUs. 453 static GrStencilFunc ConvertStencilFunc(bool stencilInClip, 454 GrStencilFunc func); 455 static void ConvertStencilFuncAndMask(GrStencilFunc func, 456 bool clipInStencil, 457 unsigned int clipBit, 458 unsigned int userBits, 459 unsigned int* ref, 460 unsigned int* mask); 461 462 struct GeometrySrcState { 463 GeometrySrcState() : fVertexBuffer(NULL), fIndexBuffer(NULL), fVertexSize(0) {} 464 const GrVertexBuffer* fVertexBuffer; 465 const GrIndexBuffer* fIndexBuffer; 466 size_t fVertexSize; 467 }; 468 469 // accessors for derived classes 470 const GeometrySrcState& getGeomSrc() const { return fGeoSrcState; } 471 472 // it is preferable to call this rather than getGeomSrc()->fVertexSize because of the assert. 473 size_t getVertexSize() const { 474 // the vertex layout is only valid if a vertex source has been specified. 475 SkASSERT(this->getGeomSrc().fVertexBuffer); 476 return this->getGeomSrc().fVertexSize; 477 } 478 479 const GrTraceMarkerSet& getActiveTraceMarkers() { return fActiveTraceMarkers; } 480 481 GrContext::GPUStats fGPUStats; 482 483 SkAutoTDelete<GrPathRendering> fPathRendering; 484 485 // Subclass must initialize this in its constructor. 486 SkAutoTUnref<const GrDrawTargetCaps> fCaps; 487 488private: 489 // called when the 3D context state is unknown. Subclass should emit any 490 // assumed 3D context state and dirty any state cache. 491 virtual void onResetContext(uint32_t resetBits) = 0; 492 493 // overridden by backend-specific derived class to create objects. 494 virtual GrTexture* onCreateTexture(const GrSurfaceDesc& desc, 495 const void* srcData, 496 size_t rowBytes) = 0; 497 virtual GrTexture* onCreateCompressedTexture(const GrSurfaceDesc& desc, 498 const void* srcData) = 0; 499 virtual GrTexture* onWrapBackendTexture(const GrBackendTextureDesc&) = 0; 500 virtual GrRenderTarget* onWrapBackendRenderTarget(const GrBackendRenderTargetDesc&) = 0; 501 virtual GrVertexBuffer* onCreateVertexBuffer(size_t size, bool dynamic) = 0; 502 virtual GrIndexBuffer* onCreateIndexBuffer(size_t size, bool dynamic) = 0; 503 504 // overridden by backend-specific derived class to perform the clear. 505 virtual void onClear(GrRenderTarget*, const SkIRect* rect, GrColor color, 506 bool canIgnoreRect) = 0; 507 508 509 // Overridden by backend specific classes to perform a clear of the stencil clip bits. This is 510 // ONLY used by the the clip target 511 virtual void onClearStencilClip(GrRenderTarget*, 512 const SkIRect& rect, 513 bool insideClip) = 0; 514 515 // overridden by backend-specific derived class to perform the draw call. 516 virtual void onDraw(const GrDrawTarget::DrawInfo&) = 0; 517 518 // overridden by backend-specific derived class to perform the read pixels. 519 virtual bool onReadPixels(GrRenderTarget* target, 520 int left, int top, int width, int height, 521 GrPixelConfig, 522 void* buffer, 523 size_t rowBytes) = 0; 524 525 // overridden by backend-specific derived class to perform the texture update 526 virtual bool onWriteTexturePixels(GrTexture* texture, 527 int left, int top, int width, int height, 528 GrPixelConfig config, const void* buffer, 529 size_t rowBytes) = 0; 530 531 // overridden by backend-specific derived class to perform the resolve 532 virtual void onResolveRenderTarget(GrRenderTarget* target) = 0; 533 534 // width and height may be larger than rt (if underlying API allows it). 535 // Should attach the SB to the RT. Returns false if compatible sb could 536 // not be created. 537 virtual bool createStencilBufferForRenderTarget(GrRenderTarget*, int width, int height) = 0; 538 539 // attaches an existing SB to an existing RT. 540 virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer*, GrRenderTarget*) = 0; 541 542 // The GrGpu typically records the clients requested state and then flushes 543 // deltas from previous state at draw time. This function does the 544 // backend-specific flush of the state. 545 // returns false if current state is unsupported. 546 virtual bool flushGraphicsState(DrawType, 547 const GrClipMaskManager::ScissorState&, 548 const GrDeviceCoordTexture* dstCopy) = 0; 549 550 // clears target's entire stencil buffer to 0 551 virtual void clearStencil(GrRenderTarget* target) = 0; 552 553 // Given a rt, find or create a stencil buffer and attach it 554 bool attachStencilBufferToRenderTarget(GrRenderTarget* target); 555 556 virtual void didAddGpuTraceMarker() = 0; 557 virtual void didRemoveGpuTraceMarker() = 0; 558 559 void resetContext() { 560 this->onResetContext(fResetBits); 561 fResetBits = 0; 562 ++fResetTimestamp; 563 } 564 565 void handleDirtyContext() { 566 if (fResetBits) { 567 this->resetContext(); 568 } 569 } 570 571 GeometrySrcState fGeoSrcState; 572 ResetTimestamp fResetTimestamp; 573 uint32_t fResetBits; 574 // these are mutable so they can be created on-demand 575 mutable GrIndexBuffer* fQuadIndexBuffer; 576 GrDrawState fDefaultDrawState; 577 GrDrawState* fDrawState; 578 // To keep track that we always have at least as many debug marker adds as removes 579 int fGpuTraceMarkerCount; 580 GrTraceMarkerSet fActiveTraceMarkers; 581 GrTraceMarkerSet fStoredTraceMarkers; 582 // The context owns us, not vice-versa, so this ptr is not ref'ed by Gpu. 583 GrContext* fContext; 584 585 typedef SkRefCnt INHERITED; 586}; 587 588#endif 589