GrGpu.h revision f105b109264f71dfb0bfd9977e6a5dd0a5a12f57
1 2/* 3 * Copyright 2011 Google Inc. 4 * 5 * Use of this source code is governed by a BSD-style license that can be 6 * found in the LICENSE file. 7 */ 8 9 10#ifndef GrGpu_DEFINED 11#define GrGpu_DEFINED 12 13#include "GrDrawTarget.h" 14#include "GrRect.h" 15#include "GrRefCnt.h" 16#include "GrTexture.h" 17#include "GrClipMaskManager.h" 18 19class GrContext; 20class GrIndexBufferAllocPool; 21class GrPathRenderer; 22class GrPathRendererChain; 23class GrResource; 24class GrStencilBuffer; 25class GrVertexBufferAllocPool; 26 27/** 28 * Gpu usage statistics. 29 */ 30struct GrGpuStats { 31 uint32_t fVertexCnt; //<! Number of vertices drawn 32 uint32_t fIndexCnt; //<! Number of indices drawn 33 uint32_t fDrawCnt; //<! Number of draws 34 35 uint32_t fProgChngCnt;//<! Number of program changes 36 37 /** 38 * Number of times the texture is set in 3D API 39 */ 40 uint32_t fTextureChngCnt; 41 /** 42 * Number of times the render target is set in 3D API 43 */ 44 uint32_t fRenderTargetChngCnt; 45 /** 46 * Number of textures created (includes textures that are rendertargets). 47 */ 48 uint32_t fTextureCreateCnt; 49 /** 50 * Number of rendertargets created. 51 */ 52 uint32_t fRenderTargetCreateCnt; 53}; 54 55class GrGpu : public GrDrawTarget { 56 57public: 58 59 /** 60 * Additional blend coeffecients for dual source blending, not exposed 61 * through GrPaint/GrContext. 62 */ 63 enum ExtendedBlendCoeffs { 64 // source 2 refers to second output color when 65 // using dual source blending. 66 kS2C_BlendCoeff = kPublicBlendCoeffCount, 67 kIS2C_BlendCoeff, 68 kS2A_BlendCoeff, 69 kIS2A_BlendCoeff, 70 71 kTotalBlendCoeffCount 72 }; 73 74 /** 75 * Create an instance of GrGpu that matches the specified Engine backend. 76 * If the requested engine is not supported (at compile-time or run-time) 77 * this returns NULL. 78 */ 79 static GrGpu* Create(GrEngine, GrPlatform3DContext context3D); 80 81 //////////////////////////////////////////////////////////////////////////// 82 83 GrGpu(); 84 virtual ~GrGpu(); 85 86 // The GrContext sets itself as the owner of this Gpu object 87 void setContext(GrContext* context) { 88 GrAssert(NULL == fContext); 89 fContext = context; 90 fClipMaskManager.setContext(context); 91 } 92 GrContext* getContext() { return fContext; } 93 const GrContext* getContext() const { return fContext; } 94 95 /** 96 * The GrGpu object normally assumes that no outsider is setting state 97 * within the underlying 3D API's context/device/whatever. This call informs 98 * the GrGpu that the state was modified and it shouldn't make assumptions 99 * about the state. 100 */ 101 void markContextDirty() { fContextIsDirty = true; } 102 103 void unimpl(const char[]); 104 105 /** 106 * Creates a texture object. If desc width or height is not a power of 107 * two but underlying API requires a power of two texture then srcData 108 * will be embedded in a power of two texture. The extra width and height 109 * is filled as though srcData were rendered clamped into the texture. 110 * 111 * If kRenderTarget_TextureFlag is specified the GrRenderTarget is 112 * accessible via GrTexture::asRenderTarget(). The texture will hold a ref 113 * on the render target until its releaseRenderTarget() is called or it is 114 * destroyed. 115 * 116 * @param desc describes the texture to be created. 117 * @param srcData texel data to load texture. Begins with full-size 118 * palette data for paletted textures. Contains width* 119 * height texels. If NULL texture data is uninitialized. 120 * 121 * @return The texture object if successful, otherwise NULL. 122 */ 123 GrTexture* createTexture(const GrTextureDesc& desc, 124 const void* srcData, size_t rowBytes); 125 126 /** 127 * Implements GrContext::createPlatformTexture 128 */ 129 GrTexture* createPlatformTexture(const GrPlatformTextureDesc& desc); 130 131 /** 132 * Implements GrContext::createPlatformTexture 133 */ 134 GrRenderTarget* createPlatformRenderTarget(const GrPlatformRenderTargetDesc& desc); 135 136 /** 137 * Creates a vertex buffer. 138 * 139 * @param size size in bytes of the vertex buffer 140 * @param dynamic hints whether the data will be frequently changed 141 * by either GrVertexBuffer::lock or 142 * GrVertexBuffer::updateData. 143 * 144 * @return The vertex buffer if successful, otherwise NULL. 145 */ 146 GrVertexBuffer* createVertexBuffer(uint32_t size, bool dynamic); 147 148 /** 149 * Creates an index buffer. 150 * 151 * @param size size in bytes of the index buffer 152 * @param dynamic hints whether the data will be frequently changed 153 * by either GrIndexBuffer::lock or 154 * GrIndexBuffer::updateData. 155 * 156 * @return The index buffer if successful, otherwise NULL. 157 */ 158 GrIndexBuffer* createIndexBuffer(uint32_t size, bool dynamic); 159 160 /** 161 * Returns an index buffer that can be used to render quads. 162 * Six indices per quad: 0, 1, 2, 0, 2, 3, etc. 163 * The max number of quads can be queried using GrIndexBuffer::maxQuads(). 164 * Draw with kTriangles_PrimitiveType 165 * @ return the quad index buffer 166 */ 167 const GrIndexBuffer* getQuadIndexBuffer() const; 168 169 /** 170 * Returns a vertex buffer with four position-only vertices [(0,0), (1,0), 171 * (1,1), (0,1)]. 172 * @ return unit square vertex buffer 173 */ 174 const GrVertexBuffer* getUnitSquareVertexBuffer() const; 175 176 /** 177 * Resolves MSAA. 178 */ 179 void resolveRenderTarget(GrRenderTarget* target); 180 181 /** 182 * Ensures that the current render target is actually set in the 183 * underlying 3D API. Used when client wants to use 3D API to directly 184 * render to the RT. 185 */ 186 void forceRenderTargetFlush(); 187 188 /** 189 * If this returns true then a sequence that reads unpremultiplied pixels 190 * from a surface, writes back the same values, and reads them again will 191 * give the same pixel values back in both reads. 192 */ 193 virtual bool canPreserveReadWriteUnpremulPixels() = 0; 194 195 /** 196 * readPixels with some configs may be slow. Given a desired config this 197 * function returns a fast-path config. The returned config must have the 198 * same components, component sizes, and not require conversion between 199 * pre- and unpremultiplied alpha. The caller is free to ignore the result 200 * and call readPixels with the original config. 201 */ 202 virtual GrPixelConfig preferredReadPixelsConfig(GrPixelConfig config) 203 const { 204 return config; 205 } 206 207 /** 208 * Same as above but applies to writeTexturePixels 209 */ 210 virtual GrPixelConfig preferredWritePixelsConfig(GrPixelConfig config) 211 const { 212 return config; 213 } 214 215 /** 216 * OpenGL's readPixels returns the result bottom-to-top while the skia 217 * API is top-to-bottom. Thus we have to do a y-axis flip. The obvious 218 * solution is to have the subclass do the flip using either the CPU or GPU. 219 * However, the caller (GrContext) may have transformations to apply and can 220 * simply fold in the y-flip for free. On the other hand, the subclass may 221 * be able to do it for free itself. For example, the subclass may have to 222 * do memcpys to handle rowBytes that aren't tight. It could do the y-flip 223 * concurrently. 224 * 225 * This function returns true if a y-flip is required to put the pixels in 226 * top-to-bottom order and the subclass cannot do it for free. 227 * 228 * See read pixels for the params 229 * @return true if calling readPixels with the same set of params will 230 * produce bottom-to-top data 231 */ 232 virtual bool readPixelsWillPayForYFlip(GrRenderTarget* renderTarget, 233 int left, int top, 234 int width, int height, 235 GrPixelConfig config, 236 size_t rowBytes) const = 0; 237 /** 238 * This should return true if reading a NxM rectangle of pixels from a 239 * render target is faster if the target has dimensons N and M and the read 240 * rectangle has its top-left at 0,0. 241 */ 242 virtual bool fullReadPixelsIsFasterThanPartial() const { return false; }; 243 244 /** 245 * Reads a rectangle of pixels from a render target. Fails if read requires 246 * conversion between premultiplied and unpremultiplied configs. The caller 247 * should do the conversion by rendering to a target with the desire config 248 * first. 249 * 250 * @param renderTarget the render target to read from. NULL means the 251 * current render target. 252 * @param left left edge of the rectangle to read (inclusive) 253 * @param top top edge of the rectangle to read (inclusive) 254 * @param width width of rectangle to read in pixels. 255 * @param height height of rectangle to read in pixels. 256 * @param config the pixel config of the destination buffer 257 * @param buffer memory to read the rectangle into. 258 * @param rowBytes the number of bytes between consecutive rows. Zero 259 * means rows are tightly packed. 260 * @param invertY buffer should be populated bottom-to-top as opposed 261 * to top-to-bottom (skia's usual order) 262 * 263 * @return true if the read succeeded, false if not. The read can fail 264 * because of a unsupported pixel config or because no render 265 * target is currently set. 266 */ 267 bool readPixels(GrRenderTarget* renderTarget, 268 int left, int top, int width, int height, 269 GrPixelConfig config, void* buffer, size_t rowBytes, 270 bool invertY); 271 272 /** 273 * Updates the pixels in a rectangle of a texture. 274 * 275 * @param left left edge of the rectangle to write (inclusive) 276 * @param top top edge of the rectangle to write (inclusive) 277 * @param width width of rectangle to write in pixels. 278 * @param height height of rectangle to write in pixels. 279 * @param config the pixel config of the source buffer 280 * @param buffer memory to read pixels from 281 * @param rowBytes number of bytes bewtween consecutive rows. Zero 282 * means rows are tightly packed. 283 */ 284 void writeTexturePixels(GrTexture* texture, 285 int left, int top, int width, int height, 286 GrPixelConfig config, const void* buffer, 287 size_t rowBytes); 288 289 const GrGpuStats& getStats() const; 290 void resetStats(); 291 void printStats() const; 292 293 /** 294 * Called to tell Gpu object that all GrResources have been lost and should 295 * be abandoned. Overrides must call INHERITED::abandonResources(). 296 */ 297 virtual void abandonResources(); 298 299 /** 300 * Called to tell Gpu object to release all GrResources. Overrides must call 301 * INHERITED::releaseResources(). 302 */ 303 void releaseResources(); 304 305 /** 306 * Add resource to list of resources. Should only be called by GrResource. 307 * @param resource the resource to add. 308 */ 309 void insertResource(GrResource* resource); 310 311 /** 312 * Remove resource from list of resources. Should only be called by 313 * GrResource. 314 * @param resource the resource to remove. 315 */ 316 void removeResource(GrResource* resource); 317 318 // GrDrawTarget overrides 319 virtual void clear(const GrIRect* rect, GrColor color); 320 321 // After the client interacts directly with the 3D context state the GrGpu 322 // must resync its internal state and assumptions about 3D context state. 323 // Each time this occurs the GrGpu bumps a timestamp. 324 // state of the 3D context 325 // At 10 resets / frame and 60fps a 64bit timestamp will overflow in about 326 // a billion years. 327 typedef uint64_t ResetTimestamp; 328 329 // This timestamp is always older than the current timestamp 330 static const ResetTimestamp kExpiredTimestamp = 0; 331 // Returns a timestamp based on the number of times the context was reset. 332 // This timestamp can be used to lazily detect when cached 3D context state 333 // is dirty. 334 ResetTimestamp getResetTimestamp() const { 335 return fResetTimestamp; 336 } 337 338 /** 339 * Can the provided configuration act as a color render target? 340 */ 341 bool isConfigRenderable(GrPixelConfig config) const { 342 GrAssert(kGrPixelConfigCount > config); 343 return fConfigRenderSupport[config]; 344 } 345 346 virtual void enableScissoring(const GrIRect& rect) = 0; 347 virtual void disableScissor() = 0; 348 349 // GrGpu subclass sets clip bit in the stencil buffer. The subclass is 350 // free to clear the remaining bits to zero if masked clears are more 351 // expensive than clearing all bits. 352 virtual void clearStencilClip(const GrIRect& rect, bool insideClip) = 0; 353 354 enum PrivateDrawStateStateBits { 355 kFirstBit = (GrDrawState::kLastPublicStateBit << 1), 356 357 kModifyStencilClip_StateBit = kFirstBit, // allows draws to modify 358 // stencil bits used for 359 // clipping. 360 }; 361 362protected: 363 // prepares clip flushes gpu state before a draw 364 bool setupClipAndFlushState(GrPrimitiveType type); 365 366 // Functions used to map clip-respecting stencil tests into normal 367 // stencil funcs supported by GPUs. 368 static GrStencilFunc ConvertStencilFunc(bool stencilInClip, 369 GrStencilFunc func); 370 static void ConvertStencilFuncAndMask(GrStencilFunc func, 371 bool clipInStencil, 372 unsigned int clipBit, 373 unsigned int userBits, 374 unsigned int* ref, 375 unsigned int* mask); 376 377 // stencil settings to clip drawing when stencil clipping is in effect 378 // and the client isn't using the stencil test. 379 static const GrStencilSettings* GetClipStencilSettings(); 380 381 GrGpuStats fStats; 382 383 GrClipMaskManager fClipMaskManager; 384 385 struct GeometryPoolState { 386 const GrVertexBuffer* fPoolVertexBuffer; 387 int fPoolStartVertex; 388 389 const GrIndexBuffer* fPoolIndexBuffer; 390 int fPoolStartIndex; 391 }; 392 const GeometryPoolState& getGeomPoolState() { 393 return fGeomPoolStateStack.back(); 394 } 395 396 // Derived classes need access to this so they can fill it out in their 397 // constructors 398 bool fConfigRenderSupport[kGrPixelConfigCount]; 399 400 // GrDrawTarget overrides 401 virtual bool onReserveVertexSpace(GrVertexLayout vertexLayout, 402 int vertexCount, 403 void** vertices); 404 virtual bool onReserveIndexSpace(int indexCount, void** indices); 405 virtual void releaseReservedVertexSpace(); 406 virtual void releaseReservedIndexSpace(); 407 virtual void onSetVertexSourceToArray(const void* vertexArray, 408 int vertexCount); 409 virtual void onSetIndexSourceToArray(const void* indexArray, 410 int indexCount); 411 virtual void releaseVertexArray(); 412 virtual void releaseIndexArray(); 413 virtual void geometrySourceWillPush(); 414 virtual void geometrySourceWillPop(const GeometrySrcState& restoredState); 415 416 // Helpers for setting up geometry state 417 void finalizeReservedVertices(); 418 void finalizeReservedIndices(); 419 420 // called when the 3D context state is unknown. Subclass should emit any 421 // assumed 3D context state and dirty any state cache 422 virtual void onResetContext() = 0; 423 424 425 // overridden by API-specific derived class to create objects. 426 virtual GrTexture* onCreateTexture(const GrTextureDesc& desc, 427 const void* srcData, 428 size_t rowBytes) = 0; 429 virtual GrTexture* onCreatePlatformTexture(const GrPlatformTextureDesc& desc) = 0; 430 virtual GrRenderTarget* onCreatePlatformRenderTarget(const GrPlatformRenderTargetDesc& desc) = 0; 431 virtual GrVertexBuffer* onCreateVertexBuffer(uint32_t size, 432 bool dynamic) = 0; 433 virtual GrIndexBuffer* onCreateIndexBuffer(uint32_t size, 434 bool dynamic) = 0; 435 436 // overridden by API-specific derivated class to perform the clear and 437 // clearRect. NULL rect means clear whole target. 438 virtual void onClear(const GrIRect* rect, GrColor color) = 0; 439 440 // overridden by API-specific derived class to perform the draw call. 441 virtual void onGpuDrawIndexed(GrPrimitiveType type, 442 uint32_t startVertex, 443 uint32_t startIndex, 444 uint32_t vertexCount, 445 uint32_t indexCount) = 0; 446 447 virtual void onGpuDrawNonIndexed(GrPrimitiveType type, 448 uint32_t vertexCount, 449 uint32_t numVertices) = 0; 450 451 // overridden by API-specific derived class to perform flush 452 virtual void onForceRenderTargetFlush() = 0; 453 454 // overridden by API-specific derived class to perform the read pixels. 455 virtual bool onReadPixels(GrRenderTarget* target, 456 int left, int top, int width, int height, 457 GrPixelConfig, 458 void* buffer, 459 size_t rowBytes, 460 bool invertY) = 0; 461 462 // overridden by API-specific derived class to perform the texture update 463 virtual void onWriteTexturePixels(GrTexture* texture, 464 int left, int top, int width, int height, 465 GrPixelConfig config, const void* buffer, 466 size_t rowBytes) = 0; 467 468 // overridden by API-specific derived class to perform the resolve 469 virtual void onResolveRenderTarget(GrRenderTarget* target) = 0; 470 471 // called to program the vertex data, indexCount will be 0 if drawing non- 472 // indexed geometry. The subclass may adjust the startVertex and/or 473 // startIndex since it may have already accounted for these in the setup. 474 virtual void setupGeometry(int* startVertex, 475 int* startIndex, 476 int vertexCount, 477 int indexCount) = 0; 478 479 // width and height may be larger than rt (if underlying API allows it). 480 // Should attach the SB to the RT. Returns false if compatible sb could 481 // not be created. 482 virtual bool createStencilBufferForRenderTarget(GrRenderTarget* rt, 483 int width, 484 int height) = 0; 485 486 // attaches an existing SB to an existing RT. 487 virtual bool attachStencilBufferToRenderTarget(GrStencilBuffer* sb, 488 GrRenderTarget* rt) = 0; 489 490 // The GrGpu typically records the clients requested state and then flushes 491 // deltas from previous state at draw time. This function does the 492 // API-specific flush of the state 493 // returns false if current state is unsupported. 494 virtual bool flushGraphicsState(GrPrimitiveType type) = 0; 495 496 // clears the entire stencil buffer to 0 497 virtual void clearStencil() = 0; 498 499private: 500 GrContext* fContext; // not reffed (context refs gpu) 501 502 ResetTimestamp fResetTimestamp; 503 504 GrVertexBufferAllocPool* fVertexPool; 505 506 GrIndexBufferAllocPool* fIndexPool; 507 508 // counts number of uses of vertex/index pool in the geometry stack 509 int fVertexPoolUseCnt; 510 int fIndexPoolUseCnt; 511 512 enum { 513 kPreallocGeomPoolStateStackCnt = 4, 514 }; 515 SkSTArray<kPreallocGeomPoolStateStackCnt, 516 GeometryPoolState, true> fGeomPoolStateStack; 517 518 mutable GrIndexBuffer* fQuadIndexBuffer; // mutable so it can be 519 // created on-demand 520 521 mutable GrVertexBuffer* fUnitSquareVertexBuffer; // mutable so it can be 522 // created on-demand 523 524 bool fContextIsDirty; 525 526 GrResource* fResourceHead; 527 528 // Given a rt, find or create a stencil buffer and attach it 529 bool attachStencilBufferToRenderTarget(GrRenderTarget* target); 530 531 // GrDrawTarget overrides 532 virtual void onDrawIndexed(GrPrimitiveType type, 533 int startVertex, 534 int startIndex, 535 int vertexCount, 536 int indexCount); 537 virtual void onDrawNonIndexed(GrPrimitiveType type, 538 int startVertex, 539 int vertexCount); 540 541 // readies the pools to provide vertex/index data. 542 void prepareVertexPool(); 543 void prepareIndexPool(); 544 545 void resetContext() { 546 this->onResetContext(); 547 ++fResetTimestamp; 548 } 549 550 void handleDirtyContext() { 551 if (fContextIsDirty) { 552 this->resetContext(); 553 fContextIsDirty = false; 554 } 555 } 556 557 typedef GrDrawTarget INHERITED; 558}; 559 560#endif 561