1/*
2 * Copyright 2014 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 "sk_tool_utils.h"
9
10#include "Resources.h"
11#include "SkBitmap.h"
12#include "SkCanvas.h"
13#include "SkCommonFlags.h"
14#include "SkFontMgr.h"
15#include "SkFontStyle.h"
16#include "SkImage.h"
17#include "SkPixelRef.h"
18#include "SkPM4f.h"
19#include "SkPoint3.h"
20#include "SkShader.h"
21#include "SkSurface.h"
22#include "SkTestScalerContext.h"
23#include "SkTextBlob.h"
24
25namespace sk_tool_utils {
26
27static const char* platform_os_name() {
28    for (int index = 0; index < FLAGS_key.count(); index += 2) {
29        if (!strcmp("os", FLAGS_key[index])) {
30            return FLAGS_key[index + 1];
31        }
32    }
33    return "";
34}
35
36sk_sp<SkTypeface> emoji_typeface() {
37#if defined(SK_BUILD_FOR_WIN)
38    sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault());
39    const char *colorEmojiFontName = "Segoe UI Emoji";
40    sk_sp<SkTypeface> typeface(fm->matchFamilyStyle(colorEmojiFontName, SkFontStyle()));
41    if (typeface) {
42        return typeface;
43    }
44    sk_sp<SkTypeface> fallback(fm->matchFamilyStyleCharacter(
45        colorEmojiFontName, SkFontStyle(), nullptr /* bcp47 */, 0 /* bcp47Count */,
46        0x1f4b0 /* character: �� */));
47    if (fallback) {
48        return fallback;
49    }
50    // If we don't have Segoe UI Emoji and can't find a fallback, try Segoe UI Symbol.
51    // Windows 7 does not have Segoe UI Emoji; Segoe UI Symbol has the (non - color) emoji.
52    return SkTypeface::MakeFromName("Segoe UI Symbol", SkFontStyle());
53
54#elif defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
55    return SkTypeface::MakeFromName("Apple Color Emoji", SkFontStyle());
56
57#else
58    return MakeResourceAsTypeface("fonts/Funkster.ttf");
59
60#endif
61}
62
63const char* emoji_sample_text() {
64#if defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
65    return "\xF0\x9F\x92\xB0" "\xF0\x9F\x8F\xA1" "\xF0\x9F\x8E\x85"  // ������
66           "\xF0\x9F\x8D\xAA" "\xF0\x9F\x8D\x95" "\xF0\x9F\x9A\x80"  // ������
67           "\xF0\x9F\x9A\xBB" "\xF0\x9F\x92\xA9" "\xF0\x9F\x93\xB7"  // ������
68           "\xF0\x9F\x93\xA6"                                        // ��
69           "\xF0\x9F\x87\xBA" "\xF0\x9F\x87\xB8" "\xF0\x9F\x87\xA6"; // ������
70#else
71    return "Hamburgefons";
72#endif
73}
74
75static bool extra_config_contains(const char* substring) {
76    for (int index = 0; index < FLAGS_key.count(); index += 2) {
77        if (0 == strcmp("extra_config", FLAGS_key[index])
78                && strstr(FLAGS_key[index + 1], substring)) {
79            return true;
80        }
81    }
82    return false;
83}
84
85const char* platform_font_manager() {
86    if (extra_config_contains("GDI")) {
87        return "GDI";
88    }
89    if (extra_config_contains("NativeFonts")){
90        return platform_os_name();
91    }
92    return "";
93}
94
95
96const char* colortype_name(SkColorType ct) {
97    switch (ct) {
98        case kUnknown_SkColorType:      return "Unknown";
99        case kAlpha_8_SkColorType:      return "Alpha_8";
100        case kARGB_4444_SkColorType:    return "ARGB_4444";
101        case kRGB_565_SkColorType:      return "RGB_565";
102        case kRGBA_8888_SkColorType:    return "RGBA_8888";
103        case kBGRA_8888_SkColorType:    return "BGRA_8888";
104        case kRGBA_F16_SkColorType:     return "RGBA_F16";
105        default:
106            SkASSERT(false);
107            return "unexpected colortype";
108    }
109}
110
111SkColor color_to_565(SkColor color) {
112    SkPMColor pmColor = SkPreMultiplyColor(color);
113    U16CPU color16 = SkPixel32ToPixel16(pmColor);
114    return SkPixel16ToColor(color16);
115}
116
117sk_sp<SkTypeface> create_portable_typeface(const char* name, SkFontStyle style) {
118    return create_font(name, style);
119}
120
121void set_portable_typeface(SkPaint* paint, const char* name, SkFontStyle style) {
122    paint->setTypeface(create_font(name, style));
123}
124
125void write_pixels(SkCanvas* canvas, const SkBitmap& bitmap, int x, int y,
126                  SkColorType colorType, SkAlphaType alphaType) {
127    SkBitmap tmp(bitmap);
128    const SkImageInfo info = SkImageInfo::Make(tmp.width(), tmp.height(), colorType, alphaType);
129
130    canvas->writePixels(info, tmp.getPixels(), tmp.rowBytes(), x, y);
131}
132
133sk_sp<SkShader> create_checkerboard_shader(SkColor c1, SkColor c2, int size) {
134    SkBitmap bm;
135    bm.allocPixels(SkImageInfo::MakeS32(2 * size, 2 * size, kPremul_SkAlphaType));
136    bm.eraseColor(c1);
137    bm.eraseArea(SkIRect::MakeLTRB(0, 0, size, size), c2);
138    bm.eraseArea(SkIRect::MakeLTRB(size, size, 2 * size, 2 * size), c2);
139    return SkShader::MakeBitmapShader(
140            bm, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode);
141}
142
143SkBitmap create_checkerboard_bitmap(int w, int h, SkColor c1, SkColor c2, int checkSize) {
144    SkBitmap bitmap;
145    bitmap.allocPixels(SkImageInfo::MakeS32(w, h, kPremul_SkAlphaType));
146    SkCanvas canvas(bitmap);
147
148    sk_tool_utils::draw_checkerboard(&canvas, c1, c2, checkSize);
149    return bitmap;
150}
151
152void draw_checkerboard(SkCanvas* canvas, SkColor c1, SkColor c2, int size) {
153    SkPaint paint;
154    paint.setShader(create_checkerboard_shader(c1, c2, size));
155    paint.setBlendMode(SkBlendMode::kSrc);
156    canvas->drawPaint(paint);
157}
158
159SkBitmap create_string_bitmap(int w, int h, SkColor c, int x, int y,
160                              int textSize, const char* str) {
161    SkBitmap bitmap;
162    bitmap.allocN32Pixels(w, h);
163    SkCanvas canvas(bitmap);
164
165    SkPaint paint;
166    paint.setAntiAlias(true);
167    sk_tool_utils::set_portable_typeface(&paint);
168    paint.setColor(c);
169    paint.setTextSize(SkIntToScalar(textSize));
170
171    canvas.clear(0x00000000);
172    canvas.drawString(str, SkIntToScalar(x), SkIntToScalar(y), paint);
173
174    // Tag data as sRGB (without doing any color space conversion). Color-space aware configs
175    // will process this correctly but legacy configs will render as if this returned N32.
176    SkBitmap result;
177    result.setInfo(SkImageInfo::MakeS32(w, h, kPremul_SkAlphaType));
178    result.setPixelRef(sk_ref_sp(bitmap.pixelRef()), 0, 0);
179    return result;
180}
181
182void add_to_text_blob_w_len(SkTextBlobBuilder* builder, const char* text, size_t len,
183                            const SkPaint& origPaint, SkScalar x, SkScalar y) {
184    SkPaint paint(origPaint);
185    SkTDArray<uint16_t> glyphs;
186
187    glyphs.append(paint.textToGlyphs(text, len, nullptr));
188    paint.textToGlyphs(text, len, glyphs.begin());
189
190    paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
191    const SkTextBlobBuilder::RunBuffer& run = builder->allocRun(paint, glyphs.count(), x, y,
192                                                                nullptr);
193    memcpy(run.glyphs, glyphs.begin(), glyphs.count() * sizeof(uint16_t));
194}
195
196void add_to_text_blob(SkTextBlobBuilder* builder, const char* text,
197                      const SkPaint& origPaint, SkScalar x, SkScalar y) {
198    add_to_text_blob_w_len(builder, text, strlen(text), origPaint, x, y);
199}
200
201SkPath make_star(const SkRect& bounds, int numPts, int step) {
202    SkPath path;
203    path.setFillType(SkPath::kEvenOdd_FillType);
204    path.moveTo(0,-1);
205    for (int i = 1; i < numPts; ++i) {
206        int idx = i*step;
207        SkScalar theta = idx * 2*SK_ScalarPI/numPts + SK_ScalarPI/2;
208        SkScalar x = SkScalarCos(theta);
209        SkScalar y = -SkScalarSin(theta);
210        path.lineTo(x, y);
211    }
212    path.transform(SkMatrix::MakeRectToRect(path.getBounds(), bounds, SkMatrix::kFill_ScaleToFit));
213    return path;
214}
215
216#if !defined(__clang__) && defined(_MSC_VER)
217    // MSVC takes ~2 minutes to compile this function with optimization.
218    // We don't really care to wait that long for this function.
219    #pragma optimize("", off)
220#endif
221void make_big_path(SkPath& path) {
222    #include "BigPathBench.inc"
223}
224
225static float gaussian2d_value(int x, int y, float sigma) {
226    // don't bother with the scale term since we're just going to normalize the
227    // kernel anyways
228    float temp = expf(-(x*x + y*y)/(2*sigma*sigma));
229    return temp;
230}
231
232static float* create_2d_kernel(float sigma, int* filterSize) {
233    // We will actually take 2*halfFilterSize+1 samples (i.e., our filter kernel
234    // sizes are always odd)
235    int halfFilterSize = SkScalarCeilToInt(6*sigma)/2;
236    int wh = *filterSize = 2*halfFilterSize + 1;
237
238    float* temp = new float[wh*wh];
239
240    float filterTot = 0.0f;
241    for (int yOff = 0; yOff < wh; ++yOff) {
242        for (int xOff = 0; xOff < wh; ++xOff) {
243            temp[yOff*wh+xOff] = gaussian2d_value(xOff-halfFilterSize, yOff-halfFilterSize, sigma);
244
245            filterTot += temp[yOff*wh+xOff];
246        }
247    }
248
249    // normalize the kernel
250    for (int yOff = 0; yOff < wh; ++yOff) {
251        for (int xOff = 0; xOff < wh; ++xOff) {
252            temp[yOff*wh+xOff] /= filterTot;
253        }
254    }
255
256    return temp;
257}
258
259static SkPMColor blur_pixel(const SkBitmap& bm, int x, int y, float* kernel, int wh) {
260    SkASSERT(wh & 0x1);
261
262    int halfFilterSize = (wh-1)/2;
263
264    float r = 0.0f, g = 0.0f, b = 0.0f;
265    for (int yOff = 0; yOff < wh; ++yOff) {
266        int ySamp = y + yOff - halfFilterSize;
267
268        if (ySamp < 0) {
269            ySamp = 0;
270        } else if (ySamp > bm.height()-1) {
271            ySamp = bm.height()-1;
272        }
273
274        for (int xOff = 0; xOff < wh; ++xOff) {
275            int xSamp = x + xOff - halfFilterSize;
276
277            if (xSamp < 0) {
278                xSamp = 0;
279            } else if (xSamp > bm.width()-1) {
280                xSamp = bm.width()-1;
281            }
282
283            float filter = kernel[yOff*wh + xOff];
284
285            SkPMColor c = *bm.getAddr32(xSamp, ySamp);
286
287            r += SkGetPackedR32(c) * filter;
288            g += SkGetPackedG32(c) * filter;
289            b += SkGetPackedB32(c) * filter;
290        }
291    }
292
293    U8CPU r8, g8, b8;
294
295    r8 = (U8CPU) (r+0.5f);
296    g8 = (U8CPU) (g+0.5f);
297    b8 = (U8CPU) (b+0.5f);
298
299    return SkPackARGB32(255, r8, g8, b8);
300}
301
302SkBitmap slow_blur(const SkBitmap& src, float sigma) {
303    SkBitmap dst;
304
305    dst.allocN32Pixels(src.width(), src.height(), true);
306
307    int wh;
308    std::unique_ptr<float[]> kernel(create_2d_kernel(sigma, &wh));
309
310    for (int y = 0; y < src.height(); ++y) {
311        for (int x = 0; x < src.width(); ++x) {
312            *dst.getAddr32(x, y) = blur_pixel(src, x, y, kernel.get(), wh);
313        }
314    }
315
316    return dst;
317}
318
319// compute the intersection point between the diagonal and the ellipse in the
320// lower right corner
321static SkPoint intersection(SkScalar w, SkScalar h) {
322    SkASSERT(w > 0.0f || h > 0.0f);
323
324    return SkPoint::Make(w / SK_ScalarSqrt2, h / SK_ScalarSqrt2);
325}
326
327// Use the intersection of the corners' diagonals with their ellipses to shrink
328// the bounding rect
329SkRect compute_central_occluder(const SkRRect& rr) {
330    const SkRect r = rr.getBounds();
331
332    SkScalar newL = r.fLeft, newT = r.fTop, newR = r.fRight, newB = r.fBottom;
333
334    SkVector radii = rr.radii(SkRRect::kUpperLeft_Corner);
335    if (!radii.isZero()) {
336        SkPoint p = intersection(radii.fX, radii.fY);
337
338        newL = SkTMax(newL, r.fLeft + radii.fX - p.fX);
339        newT = SkTMax(newT, r.fTop + radii.fY - p.fY);
340    }
341
342    radii = rr.radii(SkRRect::kUpperRight_Corner);
343    if (!radii.isZero()) {
344        SkPoint p = intersection(radii.fX, radii.fY);
345
346        newR = SkTMin(newR, r.fRight + p.fX - radii.fX);
347        newT = SkTMax(newT, r.fTop + radii.fY - p.fY);
348    }
349
350    radii = rr.radii(SkRRect::kLowerRight_Corner);
351    if (!radii.isZero()) {
352        SkPoint p = intersection(radii.fX, radii.fY);
353
354        newR = SkTMin(newR, r.fRight + p.fX - radii.fX);
355        newB = SkTMin(newB, r.fBottom - radii.fY + p.fY);
356    }
357
358    radii = rr.radii(SkRRect::kLowerLeft_Corner);
359    if (!radii.isZero()) {
360        SkPoint p = intersection(radii.fX, radii.fY);
361
362        newL = SkTMax(newL, r.fLeft + radii.fX - p.fX);
363        newB = SkTMin(newB, r.fBottom - radii.fY + p.fY);
364    }
365
366    return SkRect::MakeLTRB(newL, newT, newR, newB);
367}
368
369// The widest inset rect
370SkRect compute_widest_occluder(const SkRRect& rr) {
371    const SkRect& r = rr.getBounds();
372
373    const SkVector& ul = rr.radii(SkRRect::kUpperLeft_Corner);
374    const SkVector& ur = rr.radii(SkRRect::kUpperRight_Corner);
375    const SkVector& lr = rr.radii(SkRRect::kLowerRight_Corner);
376    const SkVector& ll = rr.radii(SkRRect::kLowerLeft_Corner);
377
378    SkScalar maxT = SkTMax(ul.fY, ur.fY);
379    SkScalar maxB = SkTMax(ll.fY, lr.fY);
380
381    return SkRect::MakeLTRB(r.fLeft, r.fTop + maxT, r.fRight, r.fBottom - maxB);
382
383}
384
385// The tallest inset rect
386SkRect compute_tallest_occluder(const SkRRect& rr) {
387    const SkRect& r = rr.getBounds();
388
389    const SkVector& ul = rr.radii(SkRRect::kUpperLeft_Corner);
390    const SkVector& ur = rr.radii(SkRRect::kUpperRight_Corner);
391    const SkVector& lr = rr.radii(SkRRect::kLowerRight_Corner);
392    const SkVector& ll = rr.radii(SkRRect::kLowerLeft_Corner);
393
394    SkScalar maxL = SkTMax(ul.fX, ll.fX);
395    SkScalar maxR = SkTMax(ur.fX, lr.fX);
396
397    return SkRect::MakeLTRB(r.fLeft + maxL, r.fTop, r.fRight - maxR, r.fBottom);
398}
399
400bool copy_to(SkBitmap* dst, SkColorType dstColorType, const SkBitmap& src) {
401    SkPixmap srcPM;
402    if (!src.peekPixels(&srcPM)) {
403        return false;
404    }
405
406    SkBitmap tmpDst;
407    SkImageInfo dstInfo = srcPM.info().makeColorType(dstColorType);
408    if (!tmpDst.setInfo(dstInfo)) {
409        return false;
410    }
411
412    if (!tmpDst.tryAllocPixels()) {
413        return false;
414    }
415
416    SkPixmap dstPM;
417    if (!tmpDst.peekPixels(&dstPM)) {
418        return false;
419    }
420
421    if (!srcPM.readPixels(dstPM)) {
422        return false;
423    }
424
425    dst->swap(tmpDst);
426    return true;
427}
428
429void copy_to_g8(SkBitmap* dst, const SkBitmap& src) {
430    SkASSERT(kBGRA_8888_SkColorType == src.colorType() ||
431             kRGBA_8888_SkColorType == src.colorType());
432
433    SkImageInfo grayInfo = src.info().makeColorType(kGray_8_SkColorType);
434    dst->allocPixels(grayInfo);
435    uint8_t* dst8 = (uint8_t*)dst->getPixels();
436    const uint32_t* src32 = (const uint32_t*)src.getPixels();
437
438    const int w = src.width();
439    const int h = src.height();
440    const bool isBGRA = (kBGRA_8888_SkColorType == src.colorType());
441    for (int y = 0; y < h; ++y) {
442        if (isBGRA) {
443            // BGRA
444            for (int x = 0; x < w; ++x) {
445                uint32_t s = src32[x];
446                dst8[x] = SkComputeLuminance((s >> 16) & 0xFF, (s >> 8) & 0xFF, s & 0xFF);
447            }
448        } else {
449            // RGBA
450            for (int x = 0; x < w; ++x) {
451                uint32_t s = src32[x];
452                dst8[x] = SkComputeLuminance(s & 0xFF, (s >> 8) & 0xFF, (s >> 16) & 0xFF);
453            }
454        }
455        src32 = (const uint32_t*)((const char*)src32 + src.rowBytes());
456        dst8 += dst->rowBytes();
457    }
458}
459
460    //////////////////////////////////////////////////////////////////////////////////////////////
461
462    static int scale255(float x) {
463        return sk_float_round2int(x * 255);
464    }
465
466    static unsigned diff(const SkColorType ct, const void* a, const void* b) {
467        int dr = 0,
468            dg = 0,
469            db = 0,
470            da = 0;
471        switch (ct) {
472            case kRGBA_8888_SkColorType:
473            case kBGRA_8888_SkColorType: {
474                SkPMColor c0 = *(const SkPMColor*)a;
475                SkPMColor c1 = *(const SkPMColor*)b;
476                dr = SkGetPackedR32(c0) - SkGetPackedR32(c1);
477                dg = SkGetPackedG32(c0) - SkGetPackedG32(c1);
478                db = SkGetPackedB32(c0) - SkGetPackedB32(c1);
479                da = SkGetPackedA32(c0) - SkGetPackedA32(c1);
480            } break;
481            case kRGB_565_SkColorType: {
482                uint16_t c0 = *(const uint16_t*)a;
483                uint16_t c1 = *(const uint16_t*)b;
484                dr = SkGetPackedR16(c0) - SkGetPackedR16(c1);
485                dg = SkGetPackedG16(c0) - SkGetPackedG16(c1);
486                db = SkGetPackedB16(c0) - SkGetPackedB16(c1);
487            } break;
488            case kARGB_4444_SkColorType: {
489                uint16_t c0 = *(const uint16_t*)a;
490                uint16_t c1 = *(const uint16_t*)b;
491                dr = SkGetPackedR4444(c0) - SkGetPackedR4444(c1);
492                dg = SkGetPackedG4444(c0) - SkGetPackedG4444(c1);
493                db = SkGetPackedB4444(c0) - SkGetPackedB4444(c1);
494                da = SkGetPackedA4444(c0) - SkGetPackedA4444(c1);
495            } break;
496            case kAlpha_8_SkColorType:
497            case kGray_8_SkColorType:
498                da = (const uint8_t*)a - (const uint8_t*)b;
499                break;
500            case kRGBA_F16_SkColorType: {
501                const SkPM4f* c0 = (const SkPM4f*)a;
502                const SkPM4f* c1 = (const SkPM4f*)b;
503                dr = scale255(c0->r() - c1->r());
504                dg = scale255(c0->g() - c1->g());
505                db = scale255(c0->b() - c1->b());
506                da = scale255(c0->a() - c1->a());
507            } break;
508            default:
509                return 0;
510        }
511        dr = SkAbs32(dr);
512        dg = SkAbs32(dg);
513        db = SkAbs32(db);
514        da = SkAbs32(da);
515        return SkMax32(dr, SkMax32(dg, SkMax32(db, da)));
516    }
517
518    bool equal_pixels(const SkPixmap& a, const SkPixmap& b, unsigned maxDiff,
519                      bool respectColorSpace) {
520        if (a.width() != b.width() ||
521            a.height() != b.height() ||
522            a.colorType() != b.colorType() ||
523            (respectColorSpace && (a.colorSpace() != b.colorSpace())))
524        {
525            return false;
526        }
527
528        for (int y = 0; y < a.height(); ++y) {
529            const char* aptr = (const char*)a.addr(0, y);
530            const char* bptr = (const char*)b.addr(0, y);
531            if (memcmp(aptr, bptr, a.width() * a.info().bytesPerPixel())) {
532                for (int x = 0; x < a.width(); ++x) {
533                    if (diff(a.colorType(), a.addr(x, y), b.addr(x, y)) > maxDiff) {
534                        return false;
535                    }
536                }
537            }
538            aptr += a.rowBytes();
539            bptr += b.rowBytes();
540        }
541        return true;
542    }
543
544    bool equal_pixels(const SkBitmap& bm0, const SkBitmap& bm1, unsigned maxDiff,
545                      bool respectColorSpaces) {
546        SkPixmap pm0, pm1;
547        return bm0.peekPixels(&pm0) && bm1.peekPixels(&pm1) &&
548               equal_pixels(pm0, pm1, maxDiff, respectColorSpaces);
549    }
550
551    bool equal_pixels(const SkImage* a, const SkImage* b, unsigned maxDiff,
552                      bool respectColorSpaces) {
553        // ensure that peekPixels will succeed
554        auto imga = a->makeRasterImage();
555        auto imgb = b->makeRasterImage();
556        a = imga.get();
557        b = imgb.get();
558
559        SkPixmap pm0, pm1;
560        return a->peekPixels(&pm0) && b->peekPixels(&pm1) &&
561               equal_pixels(pm0, pm1, maxDiff, respectColorSpaces);
562    }
563
564    sk_sp<SkSurface> makeSurface(SkCanvas* canvas, const SkImageInfo& info,
565                                 const SkSurfaceProps* props) {
566        auto surf = canvas->makeSurface(info, props);
567        if (!surf) {
568            surf = SkSurface::MakeRaster(info, props);
569        }
570        return surf;
571    }
572}  // namespace sk_tool_utils
573