Sat, 03 Jan 2015 20:18:00 +0100
Conditionally enable double key logic according to:
private browsing mode or privacy.thirdparty.isolate preference and
implement in GetCookieStringCommon and FindCookie where it counts...
With some reservations of how to convince FindCookie users to test
condition and pass a nullptr when disabling double key logic.
2 /*
3 * Copyright 2012 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 */
9 #include "GrClipMaskManager.h"
10 #include "GrAAConvexPathRenderer.h"
11 #include "GrAAHairLinePathRenderer.h"
12 #include "GrAARectRenderer.h"
13 #include "GrDrawTargetCaps.h"
14 #include "GrGpu.h"
15 #include "GrPaint.h"
16 #include "GrPathRenderer.h"
17 #include "GrRenderTarget.h"
18 #include "GrStencilBuffer.h"
19 #include "GrSWMaskHelper.h"
20 #include "effects/GrTextureDomain.h"
21 #include "effects/GrConvexPolyEffect.h"
22 #include "effects/GrRRectEffect.h"
23 #include "SkRasterClip.h"
24 #include "SkStrokeRec.h"
25 #include "SkTLazy.h"
27 #define GR_AA_CLIP 1
29 typedef SkClipStack::Element Element;
31 using namespace GrReducedClip;
33 ////////////////////////////////////////////////////////////////////////////////
34 namespace {
35 // set up the draw state to enable the aa clipping mask. Besides setting up the
36 // stage matrix this also alters the vertex layout
37 void setup_drawstate_aaclip(GrGpu* gpu,
38 GrTexture* result,
39 const SkIRect &devBound) {
40 GrDrawState* drawState = gpu->drawState();
41 SkASSERT(drawState);
43 SkMatrix mat;
44 // We want to use device coords to compute the texture coordinates. We set our matrix to be
45 // equal to the view matrix followed by an offset to the devBound, and then a scaling matrix to
46 // normalized coords. We apply this matrix to the vertex positions rather than local coords.
47 mat.setIDiv(result->width(), result->height());
48 mat.preTranslate(SkIntToScalar(-devBound.fLeft),
49 SkIntToScalar(-devBound.fTop));
50 mat.preConcat(drawState->getViewMatrix());
52 SkIRect domainTexels = SkIRect::MakeWH(devBound.width(), devBound.height());
53 // This could be a long-lived effect that is cached with the alpha-mask.
54 drawState->addCoverageEffect(
55 GrTextureDomainEffect::Create(result,
56 mat,
57 GrTextureDomain::MakeTexelDomain(result, domainTexels),
58 GrTextureDomain::kDecal_Mode,
59 GrTextureParams::kNone_FilterMode,
60 kPosition_GrCoordSet))->unref();
61 }
63 bool path_needs_SW_renderer(GrContext* context,
64 GrGpu* gpu,
65 const SkPath& origPath,
66 const SkStrokeRec& stroke,
67 bool doAA) {
68 // the gpu alpha mask will draw the inverse paths as non-inverse to a temp buffer
69 SkTCopyOnFirstWrite<SkPath> path(origPath);
70 if (path->isInverseFillType()) {
71 path.writable()->toggleInverseFillType();
72 }
73 // last (false) parameter disallows use of the SW path renderer
74 GrPathRendererChain::DrawType type = doAA ?
75 GrPathRendererChain::kColorAntiAlias_DrawType :
76 GrPathRendererChain::kColor_DrawType;
78 return NULL == context->getPathRenderer(*path, stroke, gpu, false, type);
79 }
81 }
83 /*
84 * This method traverses the clip stack to see if the GrSoftwarePathRenderer
85 * will be used on any element. If so, it returns true to indicate that the
86 * entire clip should be rendered in SW and then uploaded en masse to the gpu.
87 */
88 bool GrClipMaskManager::useSWOnlyPath(const ElementList& elements) {
90 // TODO: generalize this function so that when
91 // a clip gets complex enough it can just be done in SW regardless
92 // of whether it would invoke the GrSoftwarePathRenderer.
93 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
95 for (ElementList::Iter iter(elements.headIter()); iter.get(); iter.next()) {
96 const Element* element = iter.get();
97 // rects can always be drawn directly w/o using the software path
98 // Skip rrects once we're drawing them directly.
99 if (Element::kRect_Type != element->getType()) {
100 SkPath path;
101 element->asPath(&path);
102 if (path_needs_SW_renderer(this->getContext(), fGpu, path, stroke, element->isAA())) {
103 return true;
104 }
105 }
106 }
107 return false;
108 }
110 bool GrClipMaskManager::installClipEffects(const ElementList& elements,
111 GrDrawState::AutoRestoreEffects* are,
112 const SkVector& clipToRTOffset,
113 const SkRect* drawBounds) {
115 GrDrawState* drawState = fGpu->drawState();
116 SkRect boundsInClipSpace;
117 if (NULL != drawBounds) {
118 boundsInClipSpace = *drawBounds;
119 boundsInClipSpace.offset(-clipToRTOffset.fX, -clipToRTOffset.fY);
120 }
122 are->set(drawState);
123 GrRenderTarget* rt = drawState->getRenderTarget();
124 ElementList::Iter iter(elements);
126 bool setARE = false;
127 bool failed = false;
129 while (NULL != iter.get()) {
130 SkRegion::Op op = iter.get()->getOp();
131 bool invert;
132 bool skip = false;
133 switch (op) {
134 case SkRegion::kReplace_Op:
135 SkASSERT(iter.get() == elements.head());
136 // Fallthrough, handled same as intersect.
137 case SkRegion::kIntersect_Op:
138 invert = false;
139 if (NULL != drawBounds && iter.get()->contains(boundsInClipSpace)) {
140 skip = true;
141 }
142 break;
143 case SkRegion::kDifference_Op:
144 invert = true;
145 // We don't currently have a cheap test for whether a rect is fully outside an
146 // element's primitive, so don't attempt to set skip.
147 break;
148 default:
149 failed = true;
150 break;
151 }
152 if (failed) {
153 break;
154 }
156 if (!skip) {
157 GrEffectEdgeType edgeType;
158 if (GR_AA_CLIP && iter.get()->isAA()) {
159 if (rt->isMultisampled()) {
160 // Coverage based AA clips don't place nicely with MSAA.
161 failed = true;
162 break;
163 }
164 edgeType = invert ? kInverseFillAA_GrEffectEdgeType : kFillAA_GrEffectEdgeType;
165 } else {
166 edgeType = invert ? kInverseFillBW_GrEffectEdgeType : kFillBW_GrEffectEdgeType;
167 }
168 SkAutoTUnref<GrEffectRef> effect;
169 switch (iter.get()->getType()) {
170 case SkClipStack::Element::kPath_Type:
171 effect.reset(GrConvexPolyEffect::Create(edgeType, iter.get()->getPath(),
172 &clipToRTOffset));
173 break;
174 case SkClipStack::Element::kRRect_Type: {
175 SkRRect rrect = iter.get()->getRRect();
176 rrect.offset(clipToRTOffset.fX, clipToRTOffset.fY);
177 effect.reset(GrRRectEffect::Create(edgeType, rrect));
178 break;
179 }
180 case SkClipStack::Element::kRect_Type: {
181 SkRect rect = iter.get()->getRect();
182 rect.offset(clipToRTOffset.fX, clipToRTOffset.fY);
183 effect.reset(GrConvexPolyEffect::Create(edgeType, rect));
184 break;
185 }
186 default:
187 break;
188 }
189 if (effect) {
190 if (!setARE) {
191 are->set(fGpu->drawState());
192 setARE = true;
193 }
194 fGpu->drawState()->addCoverageEffect(effect);
195 } else {
196 failed = true;
197 break;
198 }
199 }
200 iter.next();
201 }
203 if (failed) {
204 are->set(NULL);
205 }
207 return !failed;
208 }
210 ////////////////////////////////////////////////////////////////////////////////
211 // sort out what kind of clip mask needs to be created: alpha, stencil,
212 // scissor, or entirely software
213 bool GrClipMaskManager::setupClipping(const GrClipData* clipDataIn,
214 GrDrawState::AutoRestoreEffects* are,
215 const SkRect* devBounds) {
216 fCurrClipMaskType = kNone_ClipMaskType;
218 ElementList elements(16);
219 int32_t genID;
220 InitialState initialState;
221 SkIRect clipSpaceIBounds;
222 bool requiresAA;
223 bool isRect = false;
225 GrDrawState* drawState = fGpu->drawState();
227 const GrRenderTarget* rt = drawState->getRenderTarget();
228 // GrDrawTarget should have filtered this for us
229 SkASSERT(NULL != rt);
231 bool ignoreClip = !drawState->isClipState() || clipDataIn->fClipStack->isWideOpen();
233 if (!ignoreClip) {
234 SkIRect clipSpaceRTIBounds = SkIRect::MakeWH(rt->width(), rt->height());
235 clipSpaceRTIBounds.offset(clipDataIn->fOrigin);
236 ReduceClipStack(*clipDataIn->fClipStack,
237 clipSpaceRTIBounds,
238 &elements,
239 &genID,
240 &initialState,
241 &clipSpaceIBounds,
242 &requiresAA);
243 if (elements.isEmpty()) {
244 if (kAllIn_InitialState == initialState) {
245 ignoreClip = clipSpaceIBounds == clipSpaceRTIBounds;
246 isRect = true;
247 } else {
248 return false;
249 }
250 }
251 }
253 if (ignoreClip) {
254 fGpu->disableScissor();
255 this->setGpuStencil();
256 return true;
257 }
259 // An element count of 4 was chosen because of the common pattern in Blink of:
260 // isect RR
261 // diff RR
262 // isect convex_poly
263 // isect convex_poly
264 // when drawing rounded div borders. This could probably be tuned based on a
265 // configuration's relative costs of switching RTs to generate a mask vs
266 // longer shaders.
267 if (elements.count() <= 4) {
268 SkVector clipToRTOffset = { SkIntToScalar(-clipDataIn->fOrigin.fX),
269 SkIntToScalar(-clipDataIn->fOrigin.fY) };
270 if (elements.isEmpty() ||
271 this->installClipEffects(elements, are, clipToRTOffset, devBounds)) {
272 SkIRect scissorSpaceIBounds(clipSpaceIBounds);
273 scissorSpaceIBounds.offset(-clipDataIn->fOrigin);
274 if (NULL == devBounds ||
275 !SkRect::Make(scissorSpaceIBounds).contains(*devBounds)) {
276 fGpu->enableScissor(scissorSpaceIBounds);
277 } else {
278 fGpu->disableScissor();
279 }
280 this->setGpuStencil();
281 return true;
282 }
283 }
285 #if GR_AA_CLIP
286 // If MSAA is enabled we can do everything in the stencil buffer.
287 if (0 == rt->numSamples() && requiresAA) {
288 GrTexture* result = NULL;
290 if (this->useSWOnlyPath(elements)) {
291 // The clip geometry is complex enough that it will be more efficient to create it
292 // entirely in software
293 result = this->createSoftwareClipMask(genID,
294 initialState,
295 elements,
296 clipSpaceIBounds);
297 } else {
298 result = this->createAlphaClipMask(genID,
299 initialState,
300 elements,
301 clipSpaceIBounds);
302 }
304 if (NULL != result) {
305 // The mask's top left coord should be pinned to the rounded-out top left corner of
306 // clipSpace bounds. We determine the mask's position WRT to the render target here.
307 SkIRect rtSpaceMaskBounds = clipSpaceIBounds;
308 rtSpaceMaskBounds.offset(-clipDataIn->fOrigin);
309 are->set(fGpu->drawState());
310 setup_drawstate_aaclip(fGpu, result, rtSpaceMaskBounds);
311 fGpu->disableScissor();
312 this->setGpuStencil();
313 return true;
314 }
315 // if alpha clip mask creation fails fall through to the non-AA code paths
316 }
317 #endif // GR_AA_CLIP
319 // Either a hard (stencil buffer) clip was explicitly requested or an anti-aliased clip couldn't
320 // be created. In either case, free up the texture in the anti-aliased mask cache.
321 // TODO: this may require more investigation. Ganesh performs a lot of utility draws (e.g.,
322 // clears, InOrderDrawBuffer playbacks) that hit the stencil buffer path. These may be
323 // "incorrectly" clearing the AA cache.
324 fAACache.reset();
326 // If the clip is a rectangle then just set the scissor. Otherwise, create
327 // a stencil mask.
328 if (isRect) {
329 SkIRect clipRect = clipSpaceIBounds;
330 clipRect.offset(-clipDataIn->fOrigin);
331 fGpu->enableScissor(clipRect);
332 this->setGpuStencil();
333 return true;
334 }
336 // use the stencil clip if we can't represent the clip as a rectangle.
337 SkIPoint clipSpaceToStencilSpaceOffset = -clipDataIn->fOrigin;
338 this->createStencilClipMask(genID,
339 initialState,
340 elements,
341 clipSpaceIBounds,
342 clipSpaceToStencilSpaceOffset);
344 // This must occur after createStencilClipMask. That function may change the scissor. Also, it
345 // only guarantees that the stencil mask is correct within the bounds it was passed, so we must
346 // use both stencil and scissor test to the bounds for the final draw.
347 SkIRect scissorSpaceIBounds(clipSpaceIBounds);
348 scissorSpaceIBounds.offset(clipSpaceToStencilSpaceOffset);
349 fGpu->enableScissor(scissorSpaceIBounds);
350 this->setGpuStencil();
351 return true;
352 }
354 #define VISUALIZE_COMPLEX_CLIP 0
356 #if VISUALIZE_COMPLEX_CLIP
357 #include "SkRandom.h"
358 SkRandom gRandom;
359 #define SET_RANDOM_COLOR drawState->setColor(0xff000000 | gRandom.nextU());
360 #else
361 #define SET_RANDOM_COLOR
362 #endif
364 namespace {
366 ////////////////////////////////////////////////////////////////////////////////
367 // set up the OpenGL blend function to perform the specified
368 // boolean operation for alpha clip mask creation
369 void setup_boolean_blendcoeffs(GrDrawState* drawState, SkRegion::Op op) {
371 switch (op) {
372 case SkRegion::kReplace_Op:
373 drawState->setBlendFunc(kOne_GrBlendCoeff, kZero_GrBlendCoeff);
374 break;
375 case SkRegion::kIntersect_Op:
376 drawState->setBlendFunc(kDC_GrBlendCoeff, kZero_GrBlendCoeff);
377 break;
378 case SkRegion::kUnion_Op:
379 drawState->setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
380 break;
381 case SkRegion::kXOR_Op:
382 drawState->setBlendFunc(kIDC_GrBlendCoeff, kISC_GrBlendCoeff);
383 break;
384 case SkRegion::kDifference_Op:
385 drawState->setBlendFunc(kZero_GrBlendCoeff, kISC_GrBlendCoeff);
386 break;
387 case SkRegion::kReverseDifference_Op:
388 drawState->setBlendFunc(kIDC_GrBlendCoeff, kZero_GrBlendCoeff);
389 break;
390 default:
391 SkASSERT(false);
392 break;
393 }
394 }
396 }
398 ////////////////////////////////////////////////////////////////////////////////
399 bool GrClipMaskManager::drawElement(GrTexture* target,
400 const SkClipStack::Element* element,
401 GrPathRenderer* pr) {
402 GrDrawState* drawState = fGpu->drawState();
404 drawState->setRenderTarget(target->asRenderTarget());
406 // TODO: Draw rrects directly here.
407 switch (element->getType()) {
408 case Element::kEmpty_Type:
409 SkDEBUGFAIL("Should never get here with an empty element.");
410 break;
411 case Element::kRect_Type:
412 // TODO: Do rects directly to the accumulator using a aa-rect GrEffect that covers the
413 // entire mask bounds and writes 0 outside the rect.
414 if (element->isAA()) {
415 getContext()->getAARectRenderer()->fillAARect(fGpu,
416 fGpu,
417 element->getRect(),
418 SkMatrix::I(),
419 element->getRect(),
420 false);
421 } else {
422 fGpu->drawSimpleRect(element->getRect(), NULL);
423 }
424 return true;
425 default: {
426 SkPath path;
427 element->asPath(&path);
428 if (path.isInverseFillType()) {
429 path.toggleInverseFillType();
430 }
431 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
432 if (NULL == pr) {
433 GrPathRendererChain::DrawType type;
434 type = element->isAA() ? GrPathRendererChain::kColorAntiAlias_DrawType :
435 GrPathRendererChain::kColor_DrawType;
436 pr = this->getContext()->getPathRenderer(path, stroke, fGpu, false, type);
437 }
438 if (NULL == pr) {
439 return false;
440 }
441 pr->drawPath(path, stroke, fGpu, element->isAA());
442 break;
443 }
444 }
445 return true;
446 }
448 bool GrClipMaskManager::canStencilAndDrawElement(GrTexture* target,
449 const SkClipStack::Element* element,
450 GrPathRenderer** pr) {
451 GrDrawState* drawState = fGpu->drawState();
452 drawState->setRenderTarget(target->asRenderTarget());
454 if (Element::kRect_Type == element->getType()) {
455 return true;
456 } else {
457 // We shouldn't get here with an empty clip element.
458 SkASSERT(Element::kEmpty_Type != element->getType());
459 SkPath path;
460 element->asPath(&path);
461 if (path.isInverseFillType()) {
462 path.toggleInverseFillType();
463 }
464 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
465 GrPathRendererChain::DrawType type = element->isAA() ?
466 GrPathRendererChain::kStencilAndColorAntiAlias_DrawType :
467 GrPathRendererChain::kStencilAndColor_DrawType;
468 *pr = this->getContext()->getPathRenderer(path, stroke, fGpu, false, type);
469 return NULL != *pr;
470 }
471 }
473 void GrClipMaskManager::mergeMask(GrTexture* dstMask,
474 GrTexture* srcMask,
475 SkRegion::Op op,
476 const SkIRect& dstBound,
477 const SkIRect& srcBound) {
478 GrDrawState::AutoViewMatrixRestore avmr;
479 GrDrawState* drawState = fGpu->drawState();
480 SkAssertResult(avmr.setIdentity(drawState));
481 GrDrawState::AutoRestoreEffects are(drawState);
483 drawState->setRenderTarget(dstMask->asRenderTarget());
485 setup_boolean_blendcoeffs(drawState, op);
487 SkMatrix sampleM;
488 sampleM.setIDiv(srcMask->width(), srcMask->height());
490 drawState->addColorEffect(
491 GrTextureDomainEffect::Create(srcMask,
492 sampleM,
493 GrTextureDomain::MakeTexelDomain(srcMask, srcBound),
494 GrTextureDomain::kDecal_Mode,
495 GrTextureParams::kNone_FilterMode))->unref();
496 fGpu->drawSimpleRect(SkRect::Make(dstBound), NULL);
497 }
499 // get a texture to act as a temporary buffer for AA clip boolean operations
500 // TODO: given the expense of createTexture we may want to just cache this too
501 void GrClipMaskManager::getTemp(int width, int height, GrAutoScratchTexture* temp) {
502 if (NULL != temp->texture()) {
503 // we've already allocated the temp texture
504 return;
505 }
507 GrTextureDesc desc;
508 desc.fFlags = kRenderTarget_GrTextureFlagBit|kNoStencil_GrTextureFlagBit;
509 desc.fWidth = width;
510 desc.fHeight = height;
511 desc.fConfig = kAlpha_8_GrPixelConfig;
513 temp->set(this->getContext(), desc);
514 }
516 ////////////////////////////////////////////////////////////////////////////////
517 // Handles caching & allocation (if needed) of a clip alpha-mask texture for both the sw-upload
518 // or gpu-rendered cases. Returns true if there is no more work to be done (i.e., we got a cache
519 // hit)
520 bool GrClipMaskManager::getMaskTexture(int32_t elementsGenID,
521 const SkIRect& clipSpaceIBounds,
522 GrTexture** result,
523 bool willUpload) {
524 bool cached = fAACache.canReuse(elementsGenID, clipSpaceIBounds);
525 if (!cached) {
527 // There isn't a suitable entry in the cache so we create a new texture to store the mask.
528 // Since we are setting up the cache we know the last lookup was a miss. Free up the
529 // currently cached mask so it can be reused.
530 fAACache.reset();
532 GrTextureDesc desc;
533 desc.fFlags = willUpload ? kNone_GrTextureFlags : kRenderTarget_GrTextureFlagBit;
534 desc.fWidth = clipSpaceIBounds.width();
535 desc.fHeight = clipSpaceIBounds.height();
536 desc.fConfig = kRGBA_8888_GrPixelConfig;
537 if (willUpload || this->getContext()->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
538 // We would always like A8 but it isn't supported on all platforms
539 desc.fConfig = kAlpha_8_GrPixelConfig;
540 }
542 fAACache.acquireMask(elementsGenID, desc, clipSpaceIBounds);
543 }
545 *result = fAACache.getLastMask();
546 return cached;
547 }
549 ////////////////////////////////////////////////////////////////////////////////
550 // Create a 8-bit clip mask in alpha
551 GrTexture* GrClipMaskManager::createAlphaClipMask(int32_t elementsGenID,
552 InitialState initialState,
553 const ElementList& elements,
554 const SkIRect& clipSpaceIBounds) {
555 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
557 GrTexture* result;
558 if (this->getMaskTexture(elementsGenID, clipSpaceIBounds, &result, false)) {
559 fCurrClipMaskType = kAlpha_ClipMaskType;
560 return result;
561 }
563 if (NULL == result) {
564 fAACache.reset();
565 return NULL;
566 }
568 // The top-left of the mask corresponds to the top-left corner of the bounds.
569 SkVector clipToMaskOffset = {
570 SkIntToScalar(-clipSpaceIBounds.fLeft),
571 SkIntToScalar(-clipSpaceIBounds.fTop)
572 };
573 // The texture may be larger than necessary, this rect represents the part of the texture
574 // we populate with a rasterization of the clip.
575 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
577 // Set the matrix so that rendered clip elements are transformed to mask space from clip space.
578 SkMatrix translate;
579 translate.setTranslate(clipToMaskOffset);
580 GrDrawTarget::AutoGeometryAndStatePush agasp(fGpu, GrDrawTarget::kReset_ASRInit, &translate);
582 GrDrawState* drawState = fGpu->drawState();
584 // We're drawing a coverage mask and want coverage to be run through the blend function.
585 drawState->enableState(GrDrawState::kCoverageDrawing_StateBit);
587 // The scratch texture that we are drawing into can be substantially larger than the mask. Only
588 // clear the part that we care about.
589 fGpu->clear(&maskSpaceIBounds,
590 kAllIn_InitialState == initialState ? 0xffffffff : 0x00000000,
591 true,
592 result->asRenderTarget());
594 // When we use the stencil in the below loop it is important to have this clip installed.
595 // The second pass that zeros the stencil buffer renders the rect maskSpaceIBounds so the first
596 // pass must not set values outside of this bounds or stencil values outside the rect won't be
597 // cleared.
598 GrDrawTarget::AutoClipRestore acr(fGpu, maskSpaceIBounds);
599 drawState->enableState(GrDrawState::kClip_StateBit);
601 GrAutoScratchTexture temp;
602 // walk through each clip element and perform its set op
603 for (ElementList::Iter iter = elements.headIter(); iter.get(); iter.next()) {
604 const Element* element = iter.get();
605 SkRegion::Op op = element->getOp();
606 bool invert = element->isInverseFilled();
608 if (invert || SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
609 GrPathRenderer* pr = NULL;
610 bool useTemp = !this->canStencilAndDrawElement(result, element, &pr);
611 GrTexture* dst;
612 // This is the bounds of the clip element in the space of the alpha-mask. The temporary
613 // mask buffer can be substantially larger than the actually clip stack element. We
614 // touch the minimum number of pixels necessary and use decal mode to combine it with
615 // the accumulator.
616 SkIRect maskSpaceElementIBounds;
618 if (useTemp) {
619 if (invert) {
620 maskSpaceElementIBounds = maskSpaceIBounds;
621 } else {
622 SkRect elementBounds = element->getBounds();
623 elementBounds.offset(clipToMaskOffset);
624 elementBounds.roundOut(&maskSpaceElementIBounds);
625 }
627 this->getTemp(maskSpaceIBounds.fRight, maskSpaceIBounds.fBottom, &temp);
628 if (NULL == temp.texture()) {
629 fAACache.reset();
630 return NULL;
631 }
632 dst = temp.texture();
633 // clear the temp target and set blend to replace
634 fGpu->clear(&maskSpaceElementIBounds,
635 invert ? 0xffffffff : 0x00000000,
636 true,
637 dst->asRenderTarget());
638 setup_boolean_blendcoeffs(drawState, SkRegion::kReplace_Op);
640 } else {
641 // draw directly into the result with the stencil set to make the pixels affected
642 // by the clip shape be non-zero.
643 dst = result;
644 GR_STATIC_CONST_SAME_STENCIL(kStencilInElement,
645 kReplace_StencilOp,
646 kReplace_StencilOp,
647 kAlways_StencilFunc,
648 0xffff,
649 0xffff,
650 0xffff);
651 drawState->setStencil(kStencilInElement);
652 setup_boolean_blendcoeffs(drawState, op);
653 }
655 drawState->setAlpha(invert ? 0x00 : 0xff);
657 if (!this->drawElement(dst, element, pr)) {
658 fAACache.reset();
659 return NULL;
660 }
662 if (useTemp) {
663 // Now draw into the accumulator using the real operation and the temp buffer as a
664 // texture
665 this->mergeMask(result,
666 temp.texture(),
667 op,
668 maskSpaceIBounds,
669 maskSpaceElementIBounds);
670 } else {
671 // Draw to the exterior pixels (those with a zero stencil value).
672 drawState->setAlpha(invert ? 0xff : 0x00);
673 GR_STATIC_CONST_SAME_STENCIL(kDrawOutsideElement,
674 kZero_StencilOp,
675 kZero_StencilOp,
676 kEqual_StencilFunc,
677 0xffff,
678 0x0000,
679 0xffff);
680 drawState->setStencil(kDrawOutsideElement);
681 fGpu->drawSimpleRect(clipSpaceIBounds);
682 drawState->disableStencil();
683 }
684 } else {
685 // all the remaining ops can just be directly draw into the accumulation buffer
686 drawState->setAlpha(0xff);
687 setup_boolean_blendcoeffs(drawState, op);
688 this->drawElement(result, element);
689 }
690 }
692 fCurrClipMaskType = kAlpha_ClipMaskType;
693 return result;
694 }
696 ////////////////////////////////////////////////////////////////////////////////
697 // Create a 1-bit clip mask in the stencil buffer. 'devClipBounds' are in device
698 // (as opposed to canvas) coordinates
699 bool GrClipMaskManager::createStencilClipMask(int32_t elementsGenID,
700 InitialState initialState,
701 const ElementList& elements,
702 const SkIRect& clipSpaceIBounds,
703 const SkIPoint& clipSpaceToStencilOffset) {
705 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
707 GrDrawState* drawState = fGpu->drawState();
708 SkASSERT(drawState->isClipState());
710 GrRenderTarget* rt = drawState->getRenderTarget();
711 SkASSERT(NULL != rt);
713 // TODO: dynamically attach a SB when needed.
714 GrStencilBuffer* stencilBuffer = rt->getStencilBuffer();
715 if (NULL == stencilBuffer) {
716 return false;
717 }
719 if (stencilBuffer->mustRenderClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset)) {
721 stencilBuffer->setLastClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset);
723 // Set the matrix so that rendered clip elements are transformed from clip to stencil space.
724 SkVector translate = {
725 SkIntToScalar(clipSpaceToStencilOffset.fX),
726 SkIntToScalar(clipSpaceToStencilOffset.fY)
727 };
728 SkMatrix matrix;
729 matrix.setTranslate(translate);
730 GrDrawTarget::AutoGeometryAndStatePush agasp(fGpu, GrDrawTarget::kReset_ASRInit, &matrix);
731 drawState = fGpu->drawState();
733 drawState->setRenderTarget(rt);
735 // We set the current clip to the bounds so that our recursive draws are scissored to them.
736 SkIRect stencilSpaceIBounds(clipSpaceIBounds);
737 stencilSpaceIBounds.offset(clipSpaceToStencilOffset);
738 GrDrawTarget::AutoClipRestore acr(fGpu, stencilSpaceIBounds);
739 drawState->enableState(GrDrawState::kClip_StateBit);
741 #if !VISUALIZE_COMPLEX_CLIP
742 drawState->enableState(GrDrawState::kNoColorWrites_StateBit);
743 #endif
745 int clipBit = stencilBuffer->bits();
746 SkASSERT((clipBit <= 16) && "Ganesh only handles 16b or smaller stencil buffers");
747 clipBit = (1 << (clipBit-1));
749 fGpu->clearStencilClip(stencilSpaceIBounds, kAllIn_InitialState == initialState);
751 // walk through each clip element and perform its set op
752 // with the existing clip.
753 for (ElementList::Iter iter(elements.headIter()); NULL != iter.get(); iter.next()) {
754 const Element* element = iter.get();
755 bool fillInverted = false;
756 // enabled at bottom of loop
757 drawState->disableState(GrGpu::kModifyStencilClip_StateBit);
758 // if the target is MSAA then we want MSAA enabled when the clip is soft
759 if (rt->isMultisampled()) {
760 drawState->setState(GrDrawState::kHWAntialias_StateBit, element->isAA());
761 }
763 // This will be used to determine whether the clip shape can be rendered into the
764 // stencil with arbitrary stencil settings.
765 GrPathRenderer::StencilSupport stencilSupport;
767 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
769 SkRegion::Op op = element->getOp();
771 GrPathRenderer* pr = NULL;
772 SkPath clipPath;
773 if (Element::kRect_Type == element->getType()) {
774 stencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
775 fillInverted = false;
776 } else {
777 element->asPath(&clipPath);
778 fillInverted = clipPath.isInverseFillType();
779 if (fillInverted) {
780 clipPath.toggleInverseFillType();
781 }
782 pr = this->getContext()->getPathRenderer(clipPath,
783 stroke,
784 fGpu,
785 false,
786 GrPathRendererChain::kStencilOnly_DrawType,
787 &stencilSupport);
788 if (NULL == pr) {
789 return false;
790 }
791 }
793 int passes;
794 GrStencilSettings stencilSettings[GrStencilSettings::kMaxStencilClipPasses];
796 bool canRenderDirectToStencil =
797 GrPathRenderer::kNoRestriction_StencilSupport == stencilSupport;
798 bool canDrawDirectToClip; // Given the renderer, the element,
799 // fill rule, and set operation can
800 // we render the element directly to
801 // stencil bit used for clipping.
802 canDrawDirectToClip = GrStencilSettings::GetClipPasses(op,
803 canRenderDirectToStencil,
804 clipBit,
805 fillInverted,
806 &passes,
807 stencilSettings);
809 // draw the element to the client stencil bits if necessary
810 if (!canDrawDirectToClip) {
811 GR_STATIC_CONST_SAME_STENCIL(gDrawToStencil,
812 kIncClamp_StencilOp,
813 kIncClamp_StencilOp,
814 kAlways_StencilFunc,
815 0xffff,
816 0x0000,
817 0xffff);
818 SET_RANDOM_COLOR
819 if (Element::kRect_Type == element->getType()) {
820 *drawState->stencil() = gDrawToStencil;
821 fGpu->drawSimpleRect(element->getRect(), NULL);
822 } else {
823 if (!clipPath.isEmpty()) {
824 if (canRenderDirectToStencil) {
825 *drawState->stencil() = gDrawToStencil;
826 pr->drawPath(clipPath, stroke, fGpu, false);
827 } else {
828 pr->stencilPath(clipPath, stroke, fGpu);
829 }
830 }
831 }
832 }
834 // now we modify the clip bit by rendering either the clip
835 // element directly or a bounding rect of the entire clip.
836 drawState->enableState(GrGpu::kModifyStencilClip_StateBit);
837 for (int p = 0; p < passes; ++p) {
838 *drawState->stencil() = stencilSettings[p];
839 if (canDrawDirectToClip) {
840 if (Element::kRect_Type == element->getType()) {
841 SET_RANDOM_COLOR
842 fGpu->drawSimpleRect(element->getRect(), NULL);
843 } else {
844 SET_RANDOM_COLOR
845 pr->drawPath(clipPath, stroke, fGpu, false);
846 }
847 } else {
848 SET_RANDOM_COLOR
849 // The view matrix is setup to do clip space -> stencil space translation, so
850 // draw rect in clip space.
851 fGpu->drawSimpleRect(SkRect::Make(clipSpaceIBounds), NULL);
852 }
853 }
854 }
855 }
856 // set this last because recursive draws may overwrite it back to kNone.
857 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
858 fCurrClipMaskType = kStencil_ClipMaskType;
859 return true;
860 }
863 // mapping of clip-respecting stencil funcs to normal stencil funcs
864 // mapping depends on whether stencil-clipping is in effect.
865 static const GrStencilFunc
866 gSpecialToBasicStencilFunc[2][kClipStencilFuncCount] = {
867 {// Stencil-Clipping is DISABLED, we are effectively always inside the clip
868 // In the Clip Funcs
869 kAlways_StencilFunc, // kAlwaysIfInClip_StencilFunc
870 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
871 kLess_StencilFunc, // kLessIfInClip_StencilFunc
872 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
873 // Special in the clip func that forces user's ref to be 0.
874 kNotEqual_StencilFunc, // kNonZeroIfInClip_StencilFunc
875 // make ref 0 and do normal nequal.
876 },
877 {// Stencil-Clipping is ENABLED
878 // In the Clip Funcs
879 kEqual_StencilFunc, // kAlwaysIfInClip_StencilFunc
880 // eq stencil clip bit, mask
881 // out user bits.
883 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
884 // add stencil bit to mask and ref
886 kLess_StencilFunc, // kLessIfInClip_StencilFunc
887 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
888 // for both of these we can add
889 // the clip bit to the mask and
890 // ref and compare as normal
891 // Special in the clip func that forces user's ref to be 0.
892 kLess_StencilFunc, // kNonZeroIfInClip_StencilFunc
893 // make ref have only the clip bit set
894 // and make comparison be less
895 // 10..0 < 1..user_bits..
896 }
897 };
899 namespace {
900 // Sets the settings to clip against the stencil buffer clip while ignoring the
901 // client bits.
902 const GrStencilSettings& basic_apply_stencil_clip_settings() {
903 // stencil settings to use when clip is in stencil
904 GR_STATIC_CONST_SAME_STENCIL_STRUCT(gSettings,
905 kKeep_StencilOp,
906 kKeep_StencilOp,
907 kAlwaysIfInClip_StencilFunc,
908 0x0000,
909 0x0000,
910 0x0000);
911 return *GR_CONST_STENCIL_SETTINGS_PTR_FROM_STRUCT_PTR(&gSettings);
912 }
913 }
915 void GrClipMaskManager::setGpuStencil() {
916 // We make two copies of the StencilSettings here (except in the early
917 // exit scenario. One copy from draw state to the stack var. Then another
918 // from the stack var to the gpu. We could make this class hold a ptr to
919 // GrGpu's fStencilSettings and eliminate the stack copy here.
921 const GrDrawState& drawState = fGpu->getDrawState();
923 // use stencil for clipping if clipping is enabled and the clip
924 // has been written into the stencil.
925 GrClipMaskManager::StencilClipMode clipMode;
926 if (this->isClipInStencil() && drawState.isClipState()) {
927 clipMode = GrClipMaskManager::kRespectClip_StencilClipMode;
928 // We can't be modifying the clip and respecting it at the same time.
929 SkASSERT(!drawState.isStateFlagEnabled(
930 GrGpu::kModifyStencilClip_StateBit));
931 } else if (drawState.isStateFlagEnabled(
932 GrGpu::kModifyStencilClip_StateBit)) {
933 clipMode = GrClipMaskManager::kModifyClip_StencilClipMode;
934 } else {
935 clipMode = GrClipMaskManager::kIgnoreClip_StencilClipMode;
936 }
938 GrStencilSettings settings;
939 // The GrGpu client may not be using the stencil buffer but we may need to
940 // enable it in order to respect a stencil clip.
941 if (drawState.getStencil().isDisabled()) {
942 if (GrClipMaskManager::kRespectClip_StencilClipMode == clipMode) {
943 settings = basic_apply_stencil_clip_settings();
944 } else {
945 fGpu->disableStencil();
946 return;
947 }
948 } else {
949 settings = drawState.getStencil();
950 }
952 // TODO: dynamically attach a stencil buffer
953 int stencilBits = 0;
954 GrStencilBuffer* stencilBuffer =
955 drawState.getRenderTarget()->getStencilBuffer();
956 if (NULL != stencilBuffer) {
957 stencilBits = stencilBuffer->bits();
958 }
960 SkASSERT(fGpu->caps()->stencilWrapOpsSupport() || !settings.usesWrapOp());
961 SkASSERT(fGpu->caps()->twoSidedStencilSupport() || !settings.isTwoSided());
962 this->adjustStencilParams(&settings, clipMode, stencilBits);
963 fGpu->setStencilSettings(settings);
964 }
966 void GrClipMaskManager::adjustStencilParams(GrStencilSettings* settings,
967 StencilClipMode mode,
968 int stencilBitCnt) {
969 SkASSERT(stencilBitCnt > 0);
971 if (kModifyClip_StencilClipMode == mode) {
972 // We assume that this clip manager itself is drawing to the GrGpu and
973 // has already setup the correct values.
974 return;
975 }
977 unsigned int clipBit = (1 << (stencilBitCnt - 1));
978 unsigned int userBits = clipBit - 1;
980 GrStencilSettings::Face face = GrStencilSettings::kFront_Face;
981 bool twoSided = fGpu->caps()->twoSidedStencilSupport();
983 bool finished = false;
984 while (!finished) {
985 GrStencilFunc func = settings->func(face);
986 uint16_t writeMask = settings->writeMask(face);
987 uint16_t funcMask = settings->funcMask(face);
988 uint16_t funcRef = settings->funcRef(face);
990 SkASSERT((unsigned) func < kStencilFuncCount);
992 writeMask &= userBits;
994 if (func >= kBasicStencilFuncCount) {
995 int respectClip = kRespectClip_StencilClipMode == mode;
996 if (respectClip) {
997 // The GrGpu class should have checked this
998 SkASSERT(this->isClipInStencil());
999 switch (func) {
1000 case kAlwaysIfInClip_StencilFunc:
1001 funcMask = clipBit;
1002 funcRef = clipBit;
1003 break;
1004 case kEqualIfInClip_StencilFunc:
1005 case kLessIfInClip_StencilFunc:
1006 case kLEqualIfInClip_StencilFunc:
1007 funcMask = (funcMask & userBits) | clipBit;
1008 funcRef = (funcRef & userBits) | clipBit;
1009 break;
1010 case kNonZeroIfInClip_StencilFunc:
1011 funcMask = (funcMask & userBits) | clipBit;
1012 funcRef = clipBit;
1013 break;
1014 default:
1015 GrCrash("Unknown stencil func");
1016 }
1017 } else {
1018 funcMask &= userBits;
1019 funcRef &= userBits;
1020 }
1021 const GrStencilFunc* table =
1022 gSpecialToBasicStencilFunc[respectClip];
1023 func = table[func - kBasicStencilFuncCount];
1024 SkASSERT(func >= 0 && func < kBasicStencilFuncCount);
1025 } else {
1026 funcMask &= userBits;
1027 funcRef &= userBits;
1028 }
1030 settings->setFunc(face, func);
1031 settings->setWriteMask(face, writeMask);
1032 settings->setFuncMask(face, funcMask);
1033 settings->setFuncRef(face, funcRef);
1035 if (GrStencilSettings::kFront_Face == face) {
1036 face = GrStencilSettings::kBack_Face;
1037 finished = !twoSided;
1038 } else {
1039 finished = true;
1040 }
1041 }
1042 if (!twoSided) {
1043 settings->copyFrontSettingsToBack();
1044 }
1045 }
1047 ////////////////////////////////////////////////////////////////////////////////
1048 GrTexture* GrClipMaskManager::createSoftwareClipMask(int32_t elementsGenID,
1049 GrReducedClip::InitialState initialState,
1050 const GrReducedClip::ElementList& elements,
1051 const SkIRect& clipSpaceIBounds) {
1052 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
1054 GrTexture* result;
1055 if (this->getMaskTexture(elementsGenID, clipSpaceIBounds, &result, true)) {
1056 return result;
1057 }
1059 if (NULL == result) {
1060 fAACache.reset();
1061 return NULL;
1062 }
1064 // The mask texture may be larger than necessary. We round out the clip space bounds and pin
1065 // the top left corner of the resulting rect to the top left of the texture.
1066 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
1068 GrSWMaskHelper helper(this->getContext());
1070 SkMatrix matrix;
1071 matrix.setTranslate(SkIntToScalar(-clipSpaceIBounds.fLeft),
1072 SkIntToScalar(-clipSpaceIBounds.fTop));
1073 helper.init(maskSpaceIBounds, &matrix);
1075 helper.clear(kAllIn_InitialState == initialState ? 0xFF : 0x00);
1077 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
1079 for (ElementList::Iter iter(elements.headIter()) ; NULL != iter.get(); iter.next()) {
1081 const Element* element = iter.get();
1082 SkRegion::Op op = element->getOp();
1084 if (SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
1085 // Intersect and reverse difference require modifying pixels outside of the geometry
1086 // that is being "drawn". In both cases we erase all the pixels outside of the geometry
1087 // but leave the pixels inside the geometry alone. For reverse difference we invert all
1088 // the pixels before clearing the ones outside the geometry.
1089 if (SkRegion::kReverseDifference_Op == op) {
1090 SkRect temp = SkRect::Make(clipSpaceIBounds);
1091 // invert the entire scene
1092 helper.draw(temp, SkRegion::kXOR_Op, false, 0xFF);
1093 }
1095 SkPath clipPath;
1096 element->asPath(&clipPath);
1097 clipPath.toggleInverseFillType();
1098 helper.draw(clipPath, stroke, SkRegion::kReplace_Op, element->isAA(), 0x00);
1100 continue;
1101 }
1103 // The other ops (union, xor, diff) only affect pixels inside
1104 // the geometry so they can just be drawn normally
1105 if (Element::kRect_Type == element->getType()) {
1106 helper.draw(element->getRect(), op, element->isAA(), 0xFF);
1107 } else {
1108 SkPath path;
1109 element->asPath(&path);
1110 helper.draw(path, stroke, op, element->isAA(), 0xFF);
1111 }
1112 }
1114 helper.toTexture(result);
1116 fCurrClipMaskType = kAlpha_ClipMaskType;
1117 return result;
1118 }
1120 ////////////////////////////////////////////////////////////////////////////////
1121 void GrClipMaskManager::releaseResources() {
1122 fAACache.releaseResources();
1123 }
1125 void GrClipMaskManager::setGpu(GrGpu* gpu) {
1126 fGpu = gpu;
1127 fAACache.setContext(gpu->getContext());
1128 }
1130 void GrClipMaskManager::adjustPathStencilParams(GrStencilSettings* settings) {
1131 const GrDrawState& drawState = fGpu->getDrawState();
1132 GrClipMaskManager::StencilClipMode clipMode;
1133 if (this->isClipInStencil() && drawState.isClipState()) {
1134 clipMode = GrClipMaskManager::kRespectClip_StencilClipMode;
1135 // We can't be modifying the clip and respecting it at the same time.
1136 SkASSERT(!drawState.isStateFlagEnabled(
1137 GrGpu::kModifyStencilClip_StateBit));
1138 } else if (drawState.isStateFlagEnabled(
1139 GrGpu::kModifyStencilClip_StateBit)) {
1140 clipMode = GrClipMaskManager::kModifyClip_StencilClipMode;
1141 } else {
1142 clipMode = GrClipMaskManager::kIgnoreClip_StencilClipMode;
1143 }
1145 // TODO: dynamically attach a stencil buffer
1146 int stencilBits = 0;
1147 GrStencilBuffer* stencilBuffer =
1148 drawState.getRenderTarget()->getStencilBuffer();
1149 if (NULL != stencilBuffer) {
1150 stencilBits = stencilBuffer->bits();
1151 this->adjustStencilParams(settings, clipMode, stencilBits);
1152 }
1153 }