- add third_party src.
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / effects / SkBlurMaskFilter.cpp
1
2 /*
3  * Copyright 2006 The Android Open Source Project
4  *
5  * Use of this source code is governed by a BSD-style license that can be
6  * found in the LICENSE file.
7  */
8
9 #include "SkBlurMaskFilter.h"
10 #include "SkBlurMask.h"
11 #include "SkGpuBlurUtils.h"
12 #include "SkFlattenableBuffers.h"
13 #include "SkMaskFilter.h"
14 #include "SkRTConf.h"
15 #include "SkStringUtils.h"
16 #include "SkStrokeRec.h"
17
18 #if SK_SUPPORT_GPU
19 #include "GrContext.h"
20 #include "GrTexture.h"
21 #include "effects/GrSimpleTextureEffect.h"
22 #include "SkGrPixelRef.h"
23 #endif
24
25 class SkBlurMaskFilterImpl : public SkMaskFilter {
26 public:
27     SkBlurMaskFilterImpl(SkScalar sigma, SkBlurMaskFilter::BlurStyle, uint32_t flags);
28
29     // overrides from SkMaskFilter
30     virtual SkMask::Format getFormat() const SK_OVERRIDE;
31     virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
32                             SkIPoint* margin) const SK_OVERRIDE;
33
34 #if SK_SUPPORT_GPU
35     virtual bool canFilterMaskGPU(const SkRect& devBounds,
36                                   const SkIRect& clipBounds,
37                                   const SkMatrix& ctm,
38                                   SkRect* maskRect) const SK_OVERRIDE;
39     virtual bool filterMaskGPU(GrTexture* src,
40                                const SkRect& maskRect,
41                                GrTexture** result,
42                                bool canOverwriteSrc) const;
43 #endif
44
45     virtual void computeFastBounds(const SkRect&, SkRect*) const SK_OVERRIDE;
46
47     SkDEVCODE(virtual void toString(SkString* str) const SK_OVERRIDE;)
48     SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl)
49
50 protected:
51     virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
52                                            const SkIRect& clipBounds,
53                                            NinePatch*) const SK_OVERRIDE;
54
55     bool filterRectMask(SkMask* dstM, const SkRect& r, const SkMatrix& matrix,
56                         SkIPoint* margin, SkMask::CreateMode createMode) const;
57
58 private:
59     // To avoid unseemly allocation requests (esp. for finite platforms like
60     // handset) we limit the radius so something manageable. (as opposed to
61     // a request like 10,000)
62     static const SkScalar kMAX_BLUR_SIGMA;
63
64     SkScalar                    fSigma;
65     SkBlurMaskFilter::BlurStyle fBlurStyle;
66     uint32_t                    fBlurFlags;
67
68     SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);
69     virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE;
70
71     SkScalar computeXformedSigma(const SkMatrix& ctm) const {
72         bool ignoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
73
74         SkScalar xformedSigma = ignoreTransform ? fSigma : ctm.mapRadius(fSigma);
75         return SkMinScalar(xformedSigma, kMAX_BLUR_SIGMA);
76     }
77
78     typedef SkMaskFilter INHERITED;
79 };
80
81 const SkScalar SkBlurMaskFilterImpl::kMAX_BLUR_SIGMA = SkIntToScalar(128);
82
83 SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
84                                        SkBlurMaskFilter::BlurStyle style,
85                                        uint32_t flags) {
86     // use !(radius > 0) instead of radius <= 0 to reject NaN values
87     if (!(radius > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
88         || flags > SkBlurMaskFilter::kAll_BlurFlag) {
89         return NULL;
90     }
91
92     SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
93
94     return SkNEW_ARGS(SkBlurMaskFilterImpl, (sigma, style, flags));
95 }
96
97 SkMaskFilter* SkBlurMaskFilter::Create(SkBlurMaskFilter::BlurStyle style,
98                                        SkScalar sigma,
99                                        uint32_t flags) {
100     // use !(sigma > 0) instead of sigma <= 0 to reject NaN values
101     if (!(sigma > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
102         || flags > SkBlurMaskFilter::kAll_BlurFlag) {
103         return NULL;
104     }
105
106     return SkNEW_ARGS(SkBlurMaskFilterImpl, (sigma, style, flags));
107 }
108
109 ///////////////////////////////////////////////////////////////////////////////
110
111 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar sigma,
112                                            SkBlurMaskFilter::BlurStyle style,
113                                            uint32_t flags)
114     : fSigma(sigma), fBlurStyle(style), fBlurFlags(flags) {
115 #if 0
116     fGamma = NULL;
117     if (gammaScale) {
118         fGamma = new U8[256];
119         if (gammaScale > 0)
120             SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
121         else
122             SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
123     }
124 #endif
125     SkASSERT(fSigma >= 0);
126     SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
127     SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
128 }
129
130 SkMask::Format SkBlurMaskFilterImpl::getFormat() const {
131     return SkMask::kA8_Format;
132 }
133
134 bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
135                                       const SkMatrix& matrix,
136                                       SkIPoint* margin) const{
137     SkScalar sigma = this->computeXformedSigma(matrix);
138
139     SkBlurMask::Quality blurQuality =
140         (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
141             SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;
142
143     return SkBlurMask::BoxBlur(dst, src, sigma, (SkBlurMask::Style)fBlurStyle,
144                                blurQuality, margin);
145 }
146
147 bool SkBlurMaskFilterImpl::filterRectMask(SkMask* dst, const SkRect& r,
148                                           const SkMatrix& matrix,
149                                           SkIPoint* margin, SkMask::CreateMode createMode) const{
150     SkScalar sigma = computeXformedSigma(matrix);
151
152     return SkBlurMask::BlurRect(sigma, dst, r, (SkBlurMask::Style)fBlurStyle,
153                                 margin, createMode);
154 }
155
156 #include "SkCanvas.h"
157
158 static bool drawRectsIntoMask(const SkRect rects[], int count, SkMask* mask) {
159     rects[0].roundOut(&mask->fBounds);
160     mask->fRowBytes = SkAlign4(mask->fBounds.width());
161     mask->fFormat = SkMask::kA8_Format;
162     size_t size = mask->computeImageSize();
163     mask->fImage = SkMask::AllocImage(size);
164     if (NULL == mask->fImage) {
165         return false;
166     }
167     sk_bzero(mask->fImage, size);
168
169     SkBitmap bitmap;
170     bitmap.setConfig(SkBitmap::kA8_Config,
171                      mask->fBounds.width(), mask->fBounds.height(),
172                      mask->fRowBytes);
173     bitmap.setPixels(mask->fImage);
174
175     SkCanvas canvas(bitmap);
176     canvas.translate(-SkIntToScalar(mask->fBounds.left()),
177                      -SkIntToScalar(mask->fBounds.top()));
178
179     SkPaint paint;
180     paint.setAntiAlias(true);
181
182     if (1 == count) {
183         canvas.drawRect(rects[0], paint);
184     } else {
185         // todo: do I need a fast way to do this?
186         SkPath path;
187         path.addRect(rects[0]);
188         path.addRect(rects[1]);
189         path.setFillType(SkPath::kEvenOdd_FillType);
190         canvas.drawPath(path, paint);
191     }
192     return true;
193 }
194
195 static bool rect_exceeds(const SkRect& r, SkScalar v) {
196     return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
197            r.width() > v || r.height() > v;
198 }
199
200 #ifdef SK_IGNORE_FAST_RECT_BLUR
201 SK_CONF_DECLARE( bool, c_analyticBlurNinepatch, "mask.filter.analyticNinePatch", false, "Use the faster analytic blur approach for ninepatch rects" );
202 #else
203 SK_CONF_DECLARE( bool, c_analyticBlurNinepatch, "mask.filter.analyticNinePatch", true, "Use the faster analytic blur approach for ninepatch rects" );
204 #endif
205
206 SkMaskFilter::FilterReturn
207 SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
208                                         const SkMatrix& matrix,
209                                         const SkIRect& clipBounds,
210                                         NinePatch* patch) const {
211     if (count < 1 || count > 2) {
212         return kUnimplemented_FilterReturn;
213     }
214
215     // TODO: report correct metrics for innerstyle, where we do not grow the
216     // total bounds, but we do need an inset the size of our blur-radius
217     if (SkBlurMaskFilter::kInner_BlurStyle == fBlurStyle) {
218         return kUnimplemented_FilterReturn;
219     }
220
221     // TODO: take clipBounds into account to limit our coordinates up front
222     // for now, just skip too-large src rects (to take the old code path).
223     if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
224         return kUnimplemented_FilterReturn;
225     }
226
227     SkIPoint margin;
228     SkMask  srcM, dstM;
229     rects[0].roundOut(&srcM.fBounds);
230     srcM.fImage = NULL;
231     srcM.fFormat = SkMask::kA8_Format;
232     srcM.fRowBytes = 0;
233
234     bool filterResult = false;
235     if (count == 1 && c_analyticBlurNinepatch) {
236         // special case for fast rect blur
237         // don't actually do the blur the first time, just compute the correct size
238         filterResult = this->filterRectMask(&dstM, rects[0], matrix, &margin,
239                                             SkMask::kJustComputeBounds_CreateMode);
240     } else {
241         filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
242     }
243
244     if (!filterResult) {
245         return kFalse_FilterReturn;
246     }
247
248     /*
249      *  smallR is the smallest version of 'rect' that will still guarantee that
250      *  we get the same blur results on all edges, plus 1 center row/col that is
251      *  representative of the extendible/stretchable edges of the ninepatch.
252      *  Since our actual edge may be fractional we inset 1 more to be sure we
253      *  don't miss any interior blur.
254      *  x is an added pixel of blur, and { and } are the (fractional) edge
255      *  pixels from the original rect.
256      *
257      *   x x { x x .... x x } x x
258      *
259      *  Thus, in this case, we inset by a total of 5 (on each side) beginning
260      *  with our outer-rect (dstM.fBounds)
261      */
262     SkRect smallR[2];
263     SkIPoint center;
264
265     // +2 is from +1 for each edge (to account for possible fractional edges
266     int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
267     int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
268     SkIRect innerIR;
269
270     if (1 == count) {
271         innerIR = srcM.fBounds;
272         center.set(smallW, smallH);
273     } else {
274         SkASSERT(2 == count);
275         rects[1].roundIn(&innerIR);
276         center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
277                    smallH + (innerIR.top() - srcM.fBounds.top()));
278     }
279
280     // +1 so we get a clean, stretchable, center row/col
281     smallW += 1;
282     smallH += 1;
283
284     // we want the inset amounts to be integral, so we don't change any
285     // fractional phase on the fRight or fBottom of our smallR.
286     const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
287     const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
288     if (dx < 0 || dy < 0) {
289         // we're too small, relative to our blur, to break into nine-patch,
290         // so we ask to have our normal filterMask() be called.
291         return kUnimplemented_FilterReturn;
292     }
293
294     smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy);
295     if (smallR[0].width() < 2 || smallR[0].height() < 2) {
296         return kUnimplemented_FilterReturn;
297     }
298     if (2 == count) {
299         smallR[1].set(rects[1].left(), rects[1].top(),
300                       rects[1].right() - dx, rects[1].bottom() - dy);
301         SkASSERT(!smallR[1].isEmpty());
302     }
303
304     if (count > 1 || !c_analyticBlurNinepatch) {
305         if (!drawRectsIntoMask(smallR, count, &srcM)) {
306             return kFalse_FilterReturn;
307         }
308
309         SkAutoMaskFreeImage amf(srcM.fImage);
310
311         if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
312             return kFalse_FilterReturn;
313         }
314     } else {
315         if (!this->filterRectMask(&patch->fMask, smallR[0], matrix, &margin,
316                                   SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
317             return kFalse_FilterReturn;
318         }
319     }
320     patch->fMask.fBounds.offsetTo(0, 0);
321     patch->fOuterRect = dstM.fBounds;
322     patch->fCenter = center;
323     return kTrue_FilterReturn;
324 }
325
326 void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src,
327                                              SkRect* dst) const {
328     SkScalar pad = 3.0f * fSigma;
329
330     dst->set(src.fLeft  - pad, src.fTop    - pad,
331              src.fRight + pad, src.fBottom + pad);
332 }
333
334 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
335         : SkMaskFilter(buffer) {
336     fSigma = buffer.readScalar();
337 #ifndef DELETE_THIS_CODE_WHEN_SKPS_ARE_REBUILT_AT_V13_AND_ALL_OTHER_INSTANCES_TOO
338     // Fixing this must be done in two stages. When the skps are recaptured in V13,
339     // remove the ConvertRadiusToSigma but retain the absolute value.
340     // At the same time, switch the code in flatten to write a positive value.
341     // When the skps are captured in V14 the absolute value can be removed.
342     if (fSigma > 0) {
343         fSigma = SkBlurMask::ConvertRadiusToSigma(fSigma);
344     } else {
345         fSigma = -fSigma;
346     }
347 #endif
348     fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readInt();
349     fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag;
350     SkASSERT(fSigma >= 0);
351     SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
352 }
353
354 void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) const {
355     this->INHERITED::flatten(buffer);
356     buffer.writeScalar(-fSigma);
357     buffer.writeInt(fBlurStyle);
358     buffer.writeUInt(fBlurFlags);
359 }
360
361 #if SK_SUPPORT_GPU
362
363 bool SkBlurMaskFilterImpl::canFilterMaskGPU(const SkRect& srcBounds,
364                                             const SkIRect& clipBounds,
365                                             const SkMatrix& ctm,
366                                             SkRect* maskRect) const {
367     SkScalar xformedSigma = this->computeXformedSigma(ctm);
368     if (xformedSigma <= 0) {
369         return false;
370     }
371
372     static const SkScalar kMIN_GPU_BLUR_SIZE  = SkIntToScalar(64);
373     static const SkScalar kMIN_GPU_BLUR_SIGMA = SkIntToScalar(32);
374
375     if (srcBounds.width() <= kMIN_GPU_BLUR_SIZE &&
376         srcBounds.height() <= kMIN_GPU_BLUR_SIZE &&
377         xformedSigma <= kMIN_GPU_BLUR_SIGMA) {
378         // We prefer to blur small rect with small radius via CPU.
379         return false;
380     }
381
382     if (NULL == maskRect) {
383         // don't need to compute maskRect
384         return true;
385     }
386
387     float sigma3 = 3 * SkScalarToFloat(xformedSigma);
388
389     SkRect clipRect = SkRect::Make(clipBounds);
390     SkRect srcRect(srcBounds);
391
392     // Outset srcRect and clipRect by 3 * sigma, to compute affected blur area.
393     srcRect.outset(SkFloatToScalar(sigma3), SkFloatToScalar(sigma3));
394     clipRect.outset(SkFloatToScalar(sigma3), SkFloatToScalar(sigma3));
395     srcRect.intersect(clipRect);
396     *maskRect = srcRect;
397     return true;
398 }
399
400 bool SkBlurMaskFilterImpl::filterMaskGPU(GrTexture* src,
401                                          const SkRect& maskRect,
402                                          GrTexture** result,
403                                          bool canOverwriteSrc) const {
404     SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
405
406     GrContext* context = src->getContext();
407
408     GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
409
410     SkScalar xformedSigma = this->computeXformedSigma(context->getMatrix());
411     SkASSERT(xformedSigma > 0);
412
413     // If we're doing a normal blur, we can clobber the pathTexture in the
414     // gaussianBlur.  Otherwise, we need to save it for later compositing.
415     bool isNormalBlur = (SkBlurMaskFilter::kNormal_BlurStyle == fBlurStyle);
416     *result = SkGpuBlurUtils::GaussianBlur(context, src, isNormalBlur && canOverwriteSrc,
417                                            clipRect, false, xformedSigma, xformedSigma);
418     if (NULL == *result) {
419         return false;
420     }
421
422     if (!isNormalBlur) {
423         context->setIdentityMatrix();
424         GrPaint paint;
425         SkMatrix matrix;
426         matrix.setIDiv(src->width(), src->height());
427         // Blend pathTexture over blurTexture.
428         GrContext::AutoRenderTarget art(context, (*result)->asRenderTarget());
429         paint.addColorEffect(GrSimpleTextureEffect::Create(src, matrix))->unref();
430         if (SkBlurMaskFilter::kInner_BlurStyle == fBlurStyle) {
431             // inner:  dst = dst * src
432             paint.setBlendFunc(kDC_GrBlendCoeff, kZero_GrBlendCoeff);
433         } else if (SkBlurMaskFilter::kSolid_BlurStyle == fBlurStyle) {
434             // solid:  dst = src + dst - src * dst
435             //             = (1 - dst) * src + 1 * dst
436             paint.setBlendFunc(kIDC_GrBlendCoeff, kOne_GrBlendCoeff);
437         } else if (SkBlurMaskFilter::kOuter_BlurStyle == fBlurStyle) {
438             // outer:  dst = dst * (1 - src)
439             //             = 0 * src + (1 - src) * dst
440             paint.setBlendFunc(kZero_GrBlendCoeff, kISC_GrBlendCoeff);
441         }
442         context->drawRect(paint, clipRect);
443     }
444
445     return true;
446 }
447
448 #endif // SK_SUPPORT_GPU
449
450
451 #ifdef SK_DEVELOPER
452 void SkBlurMaskFilterImpl::toString(SkString* str) const {
453     str->append("SkBlurMaskFilterImpl: (");
454
455     str->append("sigma: ");
456     str->appendScalar(fSigma);
457     str->append(" ");
458
459     static const char* gStyleName[SkBlurMaskFilter::kBlurStyleCount] = {
460         "normal", "solid", "outer", "inner"
461     };
462
463     str->appendf("style: %s ", gStyleName[fBlurStyle]);
464     str->append("flags: (");
465     if (fBlurFlags) {
466         bool needSeparator = false;
467         SkAddFlagToString(str,
468                           SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag),
469                           "IgnoreXform", &needSeparator);
470         SkAddFlagToString(str,
471                           SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag),
472                           "HighQuality", &needSeparator);
473     } else {
474         str->append("None");
475     }
476     str->append("))");
477 }
478 #endif
479
480 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter)
481     SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl)
482 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END