3 * Copyright 2012 Google Inc.
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
9 #include "GrClipMaskManager.h"
10 #include "GrAAConvexPathRenderer.h"
11 #include "GrAAHairLinePathRenderer.h"
12 #include "GrAARectRenderer.h"
13 #include "GrDrawTargetCaps.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"
29 typedef SkClipStack::Element Element;
31 using namespace GrReducedClip;
33 ////////////////////////////////////////////////////////////////////////////////
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,
39 const SkIRect &devBound) {
40 GrDrawState* drawState = gpu->drawState();
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,
57 GrTextureDomain::MakeTexelDomain(result, domainTexels),
58 GrTextureDomain::kDecal_Mode,
59 GrTextureParams::kNone_FilterMode,
60 kPosition_GrCoordSet))->unref();
63 bool path_needs_SW_renderer(GrContext* context,
65 const SkPath& origPath,
66 const SkStrokeRec& stroke,
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();
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);
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.
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()) {
101 element->asPath(&path);
102 if (path_needs_SW_renderer(this->getContext(), fGpu, path, stroke, element->isAA())) {
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);
123 GrRenderTarget* rt = drawState->getRenderTarget();
124 ElementList::Iter iter(elements);
129 while (NULL != iter.get()) {
130 SkRegion::Op op = iter.get()->getOp();
134 case SkRegion::kReplace_Op:
135 SkASSERT(iter.get() == elements.head());
136 // Fallthrough, handled same as intersect.
137 case SkRegion::kIntersect_Op:
139 if (NULL != drawBounds && iter.get()->contains(boundsInClipSpace)) {
143 case SkRegion::kDifference_Op:
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.
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.
164 edgeType = invert ? kInverseFillAA_GrEffectEdgeType : kFillAA_GrEffectEdgeType;
166 edgeType = invert ? kInverseFillBW_GrEffectEdgeType : kFillBW_GrEffectEdgeType;
168 SkAutoTUnref<GrEffectRef> effect;
169 switch (iter.get()->getType()) {
170 case SkClipStack::Element::kPath_Type:
171 effect.reset(GrConvexPolyEffect::Create(edgeType, iter.get()->getPath(),
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));
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));
191 are->set(fGpu->drawState());
194 fGpu->drawState()->addCoverageEffect(effect);
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);
220 InitialState initialState;
221 SkIRect clipSpaceIBounds;
224 GrDrawState* drawState = fGpu->drawState();
226 const GrRenderTarget* rt = drawState->getRenderTarget();
227 // GrDrawTarget should have filtered this for us
228 SkASSERT(NULL != rt);
230 bool ignoreClip = !drawState->isClipState() || clipDataIn->fClipStack->isWideOpen();
233 SkIRect clipSpaceRTIBounds = SkIRect::MakeWH(rt->width(), rt->height());
234 clipSpaceRTIBounds.offset(clipDataIn->fOrigin);
235 ReduceClipStack(*clipDataIn->fClipStack,
242 if (elements.isEmpty()) {
243 if (kAllIn_InitialState == initialState) {
244 ignoreClip = clipSpaceIBounds == clipSpaceRTIBounds;
252 fGpu->disableScissor();
253 this->setGpuStencil();
257 // An element count of 4 was chosen because of the common pattern in Blink of:
262 // when drawing rounded div borders. This could probably be tuned based on a
263 // configuration's relative costs of switching RTs to generate a mask vs
265 if (elements.count() <= 4) {
266 SkVector clipToRTOffset = { SkIntToScalar(-clipDataIn->fOrigin.fX),
267 SkIntToScalar(-clipDataIn->fOrigin.fY) };
268 if (elements.isEmpty() ||
269 (requiresAA && this->installClipEffects(elements, are, clipToRTOffset, devBounds))) {
270 SkIRect scissorSpaceIBounds(clipSpaceIBounds);
271 scissorSpaceIBounds.offset(-clipDataIn->fOrigin);
272 if (NULL == devBounds ||
273 !SkRect::Make(scissorSpaceIBounds).contains(*devBounds)) {
274 fGpu->enableScissor(scissorSpaceIBounds);
276 fGpu->disableScissor();
278 this->setGpuStencil();
284 // If MSAA is enabled we can do everything in the stencil buffer.
285 if (0 == rt->numSamples() && requiresAA) {
286 GrTexture* result = NULL;
288 if (this->useSWOnlyPath(elements)) {
289 // The clip geometry is complex enough that it will be more efficient to create it
290 // entirely in software
291 result = this->createSoftwareClipMask(genID,
296 result = this->createAlphaClipMask(genID,
302 if (NULL != result) {
303 // The mask's top left coord should be pinned to the rounded-out top left corner of
304 // clipSpace bounds. We determine the mask's position WRT to the render target here.
305 SkIRect rtSpaceMaskBounds = clipSpaceIBounds;
306 rtSpaceMaskBounds.offset(-clipDataIn->fOrigin);
307 are->set(fGpu->drawState());
308 setup_drawstate_aaclip(fGpu, result, rtSpaceMaskBounds);
309 fGpu->disableScissor();
310 this->setGpuStencil();
313 // if alpha clip mask creation fails fall through to the non-AA code paths
317 // Either a hard (stencil buffer) clip was explicitly requested or an anti-aliased clip couldn't
318 // be created. In either case, free up the texture in the anti-aliased mask cache.
319 // TODO: this may require more investigation. Ganesh performs a lot of utility draws (e.g.,
320 // clears, InOrderDrawBuffer playbacks) that hit the stencil buffer path. These may be
321 // "incorrectly" clearing the AA cache.
324 // use the stencil clip if we can't represent the clip as a rectangle.
325 SkIPoint clipSpaceToStencilSpaceOffset = -clipDataIn->fOrigin;
326 this->createStencilClipMask(genID,
330 clipSpaceToStencilSpaceOffset);
332 // This must occur after createStencilClipMask. That function may change the scissor. Also, it
333 // only guarantees that the stencil mask is correct within the bounds it was passed, so we must
334 // use both stencil and scissor test to the bounds for the final draw.
335 SkIRect scissorSpaceIBounds(clipSpaceIBounds);
336 scissorSpaceIBounds.offset(clipSpaceToStencilSpaceOffset);
337 fGpu->enableScissor(scissorSpaceIBounds);
338 this->setGpuStencil();
342 #define VISUALIZE_COMPLEX_CLIP 0
344 #if VISUALIZE_COMPLEX_CLIP
345 #include "SkRandom.h"
347 #define SET_RANDOM_COLOR drawState->setColor(0xff000000 | gRandom.nextU());
349 #define SET_RANDOM_COLOR
354 ////////////////////////////////////////////////////////////////////////////////
355 // set up the OpenGL blend function to perform the specified
356 // boolean operation for alpha clip mask creation
357 void setup_boolean_blendcoeffs(GrDrawState* drawState, SkRegion::Op op) {
360 case SkRegion::kReplace_Op:
361 drawState->setBlendFunc(kOne_GrBlendCoeff, kZero_GrBlendCoeff);
363 case SkRegion::kIntersect_Op:
364 drawState->setBlendFunc(kDC_GrBlendCoeff, kZero_GrBlendCoeff);
366 case SkRegion::kUnion_Op:
367 drawState->setBlendFunc(kOne_GrBlendCoeff, kISC_GrBlendCoeff);
369 case SkRegion::kXOR_Op:
370 drawState->setBlendFunc(kIDC_GrBlendCoeff, kISC_GrBlendCoeff);
372 case SkRegion::kDifference_Op:
373 drawState->setBlendFunc(kZero_GrBlendCoeff, kISC_GrBlendCoeff);
375 case SkRegion::kReverseDifference_Op:
376 drawState->setBlendFunc(kIDC_GrBlendCoeff, kZero_GrBlendCoeff);
386 ////////////////////////////////////////////////////////////////////////////////
387 bool GrClipMaskManager::drawElement(GrTexture* target,
388 const SkClipStack::Element* element,
389 GrPathRenderer* pr) {
390 GrDrawState* drawState = fGpu->drawState();
392 drawState->setRenderTarget(target->asRenderTarget());
394 // TODO: Draw rrects directly here.
395 switch (element->getType()) {
396 case Element::kEmpty_Type:
397 SkDEBUGFAIL("Should never get here with an empty element.");
399 case Element::kRect_Type:
400 // TODO: Do rects directly to the accumulator using a aa-rect GrEffect that covers the
401 // entire mask bounds and writes 0 outside the rect.
402 if (element->isAA()) {
403 getContext()->getAARectRenderer()->fillAARect(fGpu,
410 fGpu->drawSimpleRect(element->getRect(), NULL);
415 element->asPath(&path);
416 if (path.isInverseFillType()) {
417 path.toggleInverseFillType();
419 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
421 GrPathRendererChain::DrawType type;
422 type = element->isAA() ? GrPathRendererChain::kColorAntiAlias_DrawType :
423 GrPathRendererChain::kColor_DrawType;
424 pr = this->getContext()->getPathRenderer(path, stroke, fGpu, false, type);
429 pr->drawPath(path, stroke, fGpu, element->isAA());
436 bool GrClipMaskManager::canStencilAndDrawElement(GrTexture* target,
437 const SkClipStack::Element* element,
438 GrPathRenderer** pr) {
439 GrDrawState* drawState = fGpu->drawState();
440 drawState->setRenderTarget(target->asRenderTarget());
442 if (Element::kRect_Type == element->getType()) {
445 // We shouldn't get here with an empty clip element.
446 SkASSERT(Element::kEmpty_Type != element->getType());
448 element->asPath(&path);
449 if (path.isInverseFillType()) {
450 path.toggleInverseFillType();
452 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
453 GrPathRendererChain::DrawType type = element->isAA() ?
454 GrPathRendererChain::kStencilAndColorAntiAlias_DrawType :
455 GrPathRendererChain::kStencilAndColor_DrawType;
456 *pr = this->getContext()->getPathRenderer(path, stroke, fGpu, false, type);
461 void GrClipMaskManager::mergeMask(GrTexture* dstMask,
464 const SkIRect& dstBound,
465 const SkIRect& srcBound) {
466 GrDrawState::AutoViewMatrixRestore avmr;
467 GrDrawState* drawState = fGpu->drawState();
468 SkAssertResult(avmr.setIdentity(drawState));
469 GrDrawState::AutoRestoreEffects are(drawState);
471 drawState->setRenderTarget(dstMask->asRenderTarget());
473 setup_boolean_blendcoeffs(drawState, op);
476 sampleM.setIDiv(srcMask->width(), srcMask->height());
478 drawState->addColorEffect(
479 GrTextureDomainEffect::Create(srcMask,
481 GrTextureDomain::MakeTexelDomain(srcMask, srcBound),
482 GrTextureDomain::kDecal_Mode,
483 GrTextureParams::kNone_FilterMode))->unref();
484 fGpu->drawSimpleRect(SkRect::Make(dstBound), NULL);
487 // get a texture to act as a temporary buffer for AA clip boolean operations
488 // TODO: given the expense of createTexture we may want to just cache this too
489 void GrClipMaskManager::getTemp(int width, int height, GrAutoScratchTexture* temp) {
490 if (NULL != temp->texture()) {
491 // we've already allocated the temp texture
496 desc.fFlags = kRenderTarget_GrTextureFlagBit|kNoStencil_GrTextureFlagBit;
498 desc.fHeight = height;
499 desc.fConfig = kAlpha_8_GrPixelConfig;
501 temp->set(this->getContext(), desc);
504 ////////////////////////////////////////////////////////////////////////////////
505 // Return the texture currently in the cache if it exists. Otherwise, return NULL
506 GrTexture* GrClipMaskManager::getCachedMaskTexture(int32_t elementsGenID,
507 const SkIRect& clipSpaceIBounds) {
508 bool cached = fAACache.canReuse(elementsGenID, clipSpaceIBounds);
513 return fAACache.getLastMask();
516 ////////////////////////////////////////////////////////////////////////////////
517 // Allocate a texture in the texture cache. This function returns the texture
518 // allocated (or NULL on error).
519 GrTexture* GrClipMaskManager::allocMaskTexture(int32_t elementsGenID,
520 const SkIRect& clipSpaceIBounds,
522 // Since we are setting up the cache we should free up the
523 // currently cached mask so it can be reused.
527 desc.fFlags = willUpload ? kNone_GrTextureFlags : kRenderTarget_GrTextureFlagBit;
528 desc.fWidth = clipSpaceIBounds.width();
529 desc.fHeight = clipSpaceIBounds.height();
530 desc.fConfig = kRGBA_8888_GrPixelConfig;
531 if (willUpload || this->getContext()->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
532 // We would always like A8 but it isn't supported on all platforms
533 desc.fConfig = kAlpha_8_GrPixelConfig;
536 fAACache.acquireMask(elementsGenID, desc, clipSpaceIBounds);
537 return fAACache.getLastMask();
540 ////////////////////////////////////////////////////////////////////////////////
541 // Create a 8-bit clip mask in alpha
542 GrTexture* GrClipMaskManager::createAlphaClipMask(int32_t elementsGenID,
543 InitialState initialState,
544 const ElementList& elements,
545 const SkIRect& clipSpaceIBounds) {
546 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
548 // First, check for cached texture
549 GrTexture* result = this->getCachedMaskTexture(elementsGenID, clipSpaceIBounds);
550 if (NULL != result) {
551 fCurrClipMaskType = kAlpha_ClipMaskType;
555 // There's no texture in the cache. Let's try to allocate it then.
556 result = this->allocMaskTexture(elementsGenID, clipSpaceIBounds, false);
557 if (NULL == result) {
562 // The top-left of the mask corresponds to the top-left corner of the bounds.
563 SkVector clipToMaskOffset = {
564 SkIntToScalar(-clipSpaceIBounds.fLeft),
565 SkIntToScalar(-clipSpaceIBounds.fTop)
567 // The texture may be larger than necessary, this rect represents the part of the texture
568 // we populate with a rasterization of the clip.
569 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
571 // Set the matrix so that rendered clip elements are transformed to mask space from clip space.
573 translate.setTranslate(clipToMaskOffset);
574 GrDrawTarget::AutoGeometryAndStatePush agasp(fGpu, GrDrawTarget::kReset_ASRInit, &translate);
576 GrDrawState* drawState = fGpu->drawState();
578 // We're drawing a coverage mask and want coverage to be run through the blend function.
579 drawState->enableState(GrDrawState::kCoverageDrawing_StateBit);
581 // The scratch texture that we are drawing into can be substantially larger than the mask. Only
582 // clear the part that we care about.
583 fGpu->clear(&maskSpaceIBounds,
584 kAllIn_InitialState == initialState ? 0xffffffff : 0x00000000,
586 result->asRenderTarget());
588 // When we use the stencil in the below loop it is important to have this clip installed.
589 // The second pass that zeros the stencil buffer renders the rect maskSpaceIBounds so the first
590 // pass must not set values outside of this bounds or stencil values outside the rect won't be
592 GrDrawTarget::AutoClipRestore acr(fGpu, maskSpaceIBounds);
593 drawState->enableState(GrDrawState::kClip_StateBit);
595 GrAutoScratchTexture temp;
596 // walk through each clip element and perform its set op
597 for (ElementList::Iter iter = elements.headIter(); iter.get(); iter.next()) {
598 const Element* element = iter.get();
599 SkRegion::Op op = element->getOp();
600 bool invert = element->isInverseFilled();
602 if (invert || SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
603 GrPathRenderer* pr = NULL;
604 bool useTemp = !this->canStencilAndDrawElement(result, element, &pr);
606 // This is the bounds of the clip element in the space of the alpha-mask. The temporary
607 // mask buffer can be substantially larger than the actually clip stack element. We
608 // touch the minimum number of pixels necessary and use decal mode to combine it with
610 SkIRect maskSpaceElementIBounds;
614 maskSpaceElementIBounds = maskSpaceIBounds;
616 SkRect elementBounds = element->getBounds();
617 elementBounds.offset(clipToMaskOffset);
618 elementBounds.roundOut(&maskSpaceElementIBounds);
621 this->getTemp(maskSpaceIBounds.fRight, maskSpaceIBounds.fBottom, &temp);
622 if (NULL == temp.texture()) {
626 dst = temp.texture();
627 // clear the temp target and set blend to replace
628 fGpu->clear(&maskSpaceElementIBounds,
629 invert ? 0xffffffff : 0x00000000,
631 dst->asRenderTarget());
632 setup_boolean_blendcoeffs(drawState, SkRegion::kReplace_Op);
635 // draw directly into the result with the stencil set to make the pixels affected
636 // by the clip shape be non-zero.
638 GR_STATIC_CONST_SAME_STENCIL(kStencilInElement,
645 drawState->setStencil(kStencilInElement);
646 setup_boolean_blendcoeffs(drawState, op);
649 drawState->setAlpha(invert ? 0x00 : 0xff);
651 if (!this->drawElement(dst, element, pr)) {
657 // Now draw into the accumulator using the real operation and the temp buffer as a
659 this->mergeMask(result,
663 maskSpaceElementIBounds);
665 // Draw to the exterior pixels (those with a zero stencil value).
666 drawState->setAlpha(invert ? 0xff : 0x00);
667 GR_STATIC_CONST_SAME_STENCIL(kDrawOutsideElement,
674 drawState->setStencil(kDrawOutsideElement);
675 fGpu->drawSimpleRect(clipSpaceIBounds);
676 drawState->disableStencil();
679 // all the remaining ops can just be directly draw into the accumulation buffer
680 drawState->setAlpha(0xff);
681 setup_boolean_blendcoeffs(drawState, op);
682 this->drawElement(result, element);
686 fCurrClipMaskType = kAlpha_ClipMaskType;
690 ////////////////////////////////////////////////////////////////////////////////
691 // Create a 1-bit clip mask in the stencil buffer. 'devClipBounds' are in device
692 // (as opposed to canvas) coordinates
693 bool GrClipMaskManager::createStencilClipMask(int32_t elementsGenID,
694 InitialState initialState,
695 const ElementList& elements,
696 const SkIRect& clipSpaceIBounds,
697 const SkIPoint& clipSpaceToStencilOffset) {
699 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
701 GrDrawState* drawState = fGpu->drawState();
702 SkASSERT(drawState->isClipState());
704 GrRenderTarget* rt = drawState->getRenderTarget();
705 SkASSERT(NULL != rt);
707 // TODO: dynamically attach a SB when needed.
708 GrStencilBuffer* stencilBuffer = rt->getStencilBuffer();
709 if (NULL == stencilBuffer) {
713 if (stencilBuffer->mustRenderClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset)) {
715 stencilBuffer->setLastClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset);
717 // Set the matrix so that rendered clip elements are transformed from clip to stencil space.
718 SkVector translate = {
719 SkIntToScalar(clipSpaceToStencilOffset.fX),
720 SkIntToScalar(clipSpaceToStencilOffset.fY)
723 matrix.setTranslate(translate);
724 GrDrawTarget::AutoGeometryAndStatePush agasp(fGpu, GrDrawTarget::kReset_ASRInit, &matrix);
725 drawState = fGpu->drawState();
727 drawState->setRenderTarget(rt);
729 // We set the current clip to the bounds so that our recursive draws are scissored to them.
730 SkIRect stencilSpaceIBounds(clipSpaceIBounds);
731 stencilSpaceIBounds.offset(clipSpaceToStencilOffset);
732 GrDrawTarget::AutoClipRestore acr(fGpu, stencilSpaceIBounds);
733 drawState->enableState(GrDrawState::kClip_StateBit);
735 #if !VISUALIZE_COMPLEX_CLIP
736 drawState->enableState(GrDrawState::kNoColorWrites_StateBit);
739 int clipBit = stencilBuffer->bits();
740 SkASSERT((clipBit <= 16) && "Ganesh only handles 16b or smaller stencil buffers");
741 clipBit = (1 << (clipBit-1));
743 fGpu->clearStencilClip(stencilSpaceIBounds, kAllIn_InitialState == initialState);
745 // walk through each clip element and perform its set op
746 // with the existing clip.
747 for (ElementList::Iter iter(elements.headIter()); NULL != iter.get(); iter.next()) {
748 const Element* element = iter.get();
749 bool fillInverted = false;
750 // enabled at bottom of loop
751 drawState->disableState(GrGpu::kModifyStencilClip_StateBit);
752 // if the target is MSAA then we want MSAA enabled when the clip is soft
753 if (rt->isMultisampled()) {
754 drawState->setState(GrDrawState::kHWAntialias_StateBit, element->isAA());
757 // This will be used to determine whether the clip shape can be rendered into the
758 // stencil with arbitrary stencil settings.
759 GrPathRenderer::StencilSupport stencilSupport;
761 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
763 SkRegion::Op op = element->getOp();
765 GrPathRenderer* pr = NULL;
767 if (Element::kRect_Type == element->getType()) {
768 stencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
769 fillInverted = false;
771 element->asPath(&clipPath);
772 fillInverted = clipPath.isInverseFillType();
774 clipPath.toggleInverseFillType();
776 pr = this->getContext()->getPathRenderer(clipPath,
780 GrPathRendererChain::kStencilOnly_DrawType,
788 GrStencilSettings stencilSettings[GrStencilSettings::kMaxStencilClipPasses];
790 bool canRenderDirectToStencil =
791 GrPathRenderer::kNoRestriction_StencilSupport == stencilSupport;
792 bool canDrawDirectToClip; // Given the renderer, the element,
793 // fill rule, and set operation can
794 // we render the element directly to
795 // stencil bit used for clipping.
796 canDrawDirectToClip = GrStencilSettings::GetClipPasses(op,
797 canRenderDirectToStencil,
803 // draw the element to the client stencil bits if necessary
804 if (!canDrawDirectToClip) {
805 GR_STATIC_CONST_SAME_STENCIL(gDrawToStencil,
813 if (Element::kRect_Type == element->getType()) {
814 *drawState->stencil() = gDrawToStencil;
815 fGpu->drawSimpleRect(element->getRect(), NULL);
817 if (!clipPath.isEmpty()) {
818 if (canRenderDirectToStencil) {
819 *drawState->stencil() = gDrawToStencil;
820 pr->drawPath(clipPath, stroke, fGpu, false);
822 pr->stencilPath(clipPath, stroke, fGpu);
828 // now we modify the clip bit by rendering either the clip
829 // element directly or a bounding rect of the entire clip.
830 drawState->enableState(GrGpu::kModifyStencilClip_StateBit);
831 for (int p = 0; p < passes; ++p) {
832 *drawState->stencil() = stencilSettings[p];
833 if (canDrawDirectToClip) {
834 if (Element::kRect_Type == element->getType()) {
836 fGpu->drawSimpleRect(element->getRect(), NULL);
839 pr->drawPath(clipPath, stroke, fGpu, false);
843 // The view matrix is setup to do clip space -> stencil space translation, so
844 // draw rect in clip space.
845 fGpu->drawSimpleRect(SkRect::Make(clipSpaceIBounds), NULL);
850 // set this last because recursive draws may overwrite it back to kNone.
851 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
852 fCurrClipMaskType = kStencil_ClipMaskType;
857 // mapping of clip-respecting stencil funcs to normal stencil funcs
858 // mapping depends on whether stencil-clipping is in effect.
859 static const GrStencilFunc
860 gSpecialToBasicStencilFunc[2][kClipStencilFuncCount] = {
861 {// Stencil-Clipping is DISABLED, we are effectively always inside the clip
863 kAlways_StencilFunc, // kAlwaysIfInClip_StencilFunc
864 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
865 kLess_StencilFunc, // kLessIfInClip_StencilFunc
866 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
867 // Special in the clip func that forces user's ref to be 0.
868 kNotEqual_StencilFunc, // kNonZeroIfInClip_StencilFunc
869 // make ref 0 and do normal nequal.
871 {// Stencil-Clipping is ENABLED
873 kEqual_StencilFunc, // kAlwaysIfInClip_StencilFunc
874 // eq stencil clip bit, mask
877 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
878 // add stencil bit to mask and ref
880 kLess_StencilFunc, // kLessIfInClip_StencilFunc
881 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
882 // for both of these we can add
883 // the clip bit to the mask and
884 // ref and compare as normal
885 // Special in the clip func that forces user's ref to be 0.
886 kLess_StencilFunc, // kNonZeroIfInClip_StencilFunc
887 // make ref have only the clip bit set
888 // and make comparison be less
889 // 10..0 < 1..user_bits..
894 // Sets the settings to clip against the stencil buffer clip while ignoring the
896 const GrStencilSettings& basic_apply_stencil_clip_settings() {
897 // stencil settings to use when clip is in stencil
898 GR_STATIC_CONST_SAME_STENCIL_STRUCT(gSettings,
901 kAlwaysIfInClip_StencilFunc,
905 return *GR_CONST_STENCIL_SETTINGS_PTR_FROM_STRUCT_PTR(&gSettings);
909 void GrClipMaskManager::setGpuStencil() {
910 // We make two copies of the StencilSettings here (except in the early
911 // exit scenario. One copy from draw state to the stack var. Then another
912 // from the stack var to the gpu. We could make this class hold a ptr to
913 // GrGpu's fStencilSettings and eliminate the stack copy here.
915 const GrDrawState& drawState = fGpu->getDrawState();
917 // use stencil for clipping if clipping is enabled and the clip
918 // has been written into the stencil.
919 GrClipMaskManager::StencilClipMode clipMode;
920 if (this->isClipInStencil() && drawState.isClipState()) {
921 clipMode = GrClipMaskManager::kRespectClip_StencilClipMode;
922 // We can't be modifying the clip and respecting it at the same time.
923 SkASSERT(!drawState.isStateFlagEnabled(
924 GrGpu::kModifyStencilClip_StateBit));
925 } else if (drawState.isStateFlagEnabled(
926 GrGpu::kModifyStencilClip_StateBit)) {
927 clipMode = GrClipMaskManager::kModifyClip_StencilClipMode;
929 clipMode = GrClipMaskManager::kIgnoreClip_StencilClipMode;
932 GrStencilSettings settings;
933 // The GrGpu client may not be using the stencil buffer but we may need to
934 // enable it in order to respect a stencil clip.
935 if (drawState.getStencil().isDisabled()) {
936 if (GrClipMaskManager::kRespectClip_StencilClipMode == clipMode) {
937 settings = basic_apply_stencil_clip_settings();
939 fGpu->disableStencil();
943 settings = drawState.getStencil();
946 // TODO: dynamically attach a stencil buffer
948 GrStencilBuffer* stencilBuffer =
949 drawState.getRenderTarget()->getStencilBuffer();
950 if (NULL != stencilBuffer) {
951 stencilBits = stencilBuffer->bits();
954 SkASSERT(fGpu->caps()->stencilWrapOpsSupport() || !settings.usesWrapOp());
955 SkASSERT(fGpu->caps()->twoSidedStencilSupport() || !settings.isTwoSided());
956 this->adjustStencilParams(&settings, clipMode, stencilBits);
957 fGpu->setStencilSettings(settings);
960 void GrClipMaskManager::adjustStencilParams(GrStencilSettings* settings,
961 StencilClipMode mode,
963 SkASSERT(stencilBitCnt > 0);
965 if (kModifyClip_StencilClipMode == mode) {
966 // We assume that this clip manager itself is drawing to the GrGpu and
967 // has already setup the correct values.
971 unsigned int clipBit = (1 << (stencilBitCnt - 1));
972 unsigned int userBits = clipBit - 1;
974 GrStencilSettings::Face face = GrStencilSettings::kFront_Face;
975 bool twoSided = fGpu->caps()->twoSidedStencilSupport();
977 bool finished = false;
979 GrStencilFunc func = settings->func(face);
980 uint16_t writeMask = settings->writeMask(face);
981 uint16_t funcMask = settings->funcMask(face);
982 uint16_t funcRef = settings->funcRef(face);
984 SkASSERT((unsigned) func < kStencilFuncCount);
986 writeMask &= userBits;
988 if (func >= kBasicStencilFuncCount) {
989 int respectClip = kRespectClip_StencilClipMode == mode;
991 // The GrGpu class should have checked this
992 SkASSERT(this->isClipInStencil());
994 case kAlwaysIfInClip_StencilFunc:
998 case kEqualIfInClip_StencilFunc:
999 case kLessIfInClip_StencilFunc:
1000 case kLEqualIfInClip_StencilFunc:
1001 funcMask = (funcMask & userBits) | clipBit;
1002 funcRef = (funcRef & userBits) | clipBit;
1004 case kNonZeroIfInClip_StencilFunc:
1005 funcMask = (funcMask & userBits) | clipBit;
1009 SkFAIL("Unknown stencil func");
1012 funcMask &= userBits;
1013 funcRef &= userBits;
1015 const GrStencilFunc* table =
1016 gSpecialToBasicStencilFunc[respectClip];
1017 func = table[func - kBasicStencilFuncCount];
1018 SkASSERT(func >= 0 && func < kBasicStencilFuncCount);
1020 funcMask &= userBits;
1021 funcRef &= userBits;
1024 settings->setFunc(face, func);
1025 settings->setWriteMask(face, writeMask);
1026 settings->setFuncMask(face, funcMask);
1027 settings->setFuncRef(face, funcRef);
1029 if (GrStencilSettings::kFront_Face == face) {
1030 face = GrStencilSettings::kBack_Face;
1031 finished = !twoSided;
1037 settings->copyFrontSettingsToBack();
1041 ////////////////////////////////////////////////////////////////////////////////
1042 GrTexture* GrClipMaskManager::createSoftwareClipMask(int32_t elementsGenID,
1043 GrReducedClip::InitialState initialState,
1044 const GrReducedClip::ElementList& elements,
1045 const SkIRect& clipSpaceIBounds) {
1046 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
1048 GrTexture* result = this->getCachedMaskTexture(elementsGenID, clipSpaceIBounds);
1049 if (NULL != result) {
1053 // The mask texture may be larger than necessary. We round out the clip space bounds and pin
1054 // the top left corner of the resulting rect to the top left of the texture.
1055 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
1057 GrSWMaskHelper helper(this->getContext());
1060 matrix.setTranslate(SkIntToScalar(-clipSpaceIBounds.fLeft),
1061 SkIntToScalar(-clipSpaceIBounds.fTop));
1062 helper.init(maskSpaceIBounds, &matrix);
1064 helper.clear(kAllIn_InitialState == initialState ? 0xFF : 0x00);
1066 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
1068 for (ElementList::Iter iter(elements.headIter()) ; NULL != iter.get(); iter.next()) {
1070 const Element* element = iter.get();
1071 SkRegion::Op op = element->getOp();
1073 if (SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
1074 // Intersect and reverse difference require modifying pixels outside of the geometry
1075 // that is being "drawn". In both cases we erase all the pixels outside of the geometry
1076 // but leave the pixels inside the geometry alone. For reverse difference we invert all
1077 // the pixels before clearing the ones outside the geometry.
1078 if (SkRegion::kReverseDifference_Op == op) {
1079 SkRect temp = SkRect::Make(clipSpaceIBounds);
1080 // invert the entire scene
1081 helper.draw(temp, SkRegion::kXOR_Op, false, 0xFF);
1085 element->asPath(&clipPath);
1086 clipPath.toggleInverseFillType();
1087 helper.draw(clipPath, stroke, SkRegion::kReplace_Op, element->isAA(), 0x00);
1092 // The other ops (union, xor, diff) only affect pixels inside
1093 // the geometry so they can just be drawn normally
1094 if (Element::kRect_Type == element->getType()) {
1095 helper.draw(element->getRect(), op, element->isAA(), 0xFF);
1098 element->asPath(&path);
1099 helper.draw(path, stroke, op, element->isAA(), 0xFF);
1103 // Allocate clip mask texture
1104 result = this->allocMaskTexture(elementsGenID, clipSpaceIBounds, true);
1105 if (NULL == result) {
1109 helper.toTexture(result);
1111 fCurrClipMaskType = kAlpha_ClipMaskType;
1115 ////////////////////////////////////////////////////////////////////////////////
1116 void GrClipMaskManager::releaseResources() {
1117 fAACache.releaseResources();
1120 void GrClipMaskManager::setGpu(GrGpu* gpu) {
1122 fAACache.setContext(gpu->getContext());
1125 void GrClipMaskManager::adjustPathStencilParams(GrStencilSettings* settings) {
1126 const GrDrawState& drawState = fGpu->getDrawState();
1127 GrClipMaskManager::StencilClipMode clipMode;
1128 if (this->isClipInStencil() && drawState.isClipState()) {
1129 clipMode = GrClipMaskManager::kRespectClip_StencilClipMode;
1130 // We can't be modifying the clip and respecting it at the same time.
1131 SkASSERT(!drawState.isStateFlagEnabled(
1132 GrGpu::kModifyStencilClip_StateBit));
1133 } else if (drawState.isStateFlagEnabled(
1134 GrGpu::kModifyStencilClip_StateBit)) {
1135 clipMode = GrClipMaskManager::kModifyClip_StencilClipMode;
1137 clipMode = GrClipMaskManager::kIgnoreClip_StencilClipMode;
1140 // TODO: dynamically attach a stencil buffer
1141 int stencilBits = 0;
1142 GrStencilBuffer* stencilBuffer =
1143 drawState.getRenderTarget()->getStencilBuffer();
1144 if (NULL != stencilBuffer) {
1145 stencilBits = stencilBuffer->bits();
1146 this->adjustStencilParams(settings, clipMode, stencilBits);