BlurTest.cpp revision b0b1aa04ed82a7cb16c7e6a06d92a411d7bd3749
1/*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkBlurMask.h"
9#include "SkBlurMaskFilter.h"
10#include "SkBlurDrawLooper.h"
11#include "SkLayerDrawLooper.h"
12#include "SkEmbossMaskFilter.h"
13#include "SkCanvas.h"
14#include "SkMath.h"
15#include "SkPaint.h"
16#include "Test.h"
17
18#if SK_SUPPORT_GPU
19#include "GrContextFactory.h"
20#include "SkGpuDevice.h"
21#endif
22
23#define WRITE_CSV 0
24
25///////////////////////////////////////////////////////////////////////////////
26
27#define ILLEGAL_MODE    ((SkXfermode::Mode)-1)
28
29static const int outset = 100;
30static const SkColor bgColor = SK_ColorWHITE;
31static const int strokeWidth = 4;
32
33static void create(SkBitmap* bm, const SkIRect& bound) {
34    bm->allocN32Pixels(bound.width(), bound.height());
35}
36
37static void drawBG(SkCanvas* canvas) {
38    canvas->drawColor(bgColor);
39}
40
41
42struct BlurTest {
43    void (*addPath)(SkPath*);
44    int viewLen;
45    SkIRect views[9];
46};
47
48//Path Draw Procs
49//Beware that paths themselves my draw differently depending on the clip.
50static void draw50x50Rect(SkPath* path) {
51    path->addRect(0, 0, SkIntToScalar(50), SkIntToScalar(50));
52}
53
54//Tests
55static BlurTest tests[] = {
56    { draw50x50Rect, 3, {
57        //inner half of blur
58        { 0, 0, 50, 50 },
59        //blur, but no path.
60        { 50 + strokeWidth/2, 50 + strokeWidth/2, 100, 100 },
61        //just an edge
62        { 40, strokeWidth, 60, 50 - strokeWidth },
63    }},
64};
65
66/** Assumes that the ref draw was completely inside ref canvas --
67    implies that everything outside is "bgColor".
68    Checks that all overlap is the same and that all non-overlap on the
69    ref is "bgColor".
70 */
71static bool compare(const SkBitmap& ref, const SkIRect& iref,
72                    const SkBitmap& test, const SkIRect& itest)
73{
74    const int xOff = itest.fLeft - iref.fLeft;
75    const int yOff = itest.fTop - iref.fTop;
76
77    SkAutoLockPixels alpRef(ref);
78    SkAutoLockPixels alpTest(test);
79
80    for (int y = 0; y < test.height(); ++y) {
81        for (int x = 0; x < test.width(); ++x) {
82            SkColor testColor = test.getColor(x, y);
83            int refX = x + xOff;
84            int refY = y + yOff;
85            SkColor refColor;
86            if (refX >= 0 && refX < ref.width() &&
87                refY >= 0 && refY < ref.height())
88            {
89                refColor = ref.getColor(refX, refY);
90            } else {
91                refColor = bgColor;
92            }
93            if (refColor != testColor) {
94                return false;
95            }
96        }
97    }
98    return true;
99}
100
101static void test_blur_drawing(skiatest::Reporter* reporter) {
102
103    SkPaint paint;
104    paint.setColor(SK_ColorGRAY);
105    paint.setStyle(SkPaint::kStroke_Style);
106    paint.setStrokeWidth(SkIntToScalar(strokeWidth));
107
108    SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(5));
109    for (int style = 0; style <= kLastEnum_SkBlurStyle; ++style) {
110        SkBlurStyle blurStyle = static_cast<SkBlurStyle>(style);
111
112        const uint32_t flagPermutations = SkBlurMaskFilter::kAll_BlurFlag;
113        for (uint32_t flags = 0; flags < flagPermutations; ++flags) {
114            SkMaskFilter* filter;
115            filter = SkBlurMaskFilter::Create(blurStyle, sigma, flags);
116
117            paint.setMaskFilter(filter);
118            filter->unref();
119
120            for (size_t test = 0; test < SK_ARRAY_COUNT(tests); ++test) {
121                SkPath path;
122                tests[test].addPath(&path);
123                SkPath strokedPath;
124                paint.getFillPath(path, &strokedPath);
125                SkRect refBound = strokedPath.getBounds();
126                SkIRect iref;
127                refBound.roundOut(&iref);
128                iref.inset(-outset, -outset);
129                SkBitmap refBitmap;
130                create(&refBitmap, iref);
131
132                SkCanvas refCanvas(refBitmap);
133                refCanvas.translate(SkIntToScalar(-iref.fLeft),
134                                    SkIntToScalar(-iref.fTop));
135                drawBG(&refCanvas);
136                refCanvas.drawPath(path, paint);
137
138                for (int view = 0; view < tests[test].viewLen; ++view) {
139                    SkIRect itest = tests[test].views[view];
140                    SkBitmap testBitmap;
141                    create(&testBitmap, itest);
142
143                    SkCanvas testCanvas(testBitmap);
144                    testCanvas.translate(SkIntToScalar(-itest.fLeft),
145                                         SkIntToScalar(-itest.fTop));
146                    drawBG(&testCanvas);
147                    testCanvas.drawPath(path, paint);
148
149                    REPORTER_ASSERT(reporter,
150                        compare(refBitmap, iref, testBitmap, itest));
151                }
152            }
153        }
154    }
155}
156
157///////////////////////////////////////////////////////////////////////////////
158
159// Use SkBlurMask::BlurGroundTruth to blur a 'width' x 'height' solid
160// white rect. Return the right half of the middle row in 'result'.
161static void ground_truth_2d(int width, int height,
162                            SkScalar sigma,
163                            int* result, int resultCount) {
164    SkMask src, dst;
165
166    src.fBounds.set(0, 0, width, height);
167    src.fFormat = SkMask::kA8_Format;
168    src.fRowBytes = src.fBounds.width();
169    src.fImage = SkMask::AllocImage(src.computeTotalImageSize());
170
171    memset(src.fImage, 0xff, src.computeTotalImageSize());
172
173    dst.fImage = NULL;
174    SkBlurMask::BlurGroundTruth(sigma, &dst, src, kNormal_SkBlurStyle);
175
176    int midX = dst.fBounds.centerX();
177    int midY = dst.fBounds.centerY();
178    uint8_t* bytes = dst.getAddr8(midX, midY);
179    int i;
180    for (i = 0; i < dst.fBounds.width()-(midX-dst.fBounds.fLeft); ++i) {
181        if (i < resultCount) {
182            result[i] = bytes[i];
183        }
184    }
185    for ( ; i < resultCount; ++i) {
186        result[i] = 0;
187    }
188
189    SkMask::FreeImage(src.fImage);
190    SkMask::FreeImage(dst.fImage);
191}
192
193// Implement a step function that is 255 between min and max; 0 elsewhere.
194static int step(int x, SkScalar min, SkScalar max) {
195    if (min < x && x < max) {
196        return 255;
197    }
198    return 0;
199}
200
201// Implement a Gaussian function with 0 mean and std.dev. of 'sigma'.
202static float gaussian(int x, SkScalar sigma) {
203    float k = SK_Scalar1/(sigma * sqrtf(2.0f*SK_ScalarPI));
204    float exponent = -(x * x) / (2 * sigma * sigma);
205    return k * expf(exponent);
206}
207
208// Perform a brute force convolution of a step function with a Gaussian.
209// Return the right half in 'result'
210static void brute_force_1d(SkScalar stepMin, SkScalar stepMax,
211                           SkScalar gaussianSigma,
212                           int* result, int resultCount) {
213
214    int gaussianRange = SkScalarCeilToInt(10 * gaussianSigma);
215
216    for (int i = 0; i < resultCount; ++i) {
217        SkScalar sum = 0.0f;
218        for (int j = -gaussianRange; j < gaussianRange; ++j) {
219            sum += gaussian(j, gaussianSigma) * step(i-j, stepMin, stepMax);
220        }
221
222        result[i] = SkClampMax(SkClampPos(int(sum + 0.5f)), 255);
223    }
224}
225
226static void blur_path(SkCanvas* canvas, const SkPath& path,
227                      SkScalar gaussianSigma) {
228
229    SkScalar midX = path.getBounds().centerX();
230    SkScalar midY = path.getBounds().centerY();
231
232    canvas->translate(-midX, -midY);
233
234    SkPaint blurPaint;
235    blurPaint.setColor(SK_ColorWHITE);
236    SkMaskFilter* filter = SkBlurMaskFilter::Create(kNormal_SkBlurStyle,
237                                                    gaussianSigma,
238                                                    SkBlurMaskFilter::kHighQuality_BlurFlag);
239    blurPaint.setMaskFilter(filter)->unref();
240
241    canvas->drawColor(SK_ColorBLACK);
242    canvas->drawPath(path, blurPaint);
243}
244
245// Readback the blurred draw results from the canvas
246static void readback(SkCanvas* canvas, int* result, int resultCount) {
247    SkBitmap readback;
248    readback.allocN32Pixels(resultCount, 30);
249
250    SkIRect readBackRect = { 0, 0, resultCount, 30 };
251
252    canvas->readPixels(readBackRect, &readback);
253
254    readback.lockPixels();
255    SkPMColor* pixels = (SkPMColor*) readback.getAddr32(0, 15);
256
257    for (int i = 0; i < resultCount; ++i) {
258        result[i] = SkColorGetR(pixels[i]);
259    }
260}
261
262// Draw a blurred version of the provided path.
263// Return the right half of the middle row in 'result'.
264static void cpu_blur_path(const SkPath& path, SkScalar gaussianSigma,
265                          int* result, int resultCount) {
266
267    SkBitmap bitmap;
268    bitmap.allocN32Pixels(resultCount, 30);
269    SkCanvas canvas(bitmap);
270
271    blur_path(&canvas, path, gaussianSigma);
272    readback(&canvas, result, resultCount);
273}
274
275#if SK_SUPPORT_GPU
276static bool gpu_blur_path(GrContextFactory* factory, const SkPath& path,
277                          SkScalar gaussianSigma,
278                          int* result, int resultCount) {
279
280    GrContext* grContext = factory->get(GrContextFactory::kNative_GLContextType);
281    if (NULL == grContext) {
282        return false;
283    }
284
285    GrTextureDesc desc;
286    desc.fConfig = kSkia8888_GrPixelConfig;
287    desc.fFlags = kRenderTarget_GrTextureFlagBit;
288    desc.fWidth = resultCount;
289    desc.fHeight = 30;
290    desc.fSampleCnt = 0;
291
292    SkAutoTUnref<GrTexture> texture(grContext->createUncachedTexture(desc, NULL, 0));
293    SkAutoTUnref<SkGpuDevice> device(SkNEW_ARGS(SkGpuDevice, (grContext, texture.get())));
294    SkCanvas canvas(device.get());
295
296    blur_path(&canvas, path, gaussianSigma);
297    readback(&canvas, result, resultCount);
298    return true;
299}
300#endif
301
302#if WRITE_CSV
303static void write_as_csv(const char* label, SkScalar scale, int* data, int count) {
304    SkDebugf("%s_%.2f,", label, scale);
305    for (int i = 0; i < count-1; ++i) {
306        SkDebugf("%d,", data[i]);
307    }
308    SkDebugf("%d\n", data[count-1]);
309}
310#endif
311
312static bool match(int* first, int* second, int count, int tol) {
313    int delta;
314    for (int i = 0; i < count; ++i) {
315        delta = first[i] - second[i];
316        if (delta > tol || delta < -tol) {
317            return false;
318        }
319    }
320
321    return true;
322}
323
324// Test out the normal blur style with a wide range of sigmas
325static void test_sigma_range(skiatest::Reporter* reporter, GrContextFactory* factory) {
326
327    static const int kSize = 100;
328
329    // The geometry is offset a smidge to trigger:
330    // https://code.google.com/p/chromium/issues/detail?id=282418
331    SkPath rectPath;
332    rectPath.addRect(0.3f, 0.3f, 100.3f, 100.3f);
333
334    SkPoint polyPts[] = {
335        { 0.3f, 0.3f },
336        { 100.3f, 0.3f },
337        { 100.3f, 100.3f },
338        { 0.3f, 100.3f },
339        { 2.3f, 50.3f }     // a little divet to throw off the rect special case
340    };
341    SkPath polyPath;
342    polyPath.addPoly(polyPts, SK_ARRAY_COUNT(polyPts), true);
343
344    int rectSpecialCaseResult[kSize];
345    int generalCaseResult[kSize];
346#if SK_SUPPORT_GPU
347    int gpuResult[kSize];
348#endif
349    int groundTruthResult[kSize];
350    int bruteForce1DResult[kSize];
351
352    SkScalar sigma = 10.0f;
353
354    for (int i = 0; i < 4; ++i, sigma /= 10) {
355
356        cpu_blur_path(rectPath, sigma, rectSpecialCaseResult, kSize);
357        cpu_blur_path(polyPath, sigma, generalCaseResult, kSize);
358#if SK_SUPPORT_GPU
359        bool haveGPUResult = gpu_blur_path(factory, rectPath, sigma, gpuResult, kSize);
360#endif
361        ground_truth_2d(100, 100, sigma, groundTruthResult, kSize);
362        brute_force_1d(-50.0f, 50.0f, sigma, bruteForce1DResult, kSize);
363
364        REPORTER_ASSERT(reporter, match(rectSpecialCaseResult, bruteForce1DResult, kSize, 5));
365        REPORTER_ASSERT(reporter, match(generalCaseResult, bruteForce1DResult, kSize, 15));
366#if SK_SUPPORT_GPU
367        if (haveGPUResult) {
368            // 1 works everywhere but: Ubuntu13 & Nexus4
369            REPORTER_ASSERT(reporter, match(gpuResult, bruteForce1DResult, kSize, 10));
370        }
371#endif
372        REPORTER_ASSERT(reporter, match(groundTruthResult, bruteForce1DResult, kSize, 1));
373
374#if WRITE_CSV
375        write_as_csv("RectSpecialCase", sigma, rectSpecialCaseResult, kSize);
376        write_as_csv("GeneralCase", sigma, generalCaseResult, kSize);
377#if SK_SUPPORT_GPU
378        write_as_csv("GPU", sigma, gpuResult, kSize);
379#endif
380        write_as_csv("GroundTruth2D", sigma, groundTruthResult, kSize);
381        write_as_csv("BruteForce1D", sigma, bruteForce1DResult, kSize);
382#endif
383    }
384}
385
386///////////////////////////////////////////////////////////////////////////////////////////
387
388static SkBlurQuality blurMaskFilterFlags_as_quality(uint32_t blurMaskFilterFlags) {
389    return (blurMaskFilterFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
390            kHigh_SkBlurQuality : kLow_SkBlurQuality;
391}
392
393static uint32_t blurMaskFilterFlags_to_blurDrawLooperFlags(uint32_t bmf) {
394    const struct {
395        uint32_t fBlurMaskFilterFlag;
396        uint32_t fBlurDrawLooperFlag;
397    } pairs[] = {
398        { SkBlurMaskFilter::kIgnoreTransform_BlurFlag, SkBlurDrawLooper::kIgnoreTransform_BlurFlag },
399        { SkBlurMaskFilter::kHighQuality_BlurFlag,     SkBlurDrawLooper::kHighQuality_BlurFlag },
400    };
401
402    uint32_t bdl = 0;
403    for (size_t i = 0; i < SK_ARRAY_COUNT(pairs); ++i) {
404        if (bmf & pairs[i].fBlurMaskFilterFlag) {
405            bdl |= pairs[i].fBlurDrawLooperFlag;
406        }
407    }
408    return bdl;
409}
410
411static void test_blurDrawLooper(skiatest::Reporter* reporter, SkScalar sigma,
412                                SkBlurStyle style, uint32_t blurMaskFilterFlags) {
413    if (kNormal_SkBlurStyle != style) {
414        return; // blurdrawlooper only supports normal
415    }
416
417    const SkColor color = 0xFF335577;
418    const SkScalar dx = 10;
419    const SkScalar dy = -5;
420    const SkBlurQuality quality = blurMaskFilterFlags_as_quality(blurMaskFilterFlags);
421    uint32_t flags = blurMaskFilterFlags_to_blurDrawLooperFlags(blurMaskFilterFlags);
422
423    SkAutoTUnref<SkDrawLooper> lp(SkBlurDrawLooper::Create(color, sigma, dx, dy, flags));
424
425    const bool expectSuccess = sigma > 0 &&
426                               0 == (flags & SkBlurDrawLooper::kIgnoreTransform_BlurFlag);
427
428    if (NULL == lp.get()) {
429        REPORTER_ASSERT(reporter, sigma <= 0);
430    } else {
431        SkDrawLooper::BlurShadowRec rec;
432        bool success = lp->asABlurShadow(&rec);
433        REPORTER_ASSERT(reporter, success == expectSuccess);
434        if (success) {
435            REPORTER_ASSERT(reporter, rec.fSigma == sigma);
436            REPORTER_ASSERT(reporter, rec.fOffset.x() == dx);
437            REPORTER_ASSERT(reporter, rec.fOffset.y() == dy);
438            REPORTER_ASSERT(reporter, rec.fColor == color);
439            REPORTER_ASSERT(reporter, rec.fStyle == style);
440            REPORTER_ASSERT(reporter, rec.fQuality == quality);
441        }
442    }
443}
444
445static void test_delete_looper(skiatest::Reporter* reporter, SkDrawLooper* lp, SkScalar sigma,
446                               SkBlurStyle style, SkBlurQuality quality, bool expectSuccess) {
447    SkDrawLooper::BlurShadowRec rec;
448    bool success = lp->asABlurShadow(&rec);
449    REPORTER_ASSERT(reporter, success == expectSuccess);
450    if (success != expectSuccess) {
451        lp->asABlurShadow(&rec);
452    }
453    if (success) {
454        REPORTER_ASSERT(reporter, rec.fSigma == sigma);
455        REPORTER_ASSERT(reporter, rec.fStyle == style);
456        REPORTER_ASSERT(reporter, rec.fQuality == quality);
457    }
458    lp->unref();
459}
460
461static void make_noop_layer(SkLayerDrawLooper::Builder* builder) {
462    SkLayerDrawLooper::LayerInfo info;
463
464    info.fPaintBits = 0;
465    info.fColorMode = SkXfermode::kDst_Mode;
466    builder->addLayer(info);
467}
468
469static void make_blur_layer(SkLayerDrawLooper::Builder* builder, SkMaskFilter* mf) {
470    SkLayerDrawLooper::LayerInfo info;
471
472    info.fPaintBits = SkLayerDrawLooper::kMaskFilter_Bit;
473    info.fColorMode = SkXfermode::kSrc_Mode;
474    SkPaint* paint = builder->addLayer(info);
475    paint->setMaskFilter(mf);
476}
477
478static void test_layerDrawLooper(skiatest::Reporter* reporter, SkMaskFilter* mf, SkScalar sigma,
479                                 SkBlurStyle style, SkBlurQuality quality, bool expectSuccess) {
480
481    SkLayerDrawLooper::LayerInfo info;
482    SkLayerDrawLooper::Builder builder;
483
484    // 1 layer is too few
485    make_noop_layer(&builder);
486    test_delete_looper(reporter, builder.detachLooper(), sigma, style, quality, false);
487
488    // 2 layers is good, but need blur
489    make_noop_layer(&builder);
490    make_noop_layer(&builder);
491    test_delete_looper(reporter, builder.detachLooper(), sigma, style, quality, false);
492
493    // 2 layers is just right
494    make_noop_layer(&builder);
495    make_blur_layer(&builder, mf);
496    test_delete_looper(reporter, builder.detachLooper(), sigma, style, quality, expectSuccess);
497
498    // 3 layers is too many
499    make_noop_layer(&builder);
500    make_blur_layer(&builder, mf);
501    make_noop_layer(&builder);
502    test_delete_looper(reporter, builder.detachLooper(), sigma, style, quality, false);
503}
504
505static void test_asABlur(skiatest::Reporter* reporter) {
506    const SkBlurStyle styles[] = {
507        kNormal_SkBlurStyle, kSolid_SkBlurStyle, kOuter_SkBlurStyle, kInner_SkBlurStyle
508    };
509    const SkScalar sigmas[] = {
510        // values <= 0 should not success for a blur
511        -1, 0, 0.5f, 2
512    };
513
514    // Test asABlur for SkBlurMaskFilter
515    //
516    for (size_t i = 0; i < SK_ARRAY_COUNT(styles); ++i) {
517        const SkBlurStyle style = (SkBlurStyle)styles[i];
518        for (size_t j = 0; j < SK_ARRAY_COUNT(sigmas); ++j) {
519            const SkScalar sigma = sigmas[j];
520            for (int flags = 0; flags <= SkBlurMaskFilter::kAll_BlurFlag; ++flags) {
521                const SkBlurQuality quality = blurMaskFilterFlags_as_quality(flags);
522
523                SkAutoTUnref<SkMaskFilter> mf(SkBlurMaskFilter::Create(style, sigma, flags));
524                if (NULL == mf.get()) {
525                    REPORTER_ASSERT(reporter, sigma <= 0);
526                } else {
527                    REPORTER_ASSERT(reporter, sigma > 0);
528                    SkMaskFilter::BlurRec rec;
529                    bool success = mf->asABlur(&rec);
530                    if (flags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
531                        REPORTER_ASSERT(reporter, !success);
532                    } else {
533                        REPORTER_ASSERT(reporter, success);
534                        REPORTER_ASSERT(reporter, rec.fSigma == sigma);
535                        REPORTER_ASSERT(reporter, rec.fStyle == style);
536                        REPORTER_ASSERT(reporter, rec.fQuality == quality);
537                    }
538                    test_layerDrawLooper(reporter, mf, sigma, style, quality, success);
539                }
540                test_blurDrawLooper(reporter, sigma, style, flags);
541            }
542        }
543    }
544
545    // Test asABlur for SkEmbossMaskFilter -- should never succeed
546    //
547    {
548        SkEmbossMaskFilter::Light light = {
549            { 1, 1, 1 }, 0, 127, 127
550        };
551        for (size_t j = 0; j < SK_ARRAY_COUNT(sigmas); ++j) {
552            const SkScalar sigma = sigmas[j];
553            SkAutoTUnref<SkMaskFilter> mf(SkEmbossMaskFilter::Create(sigma, light));
554            if (mf.get()) {
555                SkMaskFilter::BlurRec rec;
556                bool success = mf->asABlur(&rec);
557                REPORTER_ASSERT(reporter, !success);
558            }
559        }
560    }
561}
562
563///////////////////////////////////////////////////////////////////////////////////////////
564
565DEF_GPUTEST(Blur, reporter, factory) {
566    test_blur_drawing(reporter);
567    test_sigma_range(reporter, factory);
568    test_asABlur(reporter);
569}
570