blob: 675965447c073979104615cfafaadc226477bdb1 [file] [log] [blame]
bsalomon@google.com27847de2011-02-22 20:59:41 +00001/*
2 Copyright 2010 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17#ifndef GrContext_DEFINED
18#define GrContext_DEFINED
19
20#include "GrClip.h"
21#include "GrGpu.h"
22#include "GrTextureCache.h"
23#include "GrPaint.h"
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +000024#include "GrPathRenderer.h"
bsalomon@google.com27847de2011-02-22 20:59:41 +000025
26class GrFontCache;
27class GrPathIter;
28class GrVertexBufferAllocPool;
29class GrIndexBufferAllocPool;
30class GrInOrderDrawBuffer;
bsalomon@google.com27847de2011-02-22 20:59:41 +000031
bsalomon@google.com91826102011-03-21 19:51:57 +000032class GR_API GrContext : public GrRefCnt {
bsalomon@google.com27847de2011-02-22 20:59:41 +000033public:
34 /**
35 * Creates a GrContext from within a 3D context.
36 */
37 static GrContext* Create(GrGpu::Engine engine,
38 GrGpu::Platform3DContext context3D);
39
40 /**
41 * Helper to create a opengl-shader based context
42 */
43 static GrContext* CreateGLShaderContext();
44
45 virtual ~GrContext();
46
47 /**
48 * The GrContext normally assumes that no outsider is setting state
49 * within the underlying 3D API's context/device/whatever. This call informs
50 * the context that the state was modified and it should resend. Shouldn't
51 * be called frequently for good performance.
52 */
53 void resetContext();
54
bsalomon@google.com8fe72472011-03-30 21:26:44 +000055 /**
56 * Abandons all gpu resources, assumes 3D API state is unknown. Call this
57 * if you have lost the associated GPU context, and thus internal texture,
58 * buffer, etc. references/IDs are now invalid. Should be called even when
59 * GrContext is no longer going to be used for two reasons:
60 * 1) ~GrContext will not try to free the objects in the 3D API.
61 * 2) If you've created GrResources that outlive the GrContext they will
62 * be marked as invalid (GrResource::isValid()) and won't attempt to
63 * free their underlying resource in the 3D API.
64 * Content drawn since the last GrContext::flush() may be lost.
65 */
66 void contextLost();
bsalomon@google.com27847de2011-02-22 20:59:41 +000067
68 /**
bsalomon@google.com8fe72472011-03-30 21:26:44 +000069 * Frees gpu created by the context. Can be called to reduce GPU memory
70 * pressure.
bsalomon@google.com27847de2011-02-22 20:59:41 +000071 */
bsalomon@google.com8fe72472011-03-30 21:26:44 +000072 void freeGpuResources();
73
74 ///////////////////////////////////////////////////////////////////////////
75 // Textures
bsalomon@google.com27847de2011-02-22 20:59:41 +000076
77 /**
78 * Search for an entry with the same Key. If found, "lock" it and return it.
79 * If not found, return null.
80 */
81 GrTextureEntry* findAndLockTexture(GrTextureKey*,
82 const GrSamplerState&);
83
84
85 /**
86 * Create a new entry, based on the specified key and texture, and return
87 * its "locked" entry.
88 *
89 * Ownership of the texture is transferred to the Entry, which will unref()
90 * it when we are purged or deleted.
91 */
92 GrTextureEntry* createAndLockTexture(GrTextureKey* key,
93 const GrSamplerState&,
94 const GrGpu::TextureDesc&,
95 void* srcData, size_t rowBytes);
96
97 /**
98 * When done with an entry, call unlockTexture(entry) on it, which returns
99 * it to the cache, where it may be purged.
100 */
101 void unlockTexture(GrTextureEntry* entry);
102
103 /**
104 * Removes an texture from the cache. This prevents the texture from
105 * being found by a subsequent findAndLockTexture() until it is
106 * reattached. The entry still counts against the cache's budget and should
107 * be reattached when exclusive access is no longer needed.
108 */
109 void detachCachedTexture(GrTextureEntry*);
110
111 /**
112 * Reattaches a texture to the cache and unlocks it. Allows it to be found
113 * by a subsequent findAndLock or be purged (provided its lock count is
114 * now 0.)
115 */
116 void reattachAndUnlockCachedTexture(GrTextureEntry*);
117
118 /**
119 * Creates a texture that is outside the cache. Does not count against
120 * cache's budget.
121 */
122 GrTexture* createUncachedTexture(const GrGpu::TextureDesc&,
123 void* srcData,
124 size_t rowBytes);
125
126 /**
127 * Returns true if the specified use of an indexed texture is supported.
128 */
129 bool supportsIndex8PixelConfig(const GrSamplerState&, int width, int height);
130
131 /**
132 * Return the current texture cache limits.
133 *
134 * @param maxTextures If non-null, returns maximum number of textures that
135 * can be held in the cache.
136 * @param maxTextureBytes If non-null, returns maximum number of bytes of
137 * texture memory that can be held in the cache.
138 */
139 void getTextureCacheLimits(int* maxTextures, size_t* maxTextureBytes) const;
140
141 /**
142 * Specify the texture 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 maxTextures The maximum number of textures that can be held in
146 * the cache.
147 * @param maxTextureBytes The maximum number of bytes of texture memory
148 * that can be held in the cache.
149 */
150 void setTextureCacheLimits(int maxTextures, size_t maxTextureBytes);
151
152 /**
153 * Return the max width or height of a texture supported by the current gpu
154 */
155 int getMaxTextureDimension();
156
157 ///////////////////////////////////////////////////////////////////////////
158 // Render targets
159
160 /**
161 * Wraps an externally-created rendertarget in a GrRenderTarget.
162 * @param platformRenderTarget 3D API-specific render target identifier
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000163 * e.g. in GL platforamRenderTarget is an FBO
bsalomon@google.com27847de2011-02-22 20:59:41 +0000164 * id.
165 * @param stencilBits the number of stencil bits that the render
166 * target has.
bsalomon@google.comf954d8d2011-04-06 17:50:02 +0000167 * @param isMultisampled specify whether the render target is
168 * multisampled.
bsalomon@google.com27847de2011-02-22 20:59:41 +0000169 * @param width width of the render target.
170 * @param height height of the render target.
171 */
172 GrRenderTarget* createPlatformRenderTarget(intptr_t platformRenderTarget,
173 int stencilBits,
bsalomon@google.comf954d8d2011-04-06 17:50:02 +0000174 bool isMultisampled,
bsalomon@google.com27847de2011-02-22 20:59:41 +0000175 int width, int height);
176
177 /**
178 * Reads the current target object (e.g. FBO or IDirect3DSurface9*) and
179 * viewport state from the underlying 3D API and wraps it in a
180 * GrRenderTarget. The GrRenderTarget will not attempt to delete/destroy the
181 * underlying object in its destructor and it is up to caller to guarantee
182 * that it remains valid while the GrRenderTarget is used.
183 *
184 * @return the newly created GrRenderTarget
185 */
186 GrRenderTarget* createRenderTargetFrom3DApiState() {
187 return fGpu->createRenderTargetFrom3DApiState();
188 }
189
190 /**
191 * Sets the render target.
192 * @param target the render target to set. (should not be NULL.)
193 */
194 void setRenderTarget(GrRenderTarget* target);
195
196 /**
197 * Gets the current render target.
198 * @return the currently bound render target. Should never be NULL.
199 */
200 const GrRenderTarget* getRenderTarget() const;
201 GrRenderTarget* getRenderTarget();
202
203 ///////////////////////////////////////////////////////////////////////////
204 // Matrix state
205
206 /**
207 * Gets the current transformation matrix.
208 * @return the current matrix.
209 */
210 const GrMatrix& getMatrix() const;
211
212 /**
213 * Sets the transformation matrix.
214 * @param m the matrix to set.
215 */
216 void setMatrix(const GrMatrix& m);
217
218 /**
219 * Concats the current matrix. The passed matrix is applied before the
220 * current matrix.
221 * @param m the matrix to concat.
222 */
223 void concatMatrix(const GrMatrix& m) const;
224
225
226 ///////////////////////////////////////////////////////////////////////////
227 // Clip state
228 /**
229 * Gets the current clip.
230 * @return the current clip.
231 */
232 const GrClip& getClip() const { return fGpu->getClip(); }
233
234 /**
235 * Sets the clip.
236 * @param clip the clip to set.
237 */
238 void setClip(const GrClip& clip);
239
240 /**
241 * Convenience method for setting the clip to a rect.
242 * @param rect the rect to set as the new clip.
243 */
244 void setClip(const GrIRect& rect);
245
246 ///////////////////////////////////////////////////////////////////////////
247 // Draws
248
249 /**
250 * Erase the entire render target, ignoring any clips
251 */
252 void eraseColor(GrColor color);
253
254 /**
255 * Draw everywhere (respecting the clip) with the paint.
256 */
257 void drawPaint(const GrPaint& paint);
258
259 /**
260 * Draw the rect using a paint.
261 * @param paint describes how to color pixels.
262 * @param strokeWidth If strokeWidth < 0, then the rect is filled, else
263 * the rect is mitered stroked based on strokeWidth. If
264 * strokeWidth == 0, then the stroke is always a single
265 * pixel thick.
266 * @param matrix Optional matrix applied to the rect. Applied before
267 * context's matrix or the paint's matrix.
268 * The rects coords are used to access the paint (through texture matrix)
269 */
270 void drawRect(const GrPaint& paint,
271 const GrRect&,
272 GrScalar strokeWidth = -1,
273 const GrMatrix* matrix = NULL);
274
275 /**
276 * Maps a rect of paint coordinates onto the a rect of destination
277 * coordinates. Each rect can optionally be transformed. The srcRect
278 * is stretched over the dstRect. The dstRect is transformed by the
279 * context's matrix and the srcRect is transformed by the paint's matrix.
280 * Additional optional matrices can be provided by parameters.
281 *
282 * @param paint describes how to color pixels.
283 * @param dstRect the destination rect to draw.
284 * @param srcRect rect of paint coordinates to be mapped onto dstRect
285 * @param dstMatrix Optional matrix to transform dstRect. Applied before
286 * context's matrix.
287 * @param srcMatrix Optional matrix to transform srcRect Applied before
288 * paint's matrix.
289 */
290 void drawRectToRect(const GrPaint& paint,
291 const GrRect& dstRect,
292 const GrRect& srcRect,
293 const GrMatrix* dstMatrix = NULL,
294 const GrMatrix* srcMatrix = NULL);
295
296 /**
bsalomon@google.comd302f142011-03-03 13:54:13 +0000297 * Draws a path.
bsalomon@google.com27847de2011-02-22 20:59:41 +0000298 *
299 * @param paint describes how to color pixels.
bsalomon@google.comd302f142011-03-03 13:54:13 +0000300 * @param pathIter the path to draw
bsalomon@google.com27847de2011-02-22 20:59:41 +0000301 * @param fill the path filling rule to use.
302 * @param translate optional additional translation applied to the
303 * path.
304 */
305 void drawPath(const GrPaint& paint,
bsalomon@google.comd302f142011-03-03 13:54:13 +0000306 GrPathIter* pathIter,
307 GrPathFill fill,
308 const GrPoint* translate = NULL);
309 /**
310 * Helper version of drawPath that takes a GrPath
311 */
312 void drawPath(const GrPaint& paint,
313 const GrPath& path,
bsalomon@google.com27847de2011-02-22 20:59:41 +0000314 GrPathFill fill,
315 const GrPoint* translate = NULL);
316 /**
317 * Draws vertices with a paint.
318 *
319 * @param paint describes how to color pixels.
320 * @param primitiveType primitives type to draw.
321 * @param vertexCount number of vertices.
322 * @param positions array of vertex positions, required.
323 * @param texCoords optional array of texture coordinates used
324 * to access the paint.
325 * @param colors optional array of per-vertex colors, supercedes
326 * the paint's color field.
327 * @param indices optional array of indices. If NULL vertices
328 * are drawn non-indexed.
329 * @param indexCount if indices is non-null then this is the
330 * number of indices.
331 */
332 void drawVertices(const GrPaint& paint,
333 GrPrimitiveType primitiveType,
334 int vertexCount,
335 const GrPoint positions[],
336 const GrPoint texs[],
337 const GrColor colors[],
338 const uint16_t indices[],
339 int indexCount);
340
341 /**
342 * Similar to drawVertices but caller provides objects that convert to Gr
343 * types. The count of vertices is given by posSrc.
344 *
345 * @param paint describes how to color pixels.
346 * @param primitiveType primitives type to draw.
347 * @param posSrc Source of vertex positions. Must implement
348 * int count() const;
349 * void writeValue(int i, GrPoint* point) const;
350 * count returns the total number of vertices and
351 * writeValue writes a vertex position to point.
352 * @param texSrc optional, pass NULL to not use explicit tex
353 * coords. If present provides tex coords with
354 * method:
355 * void writeValue(int i, GrPoint* point) const;
356 * @param texSrc optional, pass NULL to not use per-vertex colors
357 * If present provides colors with method:
358 * void writeValue(int i, GrColor* point) const;
359 * @param indices optional, pass NULL for non-indexed drawing. If
360 * present supplies indices for indexed drawing
361 * with following methods:
362 * int count() const;
363 * void writeValue(int i, uint16_t* point) const;
364 * count returns the number of indices and
365 * writeValue supplies each index.
366 */
367 template <typename POS_SRC,
368 typename TEX_SRC,
369 typename COL_SRC,
370 typename IDX_SRC>
371 void drawCustomVertices(const GrPaint& paint,
372 GrPrimitiveType primitiveType,
373 const POS_SRC& posSrc,
374 const TEX_SRC* texCoordSrc,
375 const COL_SRC* colorSrc,
376 const IDX_SRC* idxSrc);
377 /**
378 * To avoid the problem of having to create a typename for NULL parameters,
379 * these reduced versions of drawCustomVertices are provided.
380 */
381 template <typename POS_SRC>
382 void drawCustomVertices(const GrPaint& paint,
383 GrPrimitiveType primitiveType,
384 const POS_SRC& posSrc);
385 template <typename POS_SRC, typename TEX_SRC>
386 void drawCustomVertices(const GrPaint& paint,
387 GrPrimitiveType primitiveType,
388 const POS_SRC& posSrc,
389 const TEX_SRC* texCoordSrc);
390 template <typename POS_SRC, typename TEX_SRC, typename COL_SRC>
391 void drawCustomVertices(const GrPaint& paint,
392 GrPrimitiveType primitiveType,
393 const POS_SRC& posSrc,
394 const TEX_SRC* texCoordSrc,
395 const COL_SRC* colorSrc);
396
397
398 ///////////////////////////////////////////////////////////////////////////
399 // Misc.
400
401 /**
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000402 * Flags that affect flush() behavior.
403 */
404 enum FlushBits {
405 /**
406 * A client may want Gr to bind a GrRenderTarget in the 3D API so that
407 * it can be rendered to directly. However, Gr lazily sets state. Simply
408 * calling setRenderTarget() followed by flush() without flags may not
409 * bind the render target. This flag forces the context to bind the last
410 * set render target in the 3D API.
411 */
412 kForceCurrentRenderTarget_FlushBit = 0x1,
413 /**
414 * A client may reach a point where it has partially rendered a frame
415 * through a GrContext that it knows the user will never see. This flag
416 * causes the flush to skip submission of deferred content to the 3D API
417 * during the flush.
418 */
419 kDiscard_FlushBit = 0x2,
420 };
421
422 /**
bsalomon@google.com27847de2011-02-22 20:59:41 +0000423 * Call to ensure all drawing to the context has been issued to the
424 * underlying 3D API.
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000425 * @param flagsBitfield flags that control the flushing behavior. See
426 * FlushBits.
bsalomon@google.com27847de2011-02-22 20:59:41 +0000427 */
bsalomon@google.com8fe72472011-03-30 21:26:44 +0000428 void flush(int flagsBitfield = 0);
bsalomon@google.com669fdc42011-04-05 17:08:27 +0000429
bsalomon@google.com27847de2011-02-22 20:59:41 +0000430 /**
bsalomon@google.com669fdc42011-04-05 17:08:27 +0000431 * Reads a rectangle of pixels from a render target.
432 * @param renderTarget the render target to read from. NULL means the
433 * current render target.
434 * @param left left edge of the rectangle to read (inclusive)
435 * @param top top edge of the rectangle to read (inclusive)
436 * @param width width of rectangle to read in pixels.
437 * @param height height of rectangle to read in pixels.
438 * @param config the pixel config of the destination buffer
439 * @param buffer memory to read the rectangle into.
440 *
441 * @return true if the read succeeded, false if not. The read can fail
442 * because of a unsupported pixel config or because no render
443 * target is currently set.
bsalomon@google.com27847de2011-02-22 20:59:41 +0000444 */
bsalomon@google.com669fdc42011-04-05 17:08:27 +0000445 bool readRenderTargetPixels(GrRenderTarget* target,
446 int left, int top, int width, int height,
447 GrPixelConfig config, void* buffer);
448
449 /**
450 * Reads a rectangle of pixels from a texture.
451 * @param texture the render target to read from.
452 * @param left left edge of the rectangle to read (inclusive)
453 * @param top top edge of the rectangle to read (inclusive)
454 * @param width width of rectangle to read in pixels.
455 * @param height height of rectangle to read in pixels.
456 * @param config the pixel config of the destination buffer
457 * @param buffer memory to read the rectangle into.
458 *
459 * @return true if the read succeeded, false if not. The read can fail
460 * because of a unsupported pixel config.
461 */
462 bool readTexturePixels(GrTexture* target,
463 int left, int top, int width, int height,
464 GrPixelConfig config, void* buffer);
bsalomon@google.com27847de2011-02-22 20:59:41 +0000465
466 /**
467 * Copy the src pixels [buffer, stride, pixelconfig] into the current
468 * render-target at the specified rectangle.
469 */
470 void writePixels(int left, int top, int width, int height,
bsalomon@google.com669fdc42011-04-05 17:08:27 +0000471 GrPixelConfig, const void* buffer, size_t stride);
bsalomon@google.com27847de2011-02-22 20:59:41 +0000472
473
474 ///////////////////////////////////////////////////////////////////////////
475 // Statistics
476
477 void resetStats();
478
479 const GrGpu::Stats& getStats() const;
480
481 void printStats() const;
482
483 ///////////////////////////////////////////////////////////////////////////
484 // Helpers
485
486 class AutoRenderTarget : ::GrNoncopyable {
487 public:
488 AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
489 fContext = NULL;
490 fPrevTarget = context->getRenderTarget();
491 if (fPrevTarget != target) {
492 context->setRenderTarget(target);
493 fContext = context;
494 }
495 }
496 ~AutoRenderTarget() {
497 if (fContext) {
498 fContext->setRenderTarget(fPrevTarget);
499 }
500 }
501 private:
502 GrContext* fContext;
503 GrRenderTarget* fPrevTarget;
504 };
505
506
507 ///////////////////////////////////////////////////////////////////////////
508 // Functions intended for internal use only.
509 GrGpu* getGpu() { return fGpu; }
510 GrFontCache* getFontCache() { return fFontCache; }
511 GrDrawTarget* getTextTarget(const GrPaint& paint);
512 void flushText();
513 const GrIndexBuffer* getQuadIndexBuffer() const;
514
515private:
516 // used to keep track of when we need to flush the draw buffer
517 enum DrawCategory {
518 kBuffered_DrawCategory, // last draw was inserted in draw buffer
519 kUnbuffered_DrawCategory, // last draw was not inserted in the draw buffer
520 kText_DrawCategory // text context was last to draw
521 };
522 DrawCategory fLastDrawCategory;
523
524 GrGpu* fGpu;
525 GrTextureCache* fTextureCache;
526 GrFontCache* fFontCache;
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +0000527
528 GrPathRenderer* fCustomPathRenderer;
529 GrDefaultPathRenderer fDefaultPathRenderer;
bsalomon@google.com27847de2011-02-22 20:59:41 +0000530
531 GrVertexBufferAllocPool* fDrawBufferVBAllocPool;
532 GrIndexBufferAllocPool* fDrawBufferIBAllocPool;
533 GrInOrderDrawBuffer* fDrawBuffer;
534
535 GrContext(GrGpu* gpu);
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +0000536
bsalomon@google.com8fe72472011-03-30 21:26:44 +0000537 void setupDrawBuffer();
538
bsalomon@google.com27847de2011-02-22 20:59:41 +0000539 void flushDrawBuffer();
540
541 static void SetPaint(const GrPaint& paint, GrDrawTarget* target);
542
543 bool finalizeTextureKey(GrTextureKey*, const GrSamplerState&) const;
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000544
bsalomon@google.com27847de2011-02-22 20:59:41 +0000545 GrDrawTarget* prepareToDraw(const GrPaint& paint, DrawCategory drawType);
546
547 void drawClipIntoStencil();
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +0000548
549 GrPathRenderer* getPathRenderer(const GrDrawTarget* target,
550 GrPathIter* path,
551 GrPathFill fill);
552
bsalomon@google.com27847de2011-02-22 20:59:41 +0000553};
554
555/**
556 * Save/restore the view-matrix in the context.
557 */
558class GrAutoMatrix : GrNoncopyable {
559public:
560 GrAutoMatrix(GrContext* ctx) : fContext(ctx) {
561 fMatrix = ctx->getMatrix();
562 }
563 GrAutoMatrix(GrContext* ctx, const GrMatrix& matrix) : fContext(ctx) {
564 fMatrix = ctx->getMatrix();
565 ctx->setMatrix(matrix);
566 }
567 ~GrAutoMatrix() {
568 fContext->setMatrix(fMatrix);
569 }
570
571private:
572 GrContext* fContext;
573 GrMatrix fMatrix;
574};
575
576#endif
577
578#include "GrContext_impl.h"