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"
15 #include "GrPathRenderer.h"
16 #include "GrRenderTarget.h"
17 #include "GrStencilBuffer.h"
18 #include "GrSWMaskHelper.h"
19 #include "SkRasterClip.h"
20 #include "SkStrokeRec.h"
22 #include "effects/GrTextureDomain.h"
23 #include "effects/GrConvexPolyEffect.h"
24 #include "effects/GrRRectEffect.h"
28 typedef SkClipStack::Element Element;
30 ////////////////////////////////////////////////////////////////////////////////
32 // set up the draw state to enable the aa clipping mask. Besides setting up the
33 // stage matrix this also alters the vertex layout
34 void setup_drawstate_aaclip(GrDrawTarget* gpu,
36 const SkIRect &devBound) {
37 GrDrawState* drawState = gpu->drawState();
41 // We want to use device coords to compute the texture coordinates. We set our matrix to be
42 // equal to the view matrix followed by an offset to the devBound, and then a scaling matrix to
43 // normalized coords. We apply this matrix to the vertex positions rather than local coords.
44 mat.setIDiv(result->width(), result->height());
45 mat.preTranslate(SkIntToScalar(-devBound.fLeft),
46 SkIntToScalar(-devBound.fTop));
47 mat.preConcat(drawState->getViewMatrix());
49 SkIRect domainTexels = SkIRect::MakeWH(devBound.width(), devBound.height());
50 // This could be a long-lived effect that is cached with the alpha-mask.
51 drawState->addCoverageProcessor(
52 GrTextureDomainEffect::Create(result,
54 GrTextureDomain::MakeTexelDomain(result, domainTexels),
55 GrTextureDomain::kDecal_Mode,
56 GrTextureParams::kNone_FilterMode,
57 kPosition_GrCoordSet))->unref();
60 bool path_needs_SW_renderer(GrContext* context,
62 const SkPath& origPath,
63 const SkStrokeRec& stroke,
65 // the gpu alpha mask will draw the inverse paths as non-inverse to a temp buffer
66 SkTCopyOnFirstWrite<SkPath> path(origPath);
67 if (path->isInverseFillType()) {
68 path.writable()->toggleInverseFillType();
70 // last (false) parameter disallows use of the SW path renderer
71 GrPathRendererChain::DrawType type = doAA ?
72 GrPathRendererChain::kColorAntiAlias_DrawType :
73 GrPathRendererChain::kColor_DrawType;
75 return NULL == context->getPathRenderer(*path, stroke, gpu, false, type);
81 * This method traverses the clip stack to see if the GrSoftwarePathRenderer
82 * will be used on any element. If so, it returns true to indicate that the
83 * entire clip should be rendered in SW and then uploaded en masse to the gpu.
85 bool GrClipMaskManager::useSWOnlyPath(const GrReducedClip::ElementList& elements) {
87 // TODO: generalize this function so that when
88 // a clip gets complex enough it can just be done in SW regardless
89 // of whether it would invoke the GrSoftwarePathRenderer.
90 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
92 for (GrReducedClip::ElementList::Iter iter(elements.headIter()); iter.get(); iter.next()) {
93 const Element* element = iter.get();
94 // rects can always be drawn directly w/o using the software path
95 // Skip rrects once we're drawing them directly.
96 if (Element::kRect_Type != element->getType()) {
98 element->asPath(&path);
99 if (path_needs_SW_renderer(this->getContext(), fClipTarget, path, stroke,
108 bool GrClipMaskManager::installClipEffects(const GrReducedClip::ElementList& elements,
109 GrDrawState::AutoRestoreEffects* are,
110 const SkVector& clipToRTOffset,
111 const SkRect* drawBounds) {
113 GrDrawState* drawState = fClipTarget->drawState();
114 SkRect boundsInClipSpace;
116 boundsInClipSpace = *drawBounds;
117 boundsInClipSpace.offset(-clipToRTOffset.fX, -clipToRTOffset.fY);
121 GrRenderTarget* rt = drawState->getRenderTarget();
122 GrReducedClip::ElementList::Iter iter(elements);
128 SkRegion::Op op = iter.get()->getOp();
132 case SkRegion::kReplace_Op:
133 SkASSERT(iter.get() == elements.head());
134 // Fallthrough, handled same as intersect.
135 case SkRegion::kIntersect_Op:
137 if (drawBounds && iter.get()->contains(boundsInClipSpace)) {
141 case SkRegion::kDifference_Op:
143 // We don't currently have a cheap test for whether a rect is fully outside an
144 // element's primitive, so don't attempt to set skip.
155 GrPrimitiveEdgeType edgeType;
156 if (GR_AA_CLIP && iter.get()->isAA()) {
157 if (rt->isMultisampled()) {
158 // Coverage based AA clips don't place nicely with MSAA.
163 invert ? kInverseFillAA_GrProcessorEdgeType : kFillAA_GrProcessorEdgeType;
166 invert ? kInverseFillBW_GrProcessorEdgeType : kFillBW_GrProcessorEdgeType;
168 SkAutoTUnref<GrFragmentProcessor> fp;
169 switch (iter.get()->getType()) {
170 case SkClipStack::Element::kPath_Type:
171 fp.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 fp.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 fp.reset(GrConvexPolyEffect::Create(edgeType, rect));
191 are->set(fClipTarget->drawState());
194 fClipTarget->drawState()->addCoverageProcessor(fp);
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 const SkRect* devBounds,
215 GrDrawState::AutoRestoreEffects* are,
216 GrDrawState::AutoRestoreStencil* ars,
217 ScissorState* scissorState) {
218 fCurrClipMaskType = kNone_ClipMaskType;
219 if (kRespectClip_StencilClipMode == fClipMode) {
220 fClipMode = kIgnoreClip_StencilClipMode;
223 GrReducedClip::ElementList elements(16);
225 GrReducedClip::InitialState initialState;
226 SkIRect clipSpaceIBounds;
229 GrDrawState* drawState = fClipTarget->drawState();
231 const GrRenderTarget* rt = drawState->getRenderTarget();
232 // GrDrawTarget should have filtered this for us
235 bool ignoreClip = !drawState->isClipState() || clipDataIn->fClipStack->isWideOpen();
237 SkIRect clipSpaceRTIBounds = SkIRect::MakeWH(rt->width(), rt->height());
238 clipSpaceRTIBounds.offset(clipDataIn->fOrigin);
239 GrReducedClip::ReduceClipStack(*clipDataIn->fClipStack,
246 if (elements.isEmpty()) {
247 if (GrReducedClip::kAllIn_InitialState == initialState) {
248 ignoreClip = clipSpaceIBounds == clipSpaceRTIBounds;
256 this->setDrawStateStencil(ars);
260 // An element count of 4 was chosen because of the common pattern in Blink of:
265 // when drawing rounded div borders. This could probably be tuned based on a
266 // configuration's relative costs of switching RTs to generate a mask vs
268 if (elements.count() <= 4) {
269 SkVector clipToRTOffset = { SkIntToScalar(-clipDataIn->fOrigin.fX),
270 SkIntToScalar(-clipDataIn->fOrigin.fY) };
271 if (elements.isEmpty() ||
272 (requiresAA && this->installClipEffects(elements, are, clipToRTOffset, devBounds))) {
273 SkIRect scissorSpaceIBounds(clipSpaceIBounds);
274 scissorSpaceIBounds.offset(-clipDataIn->fOrigin);
275 if (NULL == devBounds ||
276 !SkRect::Make(scissorSpaceIBounds).contains(*devBounds)) {
277 scissorState->set(scissorSpaceIBounds);
279 this->setDrawStateStencil(ars);
285 // If MSAA is enabled we can do everything in the stencil buffer.
286 if (0 == rt->numSamples() && requiresAA) {
287 GrTexture* result = NULL;
289 if (this->useSWOnlyPath(elements)) {
290 // The clip geometry is complex enough that it will be more efficient to create it
291 // entirely in software
292 result = this->createSoftwareClipMask(genID,
297 result = this->createAlphaClipMask(genID,
304 // The mask's top left coord should be pinned to the rounded-out top left corner of
305 // clipSpace bounds. We determine the mask's position WRT to the render target here.
306 SkIRect rtSpaceMaskBounds = clipSpaceIBounds;
307 rtSpaceMaskBounds.offset(-clipDataIn->fOrigin);
308 are->set(fClipTarget->drawState());
309 setup_drawstate_aaclip(fClipTarget, result, rtSpaceMaskBounds);
310 this->setDrawStateStencil(ars);
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 scissorState->set(scissorSpaceIBounds);
338 this->setDrawStateStencil(ars);
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 = fClipTarget->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 GrProcessor that covers
401 // the entire mask bounds and writes 0 outside the rect.
402 if (element->isAA()) {
403 this->getContext()->getAARectRenderer()->fillAARect(fClipTarget,
408 fClipTarget->drawSimpleRect(element->getRect());
413 element->asPath(&path);
414 path.setIsVolatile(true);
415 if (path.isInverseFillType()) {
416 path.toggleInverseFillType();
418 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
420 GrPathRendererChain::DrawType type;
421 type = element->isAA() ? GrPathRendererChain::kColorAntiAlias_DrawType :
422 GrPathRendererChain::kColor_DrawType;
423 pr = this->getContext()->getPathRenderer(path, stroke, fClipTarget, false, type);
428 pr->drawPath(path, stroke, fClipTarget, element->isAA());
435 bool GrClipMaskManager::canStencilAndDrawElement(GrTexture* target,
436 const SkClipStack::Element* element,
437 GrPathRenderer** pr) {
438 GrDrawState* drawState = fClipTarget->drawState();
439 drawState->setRenderTarget(target->asRenderTarget());
441 if (Element::kRect_Type == element->getType()) {
444 // We shouldn't get here with an empty clip element.
445 SkASSERT(Element::kEmpty_Type != element->getType());
447 element->asPath(&path);
448 if (path.isInverseFillType()) {
449 path.toggleInverseFillType();
451 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
452 GrPathRendererChain::DrawType type = element->isAA() ?
453 GrPathRendererChain::kStencilAndColorAntiAlias_DrawType :
454 GrPathRendererChain::kStencilAndColor_DrawType;
455 *pr = this->getContext()->getPathRenderer(path, stroke, fClipTarget, false, type);
456 return SkToBool(*pr);
460 void GrClipMaskManager::mergeMask(GrTexture* dstMask,
463 const SkIRect& dstBound,
464 const SkIRect& srcBound) {
465 GrDrawState::AutoViewMatrixRestore avmr;
466 GrDrawState* drawState = fClipTarget->drawState();
467 SkAssertResult(avmr.setIdentity(drawState));
468 GrDrawState::AutoRestoreEffects are(drawState);
470 drawState->setRenderTarget(dstMask->asRenderTarget());
472 setup_boolean_blendcoeffs(drawState, op);
475 sampleM.setIDiv(srcMask->width(), srcMask->height());
477 drawState->addColorProcessor(
478 GrTextureDomainEffect::Create(srcMask,
480 GrTextureDomain::MakeTexelDomain(srcMask, srcBound),
481 GrTextureDomain::kDecal_Mode,
482 GrTextureParams::kNone_FilterMode))->unref();
483 fClipTarget->drawSimpleRect(SkRect::Make(dstBound));
486 GrTexture* GrClipMaskManager::createTempMask(int width, int height) {
488 desc.fFlags = kRenderTarget_GrSurfaceFlag|kNoStencil_GrSurfaceFlag;
490 desc.fHeight = height;
491 desc.fConfig = kAlpha_8_GrPixelConfig;
493 return this->getContext()->refScratchTexture(desc, GrContext::kApprox_ScratchTexMatch);
496 ////////////////////////////////////////////////////////////////////////////////
497 // Return the texture currently in the cache if it exists. Otherwise, return NULL
498 GrTexture* GrClipMaskManager::getCachedMaskTexture(int32_t elementsGenID,
499 const SkIRect& clipSpaceIBounds) {
500 bool cached = fAACache.canReuse(elementsGenID, clipSpaceIBounds);
505 return fAACache.getLastMask();
508 ////////////////////////////////////////////////////////////////////////////////
509 // Allocate a texture in the texture cache. This function returns the texture
510 // allocated (or NULL on error).
511 GrTexture* GrClipMaskManager::allocMaskTexture(int32_t elementsGenID,
512 const SkIRect& clipSpaceIBounds,
514 // Since we are setting up the cache we should free up the
515 // currently cached mask so it can be reused.
519 desc.fFlags = willUpload ? kNone_GrSurfaceFlags : kRenderTarget_GrSurfaceFlag;
520 desc.fWidth = clipSpaceIBounds.width();
521 desc.fHeight = clipSpaceIBounds.height();
522 desc.fConfig = kRGBA_8888_GrPixelConfig;
523 if (willUpload || this->getContext()->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) {
524 // We would always like A8 but it isn't supported on all platforms
525 desc.fConfig = kAlpha_8_GrPixelConfig;
528 fAACache.acquireMask(elementsGenID, desc, clipSpaceIBounds);
529 return fAACache.getLastMask();
532 ////////////////////////////////////////////////////////////////////////////////
533 // Create a 8-bit clip mask in alpha
534 GrTexture* GrClipMaskManager::createAlphaClipMask(int32_t elementsGenID,
535 GrReducedClip::InitialState initialState,
536 const GrReducedClip::ElementList& elements,
537 const SkIRect& clipSpaceIBounds) {
538 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
540 // First, check for cached texture
541 GrTexture* result = this->getCachedMaskTexture(elementsGenID, clipSpaceIBounds);
543 fCurrClipMaskType = kAlpha_ClipMaskType;
547 // There's no texture in the cache. Let's try to allocate it then.
548 result = this->allocMaskTexture(elementsGenID, clipSpaceIBounds, false);
549 if (NULL == result) {
554 // The top-left of the mask corresponds to the top-left corner of the bounds.
555 SkVector clipToMaskOffset = {
556 SkIntToScalar(-clipSpaceIBounds.fLeft),
557 SkIntToScalar(-clipSpaceIBounds.fTop)
559 // The texture may be larger than necessary, this rect represents the part of the texture
560 // we populate with a rasterization of the clip.
561 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
563 // Set the matrix so that rendered clip elements are transformed to mask space from clip space.
565 translate.setTranslate(clipToMaskOffset);
566 GrDrawTarget::AutoGeometryAndStatePush agasp(fClipTarget, GrDrawTarget::kReset_ASRInit,
569 GrDrawState* drawState = fClipTarget->drawState();
571 // We're drawing a coverage mask and want coverage to be run through the blend function.
572 drawState->enableState(GrDrawState::kCoverageDrawing_StateBit);
574 // The scratch texture that we are drawing into can be substantially larger than the mask. Only
575 // clear the part that we care about.
576 fClipTarget->clear(&maskSpaceIBounds,
577 GrReducedClip::kAllIn_InitialState == initialState ? 0xffffffff : 0x00000000,
579 result->asRenderTarget());
581 // When we use the stencil in the below loop it is important to have this clip installed.
582 // The second pass that zeros the stencil buffer renders the rect maskSpaceIBounds so the first
583 // pass must not set values outside of this bounds or stencil values outside the rect won't be
585 GrDrawTarget::AutoClipRestore acr(fClipTarget, maskSpaceIBounds);
586 drawState->enableState(GrDrawState::kClip_StateBit);
588 SkAutoTUnref<GrTexture> temp;
589 // walk through each clip element and perform its set op
590 for (GrReducedClip::ElementList::Iter iter = elements.headIter(); iter.get(); iter.next()) {
591 const Element* element = iter.get();
592 SkRegion::Op op = element->getOp();
593 bool invert = element->isInverseFilled();
595 if (invert || SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
596 GrPathRenderer* pr = NULL;
597 bool useTemp = !this->canStencilAndDrawElement(result, element, &pr);
599 // This is the bounds of the clip element in the space of the alpha-mask. The temporary
600 // mask buffer can be substantially larger than the actually clip stack element. We
601 // touch the minimum number of pixels necessary and use decal mode to combine it with
603 SkIRect maskSpaceElementIBounds;
607 maskSpaceElementIBounds = maskSpaceIBounds;
609 SkRect elementBounds = element->getBounds();
610 elementBounds.offset(clipToMaskOffset);
611 elementBounds.roundOut(&maskSpaceElementIBounds);
615 temp.reset(this->createTempMask(maskSpaceIBounds.fRight,
616 maskSpaceIBounds.fBottom));
623 // clear the temp target and set blend to replace
624 fClipTarget->clear(&maskSpaceElementIBounds,
625 invert ? 0xffffffff : 0x00000000,
627 dst->asRenderTarget());
628 setup_boolean_blendcoeffs(drawState, SkRegion::kReplace_Op);
631 // draw directly into the result with the stencil set to make the pixels affected
632 // by the clip shape be non-zero.
634 GR_STATIC_CONST_SAME_STENCIL(kStencilInElement,
641 drawState->setStencil(kStencilInElement);
642 setup_boolean_blendcoeffs(drawState, op);
645 drawState->setAlpha(invert ? 0x00 : 0xff);
647 if (!this->drawElement(dst, element, pr)) {
653 // Now draw into the accumulator using the real operation and the temp buffer as a
655 this->mergeMask(result,
659 maskSpaceElementIBounds);
661 // Draw to the exterior pixels (those with a zero stencil value).
662 drawState->setAlpha(invert ? 0xff : 0x00);
663 GR_STATIC_CONST_SAME_STENCIL(kDrawOutsideElement,
670 drawState->setStencil(kDrawOutsideElement);
671 fClipTarget->drawSimpleRect(clipSpaceIBounds);
672 drawState->disableStencil();
675 // all the remaining ops can just be directly draw into the accumulation buffer
676 drawState->setAlpha(0xff);
677 setup_boolean_blendcoeffs(drawState, op);
678 this->drawElement(result, element);
682 fCurrClipMaskType = kAlpha_ClipMaskType;
686 ////////////////////////////////////////////////////////////////////////////////
687 // Create a 1-bit clip mask in the stencil buffer. 'devClipBounds' are in device
688 // (as opposed to canvas) coordinates
689 bool GrClipMaskManager::createStencilClipMask(int32_t elementsGenID,
690 GrReducedClip::InitialState initialState,
691 const GrReducedClip::ElementList& elements,
692 const SkIRect& clipSpaceIBounds,
693 const SkIPoint& clipSpaceToStencilOffset) {
695 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
697 GrDrawState* drawState = fClipTarget->drawState();
698 SkASSERT(drawState->isClipState());
700 GrRenderTarget* rt = drawState->getRenderTarget();
703 // TODO: dynamically attach a SB when needed.
704 GrStencilBuffer* stencilBuffer = rt->getStencilBuffer();
705 if (NULL == stencilBuffer) {
709 if (stencilBuffer->mustRenderClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset)) {
710 stencilBuffer->setLastClip(elementsGenID, clipSpaceIBounds, clipSpaceToStencilOffset);
712 // Set the matrix so that rendered clip elements are transformed from clip to stencil space.
713 SkVector translate = {
714 SkIntToScalar(clipSpaceToStencilOffset.fX),
715 SkIntToScalar(clipSpaceToStencilOffset.fY)
718 matrix.setTranslate(translate);
719 GrDrawTarget::AutoGeometryAndStatePush agasp(fClipTarget, GrDrawTarget::kReset_ASRInit,
721 drawState = fClipTarget->drawState();
723 drawState->setRenderTarget(rt);
725 // We set the current clip to the bounds so that our recursive draws are scissored to them.
726 SkIRect stencilSpaceIBounds(clipSpaceIBounds);
727 stencilSpaceIBounds.offset(clipSpaceToStencilOffset);
728 GrDrawTarget::AutoClipRestore acr(fClipTarget, stencilSpaceIBounds);
729 drawState->enableState(GrDrawState::kClip_StateBit);
731 #if !VISUALIZE_COMPLEX_CLIP
732 drawState->enableState(GrDrawState::kNoColorWrites_StateBit);
735 int clipBit = stencilBuffer->bits();
736 SkASSERT((clipBit <= 16) && "Ganesh only handles 16b or smaller stencil buffers");
737 clipBit = (1 << (clipBit-1));
739 fClipTarget->clearStencilClip(stencilSpaceIBounds,
740 GrReducedClip::kAllIn_InitialState == initialState,
743 // walk through each clip element and perform its set op
744 // with the existing clip.
745 for (GrReducedClip::ElementList::Iter iter(elements.headIter()); iter.get(); iter.next()) {
746 const Element* element = iter.get();
747 bool fillInverted = false;
748 // enabled at bottom of loop
749 fClipMode = kIgnoreClip_StencilClipMode;
750 // if the target is MSAA then we want MSAA enabled when the clip is soft
751 if (rt->isMultisampled()) {
752 drawState->setState(GrDrawState::kHWAntialias_StateBit, element->isAA());
755 // This will be used to determine whether the clip shape can be rendered into the
756 // stencil with arbitrary stencil settings.
757 GrPathRenderer::StencilSupport stencilSupport;
759 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
761 SkRegion::Op op = element->getOp();
763 GrPathRenderer* pr = NULL;
765 if (Element::kRect_Type == element->getType()) {
766 stencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
767 fillInverted = false;
769 element->asPath(&clipPath);
770 fillInverted = clipPath.isInverseFillType();
772 clipPath.toggleInverseFillType();
774 pr = this->getContext()->getPathRenderer(clipPath,
778 GrPathRendererChain::kStencilOnly_DrawType,
786 GrStencilSettings stencilSettings[GrStencilSettings::kMaxStencilClipPasses];
788 bool canRenderDirectToStencil =
789 GrPathRenderer::kNoRestriction_StencilSupport == stencilSupport;
790 bool canDrawDirectToClip; // Given the renderer, the element,
791 // fill rule, and set operation can
792 // we render the element directly to
793 // stencil bit used for clipping.
794 canDrawDirectToClip = GrStencilSettings::GetClipPasses(op,
795 canRenderDirectToStencil,
801 // draw the element to the client stencil bits if necessary
802 if (!canDrawDirectToClip) {
803 GR_STATIC_CONST_SAME_STENCIL(gDrawToStencil,
811 if (Element::kRect_Type == element->getType()) {
812 *drawState->stencil() = gDrawToStencil;
813 fClipTarget->drawSimpleRect(element->getRect());
815 if (!clipPath.isEmpty()) {
816 if (canRenderDirectToStencil) {
817 *drawState->stencil() = gDrawToStencil;
818 pr->drawPath(clipPath, stroke, fClipTarget, false);
820 pr->stencilPath(clipPath, stroke, fClipTarget);
826 // now we modify the clip bit by rendering either the clip
827 // element directly or a bounding rect of the entire clip.
828 fClipMode = kModifyClip_StencilClipMode;
829 for (int p = 0; p < passes; ++p) {
830 *drawState->stencil() = stencilSettings[p];
831 if (canDrawDirectToClip) {
832 if (Element::kRect_Type == element->getType()) {
834 fClipTarget->drawSimpleRect(element->getRect());
837 pr->drawPath(clipPath, stroke, fClipTarget, false);
841 // The view matrix is setup to do clip space -> stencil space translation, so
842 // draw rect in clip space.
843 fClipTarget->drawSimpleRect(SkRect::Make(clipSpaceIBounds));
848 // set this last because recursive draws may overwrite it back to kNone.
849 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
850 fCurrClipMaskType = kStencil_ClipMaskType;
851 fClipMode = kRespectClip_StencilClipMode;
856 // mapping of clip-respecting stencil funcs to normal stencil funcs
857 // mapping depends on whether stencil-clipping is in effect.
858 static const GrStencilFunc
859 gSpecialToBasicStencilFunc[2][kClipStencilFuncCount] = {
860 {// Stencil-Clipping is DISABLED, we are effectively always inside the clip
862 kAlways_StencilFunc, // kAlwaysIfInClip_StencilFunc
863 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
864 kLess_StencilFunc, // kLessIfInClip_StencilFunc
865 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
866 // Special in the clip func that forces user's ref to be 0.
867 kNotEqual_StencilFunc, // kNonZeroIfInClip_StencilFunc
868 // make ref 0 and do normal nequal.
870 {// Stencil-Clipping is ENABLED
872 kEqual_StencilFunc, // kAlwaysIfInClip_StencilFunc
873 // eq stencil clip bit, mask
876 kEqual_StencilFunc, // kEqualIfInClip_StencilFunc
877 // add stencil bit to mask and ref
879 kLess_StencilFunc, // kLessIfInClip_StencilFunc
880 kLEqual_StencilFunc, // kLEqualIfInClip_StencilFunc
881 // for both of these we can add
882 // the clip bit to the mask and
883 // ref and compare as normal
884 // Special in the clip func that forces user's ref to be 0.
885 kLess_StencilFunc, // kNonZeroIfInClip_StencilFunc
886 // make ref have only the clip bit set
887 // and make comparison be less
888 // 10..0 < 1..user_bits..
893 // Sets the settings to clip against the stencil buffer clip while ignoring the
895 const GrStencilSettings& basic_apply_stencil_clip_settings() {
896 // stencil settings to use when clip is in stencil
897 GR_STATIC_CONST_SAME_STENCIL_STRUCT(gSettings,
900 kAlwaysIfInClip_StencilFunc,
904 return *GR_CONST_STENCIL_SETTINGS_PTR_FROM_STRUCT_PTR(&gSettings);
908 void GrClipMaskManager::setDrawStateStencil(GrDrawState::AutoRestoreStencil* ars) {
909 // We make two copies of the StencilSettings here (except in the early
910 // exit scenario. One copy from draw state to the stack var. Then another
911 // from the stack var to the gpu. We could make this class hold a ptr to
912 // GrGpu's fStencilSettings and eliminate the stack copy here.
914 const GrDrawState& drawState = fClipTarget->getDrawState();
916 // use stencil for clipping if clipping is enabled and the clip
917 // has been written into the stencil.
919 GrStencilSettings settings;
920 // The GrGpu client may not be using the stencil buffer but we may need to
921 // enable it in order to respect a stencil clip.
922 if (drawState.getStencil().isDisabled()) {
923 if (GrClipMaskManager::kRespectClip_StencilClipMode == fClipMode) {
924 settings = basic_apply_stencil_clip_settings();
929 settings = drawState.getStencil();
932 // TODO: dynamically attach a stencil buffer
934 GrStencilBuffer* stencilBuffer = drawState.getRenderTarget()->getStencilBuffer();
936 stencilBits = stencilBuffer->bits();
939 SkASSERT(fClipTarget->caps()->stencilWrapOpsSupport() || !settings.usesWrapOp());
940 SkASSERT(fClipTarget->caps()->twoSidedStencilSupport() || !settings.isTwoSided());
941 this->adjustStencilParams(&settings, fClipMode, stencilBits);
942 ars->set(fClipTarget->drawState());
943 fClipTarget->drawState()->setStencil(settings);
946 void GrClipMaskManager::adjustStencilParams(GrStencilSettings* settings,
947 StencilClipMode mode,
949 SkASSERT(stencilBitCnt > 0);
951 if (kModifyClip_StencilClipMode == mode) {
952 // We assume that this clip manager itself is drawing to the GrGpu and
953 // has already setup the correct values.
957 unsigned int clipBit = (1 << (stencilBitCnt - 1));
958 unsigned int userBits = clipBit - 1;
960 GrStencilSettings::Face face = GrStencilSettings::kFront_Face;
961 bool twoSided = fClipTarget->caps()->twoSidedStencilSupport();
963 bool finished = false;
965 GrStencilFunc func = settings->func(face);
966 uint16_t writeMask = settings->writeMask(face);
967 uint16_t funcMask = settings->funcMask(face);
968 uint16_t funcRef = settings->funcRef(face);
970 SkASSERT((unsigned) func < kStencilFuncCount);
972 writeMask &= userBits;
974 if (func >= kBasicStencilFuncCount) {
975 int respectClip = kRespectClip_StencilClipMode == mode;
977 // The GrGpu class should have checked this
978 SkASSERT(this->isClipInStencil());
980 case kAlwaysIfInClip_StencilFunc:
984 case kEqualIfInClip_StencilFunc:
985 case kLessIfInClip_StencilFunc:
986 case kLEqualIfInClip_StencilFunc:
987 funcMask = (funcMask & userBits) | clipBit;
988 funcRef = (funcRef & userBits) | clipBit;
990 case kNonZeroIfInClip_StencilFunc:
991 funcMask = (funcMask & userBits) | clipBit;
995 SkFAIL("Unknown stencil func");
998 funcMask &= userBits;
1001 const GrStencilFunc* table =
1002 gSpecialToBasicStencilFunc[respectClip];
1003 func = table[func - kBasicStencilFuncCount];
1004 SkASSERT(func >= 0 && func < kBasicStencilFuncCount);
1006 funcMask &= userBits;
1007 funcRef &= userBits;
1010 settings->setFunc(face, func);
1011 settings->setWriteMask(face, writeMask);
1012 settings->setFuncMask(face, funcMask);
1013 settings->setFuncRef(face, funcRef);
1015 if (GrStencilSettings::kFront_Face == face) {
1016 face = GrStencilSettings::kBack_Face;
1017 finished = !twoSided;
1023 settings->copyFrontSettingsToBack();
1027 ////////////////////////////////////////////////////////////////////////////////
1028 GrTexture* GrClipMaskManager::createSoftwareClipMask(int32_t elementsGenID,
1029 GrReducedClip::InitialState initialState,
1030 const GrReducedClip::ElementList& elements,
1031 const SkIRect& clipSpaceIBounds) {
1032 SkASSERT(kNone_ClipMaskType == fCurrClipMaskType);
1034 GrTexture* result = this->getCachedMaskTexture(elementsGenID, clipSpaceIBounds);
1039 // The mask texture may be larger than necessary. We round out the clip space bounds and pin
1040 // the top left corner of the resulting rect to the top left of the texture.
1041 SkIRect maskSpaceIBounds = SkIRect::MakeWH(clipSpaceIBounds.width(), clipSpaceIBounds.height());
1043 GrSWMaskHelper helper(this->getContext());
1046 matrix.setTranslate(SkIntToScalar(-clipSpaceIBounds.fLeft),
1047 SkIntToScalar(-clipSpaceIBounds.fTop));
1048 helper.init(maskSpaceIBounds, &matrix, false);
1050 helper.clear(GrReducedClip::kAllIn_InitialState == initialState ? 0xFF : 0x00);
1052 SkStrokeRec stroke(SkStrokeRec::kFill_InitStyle);
1054 for (GrReducedClip::ElementList::Iter iter(elements.headIter()) ; iter.get(); iter.next()) {
1056 const Element* element = iter.get();
1057 SkRegion::Op op = element->getOp();
1059 if (SkRegion::kIntersect_Op == op || SkRegion::kReverseDifference_Op == op) {
1060 // Intersect and reverse difference require modifying pixels outside of the geometry
1061 // that is being "drawn". In both cases we erase all the pixels outside of the geometry
1062 // but leave the pixels inside the geometry alone. For reverse difference we invert all
1063 // the pixels before clearing the ones outside the geometry.
1064 if (SkRegion::kReverseDifference_Op == op) {
1065 SkRect temp = SkRect::Make(clipSpaceIBounds);
1066 // invert the entire scene
1067 helper.draw(temp, SkRegion::kXOR_Op, false, 0xFF);
1071 element->asPath(&clipPath);
1072 clipPath.toggleInverseFillType();
1073 helper.draw(clipPath, stroke, SkRegion::kReplace_Op, element->isAA(), 0x00);
1078 // The other ops (union, xor, diff) only affect pixels inside
1079 // the geometry so they can just be drawn normally
1080 if (Element::kRect_Type == element->getType()) {
1081 helper.draw(element->getRect(), op, element->isAA(), 0xFF);
1084 element->asPath(&path);
1085 helper.draw(path, stroke, op, element->isAA(), 0xFF);
1089 // Allocate clip mask texture
1090 result = this->allocMaskTexture(elementsGenID, clipSpaceIBounds, true);
1091 if (NULL == result) {
1095 helper.toTexture(result);
1097 fCurrClipMaskType = kAlpha_ClipMaskType;
1101 ////////////////////////////////////////////////////////////////////////////////
1102 void GrClipMaskManager::purgeResources() {
1103 fAACache.purgeResources();
1106 void GrClipMaskManager::setClipTarget(GrClipTarget* clipTarget) {
1107 fClipTarget = clipTarget;
1108 fAACache.setContext(clipTarget->getContext());
1111 void GrClipMaskManager::adjustPathStencilParams(GrStencilSettings* settings) {
1112 const GrDrawState& drawState = fClipTarget->getDrawState();
1114 // TODO: dynamically attach a stencil buffer
1115 int stencilBits = 0;
1116 GrStencilBuffer* stencilBuffer = drawState.getRenderTarget()->getStencilBuffer();
1117 if (stencilBuffer) {
1118 stencilBits = stencilBuffer->bits();
1119 this->adjustStencilParams(settings, fClipMode, stencilBits);