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