Update rive-cpp to 2.0 version
[platform/core/uifw/rive-tizen.git] / submodule / skia / tests / BlurTest.cpp
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 "include/core/SkBitmap.h"
9 #include "include/core/SkBlendMode.h"
10 #include "include/core/SkBlurTypes.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkColorPriv.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkMaskFilter.h"
16 #include "include/core/SkMath.h"
17 #include "include/core/SkPaint.h"
18 #include "include/core/SkPath.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkPoint.h"
21 #include "include/core/SkRRect.h"
22 #include "include/core/SkRect.h"
23 #include "include/core/SkRefCnt.h"
24 #include "include/core/SkScalar.h"
25 #include "include/core/SkShader.h"
26 #include "include/core/SkSize.h"
27 #include "include/core/SkSurface.h"
28 #include "include/core/SkTypes.h"
29 #include "include/effects/SkPerlinNoiseShader.h"
30 #include "include/gpu/GrDirectContext.h"
31 #include "include/private/SkFloatBits.h"
32 #include "include/private/SkTPin.h"
33 #include "src/core/SkBlurMask.h"
34 #include "src/core/SkGpuBlurUtils.h"
35 #include "src/core/SkMask.h"
36 #include "src/core/SkMaskFilterBase.h"
37 #include "src/core/SkMathPriv.h"
38 #include "src/effects/SkEmbossMaskFilter.h"
39 #include "tests/Test.h"
40 #include "tools/ToolUtils.h"
41 #include "tools/gpu/GrContextFactory.h"
42
43 #include <math.h>
44 #include <string.h>
45 #include <initializer_list>
46 #include <utility>
47
48 #define WRITE_CSV 0
49
50 ///////////////////////////////////////////////////////////////////////////////
51
52 #define ILLEGAL_MODE    ((SkXfermode::Mode)-1)
53
54 static const int outset = 100;
55 static const SkColor bgColor = SK_ColorWHITE;
56 static const int strokeWidth = 4;
57
58 static void create(SkBitmap* bm, const SkIRect& bound) {
59     bm->allocN32Pixels(bound.width(), bound.height());
60 }
61
62 static void drawBG(SkCanvas* canvas) {
63     canvas->drawColor(bgColor);
64 }
65
66
67 struct BlurTest {
68     void (*addPath)(SkPath*);
69     int viewLen;
70     SkIRect views[9];
71 };
72
73 //Path Draw Procs
74 //Beware that paths themselves my draw differently depending on the clip.
75 static void draw50x50Rect(SkPath* path) {
76     path->addRect(0, 0, SkIntToScalar(50), SkIntToScalar(50));
77 }
78
79 //Tests
80 static BlurTest tests[] = {
81     { draw50x50Rect, 3, {
82         //inner half of blur
83         { 0, 0, 50, 50 },
84         //blur, but no path.
85         { 50 + strokeWidth/2, 50 + strokeWidth/2, 100, 100 },
86         //just an edge
87         { 40, strokeWidth, 60, 50 - strokeWidth },
88     }},
89 };
90
91 /** Assumes that the ref draw was completely inside ref canvas --
92     implies that everything outside is "bgColor".
93     Checks that all overlap is the same and that all non-overlap on the
94     ref is "bgColor".
95  */
96 static bool compare(const SkBitmap& ref, const SkIRect& iref,
97                     const SkBitmap& test, const SkIRect& itest)
98 {
99     const int xOff = itest.fLeft - iref.fLeft;
100     const int yOff = itest.fTop - iref.fTop;
101
102     for (int y = 0; y < test.height(); ++y) {
103         for (int x = 0; x < test.width(); ++x) {
104             SkColor testColor = test.getColor(x, y);
105             int refX = x + xOff;
106             int refY = y + yOff;
107             SkColor refColor;
108             if (refX >= 0 && refX < ref.width() &&
109                 refY >= 0 && refY < ref.height())
110             {
111                 refColor = ref.getColor(refX, refY);
112             } else {
113                 refColor = bgColor;
114             }
115             if (refColor != testColor) {
116                 return false;
117             }
118         }
119     }
120     return true;
121 }
122
123 DEF_TEST(BlurDrawing, reporter) {
124     SkPaint paint;
125     paint.setColor(SK_ColorGRAY);
126     paint.setStyle(SkPaint::kStroke_Style);
127     paint.setStrokeWidth(SkIntToScalar(strokeWidth));
128
129     SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(SkIntToScalar(5));
130     for (int style = 0; style <= kLastEnum_SkBlurStyle; ++style) {
131         SkBlurStyle blurStyle = static_cast<SkBlurStyle>(style);
132
133         for (bool respectCTM : { false, true }) {
134             paint.setMaskFilter(SkMaskFilter::MakeBlur(blurStyle, sigma, respectCTM));
135
136             for (size_t test = 0; test < SK_ARRAY_COUNT(tests); ++test) {
137                 SkPath path;
138                 tests[test].addPath(&path);
139                 SkPath strokedPath;
140                 paint.getFillPath(path, &strokedPath);
141                 SkRect refBound = strokedPath.getBounds();
142                 SkIRect iref;
143                 refBound.roundOut(&iref);
144                 iref.inset(-outset, -outset);
145                 SkBitmap refBitmap;
146                 create(&refBitmap, iref);
147
148                 SkCanvas refCanvas(refBitmap);
149                 refCanvas.translate(SkIntToScalar(-iref.fLeft),
150                                     SkIntToScalar(-iref.fTop));
151                 drawBG(&refCanvas);
152                 refCanvas.drawPath(path, paint);
153
154                 for (int view = 0; view < tests[test].viewLen; ++view) {
155                     SkIRect itest = tests[test].views[view];
156                     SkBitmap testBitmap;
157                     create(&testBitmap, itest);
158
159                     SkCanvas testCanvas(testBitmap);
160                     testCanvas.translate(SkIntToScalar(-itest.fLeft),
161                                          SkIntToScalar(-itest.fTop));
162                     drawBG(&testCanvas);
163                     testCanvas.drawPath(path, paint);
164
165                     REPORTER_ASSERT(reporter,
166                         compare(refBitmap, iref, testBitmap, itest));
167                 }
168             }
169         }
170     }
171 }
172
173 ///////////////////////////////////////////////////////////////////////////////
174
175 // Use SkBlurMask::BlurGroundTruth to blur a 'width' x 'height' solid
176 // white rect. Return the right half of the middle row in 'result'.
177 static void ground_truth_2d(int width, int height,
178                             SkScalar sigma,
179                             int* result, int resultCount) {
180     SkMask src, dst;
181
182     src.fBounds.setWH(width, height);
183     src.fFormat = SkMask::kA8_Format;
184     src.fRowBytes = src.fBounds.width();
185     src.fImage = SkMask::AllocImage(src.computeTotalImageSize());
186
187     memset(src.fImage, 0xff, src.computeTotalImageSize());
188
189     if (!SkBlurMask::BlurGroundTruth(sigma, &dst, src, kNormal_SkBlurStyle)) {
190         return;
191     }
192
193     int midX = dst.fBounds.x() + dst.fBounds.width()/2;
194     int midY = dst.fBounds.y() + dst.fBounds.height()/2;
195     uint8_t* bytes = dst.getAddr8(midX, midY);
196     int i;
197     for (i = 0; i < dst.fBounds.width()-(midX-dst.fBounds.fLeft); ++i) {
198         if (i < resultCount) {
199             result[i] = bytes[i];
200         }
201     }
202     for ( ; i < resultCount; ++i) {
203         result[i] = 0;
204     }
205
206     SkMask::FreeImage(src.fImage);
207     SkMask::FreeImage(dst.fImage);
208 }
209
210 // Implement a step function that is 255 between min and max; 0 elsewhere.
211 static int step(int x, SkScalar min, SkScalar max) {
212     if (min < x && x < max) {
213         return 255;
214     }
215     return 0;
216 }
217
218 // Implement a Gaussian function with 0 mean and std.dev. of 'sigma'.
219 static float gaussian(int x, SkScalar sigma) {
220     float k = SK_Scalar1/(sigma * sqrtf(2.0f*SK_ScalarPI));
221     float exponent = -(x * x) / (2 * sigma * sigma);
222     return k * expf(exponent);
223 }
224
225 // Perform a brute force convolution of a step function with a Gaussian.
226 // Return the right half in 'result'
227 static void brute_force_1d(SkScalar stepMin, SkScalar stepMax,
228                            SkScalar gaussianSigma,
229                            int* result, int resultCount) {
230
231     int gaussianRange = SkScalarCeilToInt(10 * gaussianSigma);
232
233     for (int i = 0; i < resultCount; ++i) {
234         SkScalar sum = 0.0f;
235         for (int j = -gaussianRange; j < gaussianRange; ++j) {
236             sum += gaussian(j, gaussianSigma) * step(i-j, stepMin, stepMax);
237         }
238
239         result[i] = SkTPin(SkClampPos(int(sum + 0.5f)), 0, 255);
240     }
241 }
242
243 static void blur_path(SkCanvas* canvas, const SkPath& path,
244                       SkScalar gaussianSigma) {
245
246     SkScalar midX = path.getBounds().centerX();
247     SkScalar midY = path.getBounds().centerY();
248
249     canvas->translate(-midX, -midY);
250
251     SkPaint blurPaint;
252     blurPaint.setColor(SK_ColorWHITE);
253     blurPaint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, gaussianSigma));
254
255     canvas->drawColor(SK_ColorBLACK);
256     canvas->drawPath(path, blurPaint);
257 }
258
259 // Readback the blurred draw results from the canvas
260 static void readback(const SkBitmap& src, int* result, int resultCount) {
261     SkBitmap readback;
262     readback.allocN32Pixels(resultCount, 30);
263     SkPixmap pm;
264     readback.peekPixels(&pm);
265     src.readPixels(pm, 0, 0);
266
267     const SkPMColor* pixels = pm.addr32(0, 15);
268
269     for (int i = 0; i < resultCount; ++i) {
270         result[i] = SkColorGetR(pixels[i]);
271     }
272 }
273
274 // Draw a blurred version of the provided path.
275 // Return the right half of the middle row in 'result'.
276 static void cpu_blur_path(const SkPath& path, SkScalar gaussianSigma,
277                           int* result, int resultCount) {
278
279     SkBitmap bitmap;
280     bitmap.allocN32Pixels(resultCount, 30);
281     SkCanvas canvas(bitmap);
282
283     blur_path(&canvas, path, gaussianSigma);
284     readback(bitmap, result, resultCount);
285 }
286
287 #if WRITE_CSV
288 static void write_as_csv(const char* label, SkScalar scale, int* data, int count) {
289     SkDebugf("%s_%.2f,", label, scale);
290     for (int i = 0; i < count-1; ++i) {
291         SkDebugf("%d,", data[i]);
292     }
293     SkDebugf("%d\n", data[count-1]);
294 }
295 #endif
296
297 static bool match(int* first, int* second, int count, int tol) {
298     int delta;
299     for (int i = 0; i < count; ++i) {
300         delta = first[i] - second[i];
301         if (delta > tol || delta < -tol) {
302             return false;
303         }
304     }
305
306     return true;
307 }
308
309 // Test out the normal blur style with a wide range of sigmas
310 DEF_TEST(BlurSigmaRange, reporter) {
311     static const int kSize = 100;
312
313     // The geometry is offset a smidge to trigger:
314     // https://code.google.com/p/chromium/issues/detail?id=282418
315     SkPath rectPath;
316     rectPath.addRect(0.3f, 0.3f, 100.3f, 100.3f);
317
318     SkPoint polyPts[] = {
319         { 0.3f, 0.3f },
320         { 100.3f, 0.3f },
321         { 100.3f, 100.3f },
322         { 0.3f, 100.3f },
323         { 2.3f, 50.3f }     // a little divet to throw off the rect special case
324     };
325     SkPath polyPath;
326     polyPath.addPoly(polyPts, SK_ARRAY_COUNT(polyPts), true);
327
328     int rectSpecialCaseResult[kSize];
329     int generalCaseResult[kSize];
330     int groundTruthResult[kSize];
331     int bruteForce1DResult[kSize];
332
333     SkScalar sigma = 10.0f;
334
335     for (int i = 0; i < 4; ++i, sigma /= 10) {
336
337         cpu_blur_path(rectPath, sigma, rectSpecialCaseResult, kSize);
338         cpu_blur_path(polyPath, sigma, generalCaseResult, kSize);
339
340         ground_truth_2d(100, 100, sigma, groundTruthResult, kSize);
341         brute_force_1d(-50.0f, 50.0f, sigma, bruteForce1DResult, kSize);
342
343         REPORTER_ASSERT(reporter, match(rectSpecialCaseResult, bruteForce1DResult, kSize, 5));
344         REPORTER_ASSERT(reporter, match(generalCaseResult, bruteForce1DResult, kSize, 15));
345         REPORTER_ASSERT(reporter, match(groundTruthResult, bruteForce1DResult, kSize, 1));
346
347 #if WRITE_CSV
348         write_as_csv("RectSpecialCase", sigma, rectSpecialCaseResult, kSize);
349         write_as_csv("GeneralCase", sigma, generalCaseResult, kSize);
350         write_as_csv("GPU", sigma, gpuResult, kSize);
351         write_as_csv("GroundTruth2D", sigma, groundTruthResult, kSize);
352         write_as_csv("BruteForce1D", sigma, bruteForce1DResult, kSize);
353 #endif
354     }
355 }
356
357 ///////////////////////////////////////////////////////////////////////////////////////////
358
359 DEF_TEST(BlurAsABlur, reporter) {
360     const SkBlurStyle styles[] = {
361         kNormal_SkBlurStyle, kSolid_SkBlurStyle, kOuter_SkBlurStyle, kInner_SkBlurStyle
362     };
363     const SkScalar sigmas[] = {
364         // values <= 0 should not success for a blur
365         -1, 0, 0.5f, 2
366     };
367
368     // Test asABlur for SkBlurMaskFilter
369     //
370     for (size_t i = 0; i < SK_ARRAY_COUNT(styles); ++i) {
371         const SkBlurStyle style = styles[i];
372         for (size_t j = 0; j < SK_ARRAY_COUNT(sigmas); ++j) {
373             const SkScalar sigma = sigmas[j];
374             for (bool respectCTM : { false, true }) {
375                 sk_sp<SkMaskFilter> mf(SkMaskFilter::MakeBlur(style, sigma, respectCTM));
376                 if (nullptr == mf.get()) {
377                     REPORTER_ASSERT(reporter, sigma <= 0);
378                 } else {
379                     REPORTER_ASSERT(reporter, sigma > 0);
380                     SkMaskFilterBase::BlurRec rec;
381                     bool success = as_MFB(mf)->asABlur(&rec);
382                     if (respectCTM) {
383                         REPORTER_ASSERT(reporter, success);
384                         REPORTER_ASSERT(reporter, rec.fSigma == sigma);
385                         REPORTER_ASSERT(reporter, rec.fStyle == style);
386                     } else {
387                         REPORTER_ASSERT(reporter, !success);
388                     }
389
390                     const SkRect src = {0, 0, 100, 100};
391                     const auto dst = mf->approximateFilteredBounds(src);
392
393                     // This is a very conservative test. With more knowledge, we could
394                     // consider more stringent tests.
395                     REPORTER_ASSERT(reporter, dst.contains(src));
396                 }
397             }
398         }
399     }
400
401     // Test asABlur for SkEmbossMaskFilter -- should never succeed
402     //
403     {
404         SkEmbossMaskFilter::Light light = {
405             { 1, 1, 1 }, 0, 127, 127
406         };
407         for (size_t j = 0; j < SK_ARRAY_COUNT(sigmas); ++j) {
408             const SkScalar sigma = sigmas[j];
409             auto mf(SkEmbossMaskFilter::Make(sigma, light));
410             if (mf) {
411                 SkMaskFilterBase::BlurRec rec;
412                 bool success = as_MFB(mf)->asABlur(&rec);
413                 REPORTER_ASSERT(reporter, !success);
414             }
415         }
416     }
417 }
418
419 // This exercises the problem discovered in crbug.com/570232. The return value from
420 // SkBlurMask::BoxBlur wasn't being checked in SkBlurMaskFilter.cpp::GrRRectBlurEffect::Create
421 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SmallBoxBlurBug, reporter, ctxInfo) {
422
423     SkImageInfo info = SkImageInfo::MakeN32Premul(128, 128);
424     auto surface(SkSurface::MakeRenderTarget(ctxInfo.directContext(), SkBudgeted::kNo, info));
425     SkCanvas* canvas = surface->getCanvas();
426
427     SkRect r = SkRect::MakeXYWH(10, 10, 100, 100);
428     SkRRect rr = SkRRect::MakeRectXY(r, 10, 10);
429
430     SkPaint p;
431     p.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, 0.01f));
432
433     canvas->drawRRect(rr, p);
434 }
435
436 DEF_TEST(BlurredRRectNinePatchComputation, reporter) {
437     const SkRect r = SkRect::MakeXYWH(10, 10, 100, 100);
438     static const SkScalar kBlurRad = 3.0f;
439
440     bool ninePatchable;
441     SkRRect rrectToDraw;
442     SkISize size;
443     SkScalar rectXs[SkGpuBlurUtils::kBlurRRectMaxDivisions],
444              rectYs[SkGpuBlurUtils::kBlurRRectMaxDivisions];
445     SkScalar texXs[SkGpuBlurUtils::kBlurRRectMaxDivisions],
446              texYs[SkGpuBlurUtils::kBlurRRectMaxDivisions];
447
448     // not nine-patchable
449     {
450         SkVector radii[4] = { { 100, 100 }, { 0, 0 }, { 100, 100 }, { 0, 0 } };
451
452         SkRRect rr;
453         rr.setRectRadii(r, radii);
454
455         ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(rr, rr, kBlurRad, kBlurRad,
456                                                                   &rrectToDraw, &size,
457                                                                   rectXs, rectYs, texXs, texYs);
458         REPORTER_ASSERT(reporter, !ninePatchable);
459     }
460
461     // simple circular
462     {
463         static const SkScalar kCornerRad = 10.0f;
464         SkRRect rr;
465         rr.setRectXY(r, kCornerRad, kCornerRad);
466
467         ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(rr, rr, kBlurRad, kBlurRad,
468                                                                   &rrectToDraw, &size,
469                                                                   rectXs, rectYs, texXs, texYs);
470
471         static const SkScalar kAns = 12.0f * kBlurRad + 2.0f * kCornerRad + 1.0f;
472         REPORTER_ASSERT(reporter, ninePatchable);
473         REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fWidth), kAns));
474         REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fHeight), kAns));
475     }
476
477     // simple elliptical
478     {
479         static const SkScalar kXCornerRad = 2.0f;
480         static const SkScalar kYCornerRad = 10.0f;
481         SkRRect rr;
482         rr.setRectXY(r, kXCornerRad, kYCornerRad);
483
484         ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(rr, rr, kBlurRad, kBlurRad,
485                                                                   &rrectToDraw, &size,
486                                                                   rectXs, rectYs, texXs, texYs);
487
488         static const SkScalar kXAns = 12.0f * kBlurRad + 2.0f * kXCornerRad + 1.0f;
489         static const SkScalar kYAns = 12.0f * kBlurRad + 2.0f * kYCornerRad + 1.0f;
490
491         REPORTER_ASSERT(reporter, ninePatchable);
492         REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fWidth), kXAns));
493         REPORTER_ASSERT(reporter, SkScalarNearlyEqual(SkIntToScalar(size.fHeight), kYAns));
494     }
495 }
496
497 // https://crbugs.com/787712
498 DEF_TEST(EmbossPerlinCrash, reporter) {
499     SkPaint p;
500
501     static constexpr SkEmbossMaskFilter::Light light = {
502         { 1, 1, 1 }, 0, 127, 127
503     };
504     p.setMaskFilter(SkEmbossMaskFilter::Make(1, light));
505     p.setShader(SkPerlinNoiseShader::MakeFractalNoise(1.0f, 1.0f, 2, 0.0f));
506
507     sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(100, 100);
508     surface->getCanvas()->drawPaint(p);
509 }
510
511 ///////////////////////////////////////////////////////////////////////////////////////////
512
513 DEF_TEST(BlurZeroSigma, reporter) {
514     auto surf = SkSurface::MakeRasterN32Premul(20, 20);
515     SkPaint paint;
516     paint.setAntiAlias(true);
517
518     const SkIRect ir = { 5, 5, 15, 15 };
519     const SkRect r = SkRect::Make(ir);
520
521     const SkScalar sigmas[] = { 0, SkBits2Float(1) };
522     // if sigma is zero (or nearly so), we need to draw correctly (unblurred) and not crash
523     // or assert.
524     for (auto sigma : sigmas) {
525         paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma));
526         surf->getCanvas()->drawRect(r, paint);
527
528         ToolUtils::PixelIter iter(surf.get());
529         SkIPoint  loc;
530         while (const SkPMColor* p = (const SkPMColor*)iter.next(&loc)) {
531             if (ir.contains(loc.fX, loc.fY)) {
532                 // inside the rect we draw (opaque black)
533                 REPORTER_ASSERT(reporter, *p == SkPackARGB32(0xFF, 0, 0, 0));
534             } else {
535                 // outside the rect we didn't draw at all, no blurred edges
536                 REPORTER_ASSERT(reporter, *p == 0);
537             }
538         }
539     }
540 }
541
542
543 ///////////////////////////////////////////////////////////////////////////////////////////
544
545 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(BlurMaskBiggerThanDest, reporter, ctxInfo) {
546     auto context = ctxInfo.directContext();
547
548     SkImageInfo ii = SkImageInfo::Make(32, 32, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
549
550     sk_sp<SkSurface> dst(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, ii));
551     if (!dst) {
552         ERRORF(reporter, "Could not create surface for test.");
553         return;
554     }
555
556     SkPaint p;
557     p.setColor(SK_ColorRED);
558     p.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, 3));
559
560     SkCanvas* canvas = dst->getCanvas();
561
562     canvas->clear(SK_ColorBLACK);
563     canvas->drawCircle(SkPoint::Make(16, 16), 8, p);
564
565     SkBitmap readback;
566     SkAssertResult(readback.tryAllocPixels(ii));
567
568     canvas->readPixels(readback, 0, 0);
569     REPORTER_ASSERT(reporter, SkColorGetR(readback.getColor(15, 15)) > 128);
570     REPORTER_ASSERT(reporter, SkColorGetG(readback.getColor(15, 15)) == 0);
571     REPORTER_ASSERT(reporter, SkColorGetB(readback.getColor(15, 15)) == 0);
572     REPORTER_ASSERT(reporter, readback.getColor(31, 31) == SK_ColorBLACK);
573 }
574
575 DEF_TEST(zero_blur, reporter) {
576     SkBitmap alpha, bitmap;
577
578     SkPaint paint;
579     paint.setMaskFilter(SkMaskFilter::MakeBlur(kOuter_SkBlurStyle, 3));
580     SkIPoint offset;
581     bitmap.extractAlpha(&alpha, &paint, nullptr, &offset);
582 }