Coverage Report

Created: 2024-05-20 07:14

/src/skia/tools/ToolUtils.cpp
Line
Count
Source (jump to first uncovered line)
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 "tools/ToolUtils.h"
9
10
#include "include/core/SkAlphaType.h"
11
#include "include/core/SkBitmap.h"
12
#include "include/core/SkBlendMode.h"
13
#include "include/core/SkCanvas.h"
14
#include "include/core/SkColorPriv.h"
15
#include "include/core/SkColorSpace.h"
16
#include "include/core/SkColorType.h"
17
#include "include/core/SkFont.h"
18
#include "include/core/SkFontTypes.h"
19
#include "include/core/SkImage.h"
20
#include "include/core/SkImageInfo.h"
21
#include "include/core/SkMatrix.h"
22
#include "include/core/SkPaint.h"
23
#include "include/core/SkPath.h"
24
#include "include/core/SkPathBuilder.h"
25
#include "include/core/SkPathTypes.h"
26
#include "include/core/SkPicture.h"
27
#include "include/core/SkPixelRef.h"  // IWYU pragma: keep
28
#include "include/core/SkPixmap.h"
29
#include "include/core/SkPoint3.h"
30
#include "include/core/SkRefCnt.h"
31
#include "include/core/SkSamplingOptions.h"
32
#include "include/core/SkStream.h"
33
#include "include/core/SkSurface.h"
34
#include "include/core/SkTextBlob.h"
35
#include "include/core/SkTileMode.h"
36
#include "include/core/SkTypeface.h"
37
#include "include/effects/SkGradientShader.h"
38
#include "include/private/SkColorData.h"
39
#include "include/private/base/SkCPUTypes.h"
40
#include "include/private/base/SkTemplates.h"
41
#include "src/core/SkFontPriv.h"
42
#include "tools/SkMetaData.h"
43
44
#include <cmath>
45
#include <cstring>
46
47
#ifdef SK_BUILD_FOR_WIN
48
#include "include/ports/SkTypeface_win.h"
49
#endif
50
51
using namespace skia_private;
52
53
namespace ToolUtils {
54
55
0
const char* alphatype_name(SkAlphaType at) {
56
0
    switch (at) {
57
0
        case kUnknown_SkAlphaType:  return "Unknown";
58
0
        case kOpaque_SkAlphaType:   return "Opaque";
59
0
        case kPremul_SkAlphaType:   return "Premul";
60
0
        case kUnpremul_SkAlphaType: return "Unpremul";
61
0
    }
62
0
    SkUNREACHABLE;
63
0
}
64
65
0
const char* colortype_name(SkColorType ct) {
66
0
    switch (ct) {
67
0
        case kUnknown_SkColorType:            return "Unknown";
68
0
        case kAlpha_8_SkColorType:            return "Alpha_8";
69
0
        case kA16_unorm_SkColorType:          return "Alpha_16";
70
0
        case kA16_float_SkColorType:          return "A16_float";
71
0
        case kRGB_565_SkColorType:            return "RGB_565";
72
0
        case kARGB_4444_SkColorType:          return "ARGB_4444";
73
0
        case kRGBA_8888_SkColorType:          return "RGBA_8888";
74
0
        case kSRGBA_8888_SkColorType:         return "SRGBA_8888";
75
0
        case kRGB_888x_SkColorType:           return "RGB_888x";
76
0
        case kBGRA_8888_SkColorType:          return "BGRA_8888";
77
0
        case kRGBA_1010102_SkColorType:       return "RGBA_1010102";
78
0
        case kBGRA_1010102_SkColorType:       return "BGRA_1010102";
79
0
        case kRGB_101010x_SkColorType:        return "RGB_101010x";
80
0
        case kBGR_101010x_SkColorType:        return "BGR_101010x";
81
0
        case kBGR_101010x_XR_SkColorType:     return "BGR_101010x_XR";
82
0
        case kRGBA_10x6_SkColorType:          return "RGBA_10x6";
83
0
        case kGray_8_SkColorType:             return "Gray_8";
84
0
        case kRGBA_F16Norm_SkColorType:       return "RGBA_F16Norm";
85
0
        case kRGBA_F16_SkColorType:           return "RGBA_F16";
86
0
        case kRGBA_F32_SkColorType:           return "RGBA_F32";
87
0
        case kR8G8_unorm_SkColorType:         return "R8G8_unorm";
88
0
        case kR16G16_unorm_SkColorType:       return "R16G16_unorm";
89
0
        case kR16G16_float_SkColorType:       return "R16G16_float";
90
0
        case kR16G16B16A16_unorm_SkColorType: return "R16G16B16A16_unorm";
91
0
        case kR8_unorm_SkColorType:           return "R8_unorm";
92
0
        case kBGRA_10101010_XR_SkColorType:   return "BGRA_10101010_XR";
93
0
    }
94
0
    SkUNREACHABLE;
95
0
}
96
97
0
const char* colortype_depth(SkColorType ct) {
98
0
    switch (ct) {
99
0
        case kUnknown_SkColorType:            return "Unknown";
100
0
        case kAlpha_8_SkColorType:            return "A8";
101
0
        case kA16_unorm_SkColorType:          return "A16";
102
0
        case kA16_float_SkColorType:          return "AF16";
103
0
        case kRGB_565_SkColorType:            return "565";
104
0
        case kARGB_4444_SkColorType:          return "4444";
105
0
        case kRGBA_8888_SkColorType:          return "8888";
106
0
        case kSRGBA_8888_SkColorType:         return "8888";
107
0
        case kRGB_888x_SkColorType:           return "888";
108
0
        case kBGRA_8888_SkColorType:          return "8888";
109
0
        case kRGBA_1010102_SkColorType:       return "1010102";
110
0
        case kBGRA_1010102_SkColorType:       return "1010102";
111
0
        case kRGB_101010x_SkColorType:        return "101010";
112
0
        case kBGR_101010x_SkColorType:        return "101010";
113
0
        case kBGR_101010x_XR_SkColorType:     return "101010";
114
0
        case kBGRA_10101010_XR_SkColorType:   return "10101010";
115
0
        case kRGBA_10x6_SkColorType:          return "10101010";
116
0
        case kGray_8_SkColorType:             return "G8";
117
0
        case kRGBA_F16Norm_SkColorType:       return "F16Norm";
118
0
        case kRGBA_F16_SkColorType:           return "F16";
119
0
        case kRGBA_F32_SkColorType:           return "F32";
120
0
        case kR8G8_unorm_SkColorType:         return "88";
121
0
        case kR16G16_unorm_SkColorType:       return "1616";
122
0
        case kR16G16_float_SkColorType:       return "F16F16";
123
0
        case kR16G16B16A16_unorm_SkColorType: return "16161616";
124
0
        case kR8_unorm_SkColorType:           return "R8";
125
0
    }
126
0
    SkUNREACHABLE;
127
0
}
128
129
0
const char* tilemode_name(SkTileMode mode) {
130
0
    switch (mode) {
131
0
        case SkTileMode::kClamp:  return "clamp";
132
0
        case SkTileMode::kRepeat: return "repeat";
133
0
        case SkTileMode::kMirror: return "mirror";
134
0
        case SkTileMode::kDecal:  return "decal";
135
0
    }
136
0
    SkUNREACHABLE;
137
0
}
138
139
0
SkColor color_to_565(SkColor color) {
140
    // Not a good idea to use this function for greyscale colors...
141
    // it will add an obvious purple or green tint.
142
0
    SkASSERT(SkColorGetR(color) != SkColorGetG(color) || SkColorGetR(color) != SkColorGetB(color) ||
143
0
             SkColorGetG(color) != SkColorGetB(color));
144
145
0
    SkPMColor pmColor = SkPreMultiplyColor(color);
146
0
    U16CPU    color16 = SkPixel32ToPixel16(pmColor);
147
0
    return SkPixel16ToColor(color16);
148
0
}
Unexecuted instantiation: ToolUtils::color_to_565(unsigned int)
Unexecuted instantiation: ToolUtils::color_to_565(unsigned int)
149
150
0
sk_sp<SkShader> create_checkerboard_shader(SkColor c1, SkColor c2, int size) {
151
0
    SkBitmap bm;
152
0
    bm.allocPixels(SkImageInfo::MakeS32(2 * size, 2 * size, kPremul_SkAlphaType));
153
0
    bm.eraseColor(c1);
154
0
    bm.eraseArea(SkIRect::MakeLTRB(0, 0, size, size), c2);
155
0
    bm.eraseArea(SkIRect::MakeLTRB(size, size, 2 * size, 2 * size), c2);
156
0
    return bm.makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, SkSamplingOptions());
157
0
}
158
159
0
SkBitmap create_checkerboard_bitmap(int w, int h, SkColor c1, SkColor c2, int checkSize) {
160
0
    SkBitmap bitmap;
161
0
    bitmap.allocPixels(SkImageInfo::MakeS32(w, h, kPremul_SkAlphaType));
162
0
    SkCanvas canvas(bitmap);
163
164
0
    ToolUtils::draw_checkerboard(&canvas, c1, c2, checkSize);
165
0
    return bitmap;
166
0
}
167
168
0
sk_sp<SkImage> create_checkerboard_image(int w, int h, SkColor c1, SkColor c2, int checkSize) {
169
0
    auto surf = SkSurfaces::Raster(SkImageInfo::MakeN32Premul(w, h));
170
0
    ToolUtils::draw_checkerboard(surf->getCanvas(), c1, c2, checkSize);
171
0
    return surf->makeImageSnapshot();
172
0
}
173
174
0
void draw_checkerboard(SkCanvas* canvas, SkColor c1, SkColor c2, int size) {
175
0
    SkPaint paint;
176
0
    paint.setShader(create_checkerboard_shader(c1, c2, size));
177
0
    paint.setBlendMode(SkBlendMode::kSrc);
178
0
    canvas->drawPaint(paint);
179
0
}
180
181
int make_pixmaps(SkColorType ct,
182
                 SkAlphaType at,
183
                 bool withMips,
184
                 const SkColor4f colors[6],
185
                 SkPixmap pixmaps[6],
186
0
                 std::unique_ptr<char[]>* mem) {
187
188
0
    int levelSize = 32;
189
0
    int numMipLevels = withMips ? 6 : 1;
190
0
    size_t size = 0;
191
0
    SkImageInfo ii[6];
192
0
    size_t rowBytes[6];
193
0
    for (int level = 0; level < numMipLevels; ++level) {
194
0
        ii[level] = SkImageInfo::Make(levelSize, levelSize, ct, at);
195
0
        rowBytes[level] = ii[level].minRowBytes();
196
        // Make sure we test row bytes that aren't tight.
197
0
        if (!(level % 2)) {
198
0
            rowBytes[level] += (level + 1)*SkColorTypeBytesPerPixel(ii[level].colorType());
199
0
        }
200
0
        size += rowBytes[level]*ii[level].height();
201
0
        levelSize /= 2;
202
0
    }
203
0
    mem->reset(new char[size]);
204
0
    char* addr = mem->get();
205
0
    for (int level = 0; level < numMipLevels; ++level) {
206
0
        pixmaps[level].reset(ii[level], addr, rowBytes[level]);
207
0
        addr += rowBytes[level]*ii[level].height();
208
0
        pixmaps[level].erase(colors[level]);
209
0
    }
210
0
    return numMipLevels;
211
0
}
212
213
void add_to_text_blob_w_len(SkTextBlobBuilder* builder,
214
                            const char*        text,
215
                            size_t             len,
216
                            SkTextEncoding     encoding,
217
                            const SkFont&      font,
218
                            SkScalar           x,
219
0
                            SkScalar           y) {
220
0
    int  count = font.countText(text, len, encoding);
221
0
    if (count < 1) {
222
0
        return;
223
0
    }
224
0
    auto run   = builder->allocRun(font, count, x, y);
225
0
    font.textToGlyphs(text, len, encoding, run.glyphs, count);
226
0
}
227
228
void add_to_text_blob(SkTextBlobBuilder* builder,
229
                      const char*        text,
230
                      const SkFont&      font,
231
                      SkScalar           x,
232
0
                      SkScalar           y) {
233
0
    add_to_text_blob_w_len(builder, text, strlen(text), SkTextEncoding::kUTF8, font, x, y);
234
0
}
235
236
void get_text_path(const SkFont&  font,
237
                   const void*    text,
238
                   size_t         length,
239
                   SkTextEncoding encoding,
240
                   SkPath*        dst,
241
0
                   const SkPoint  pos[]) {
242
0
    SkAutoToGlyphs        atg(font, text, length, encoding);
243
0
    const int             count = atg.count();
244
0
    AutoTArray<SkPoint> computedPos;
245
0
    if (pos == nullptr) {
246
0
        computedPos.reset(count);
247
0
        font.getPos(atg.glyphs(), count, &computedPos[0]);
248
0
        pos = computedPos.get();
249
0
    }
250
251
0
    struct Rec {
252
0
        SkPath*        fDst;
253
0
        const SkPoint* fPos;
254
0
    } rec = {dst, pos};
255
0
    font.getPaths(atg.glyphs(),
256
0
                  atg.count(),
257
0
                  [](const SkPath* src, const SkMatrix& mx, void* ctx) {
258
0
                      Rec* rec = (Rec*)ctx;
259
0
                      if (src) {
260
0
                          SkMatrix tmp(mx);
261
0
                          tmp.postTranslate(rec->fPos->fX, rec->fPos->fY);
262
0
                          rec->fDst->addPath(*src, tmp);
263
0
                      }
264
0
                      rec->fPos += 1;
265
0
                  },
266
0
                  &rec);
267
0
}
268
269
0
SkPath make_star(const SkRect& bounds, int numPts, int step) {
270
0
    SkASSERT(numPts != step);
271
0
    SkPathBuilder builder;
272
0
    builder.setFillType(SkPathFillType::kEvenOdd);
273
0
    builder.moveTo(0, -1);
274
0
    for (int i = 1; i < numPts; ++i) {
275
0
        int      idx   = i * step % numPts;
276
0
        SkScalar theta = idx * 2 * SK_ScalarPI / numPts + SK_ScalarPI / 2;
277
0
        SkScalar x     = SkScalarCos(theta);
278
0
        SkScalar y     = -SkScalarSin(theta);
279
0
        builder.lineTo(x, y);
280
0
    }
281
0
    SkPath path = builder.detach();
282
0
    path.transform(SkMatrix::RectToRect(path.getBounds(), bounds));
283
0
    return path;
284
0
}
Unexecuted instantiation: ToolUtils::make_star(SkRect const&, int, int)
Unexecuted instantiation: ToolUtils::make_star(SkRect const&, int, int)
285
286
0
static inline void norm_to_rgb(SkBitmap* bm, int x, int y, const SkVector3& norm) {
287
0
    SkASSERT(SkScalarNearlyEqual(norm.length(), 1.0f));
288
0
    unsigned char r      = static_cast<unsigned char>((0.5f * norm.fX + 0.5f) * 255);
289
0
    unsigned char g      = static_cast<unsigned char>((-0.5f * norm.fY + 0.5f) * 255);
290
0
    unsigned char b      = static_cast<unsigned char>((0.5f * norm.fZ + 0.5f) * 255);
291
0
    *bm->getAddr32(x, y) = SkPackARGB32(0xFF, r, g, b);
292
0
}
Unexecuted instantiation: ToolUtils.cpp:ToolUtils::norm_to_rgb(SkBitmap*, int, int, SkPoint3 const&)
Unexecuted instantiation: ToolUtils.cpp:ToolUtils::norm_to_rgb(SkBitmap*, int, int, SkPoint3 const&)
293
294
0
void create_hemi_normal_map(SkBitmap* bm, const SkIRect& dst) {
295
0
    const SkPoint center =
296
0
            SkPoint::Make(dst.fLeft + (dst.width() / 2.0f), dst.fTop + (dst.height() / 2.0f));
297
0
    const SkPoint halfSize = SkPoint::Make(dst.width() / 2.0f, dst.height() / 2.0f);
298
299
0
    SkVector3 norm;
300
301
0
    for (int y = dst.fTop; y < dst.fBottom; ++y) {
302
0
        for (int x = dst.fLeft; x < dst.fRight; ++x) {
303
0
            norm.fX = (x + 0.5f - center.fX) / halfSize.fX;
304
0
            norm.fY = (y + 0.5f - center.fY) / halfSize.fY;
305
306
0
            SkScalar tmp = norm.fX * norm.fX + norm.fY * norm.fY;
307
0
            if (tmp >= 1.0f) {
308
0
                norm.set(0.0f, 0.0f, 1.0f);
309
0
            } else {
310
0
                norm.fZ = sqrtf(1.0f - tmp);
311
0
            }
312
313
0
            norm_to_rgb(bm, x, y, norm);
314
0
        }
315
0
    }
316
0
}
317
318
0
void create_frustum_normal_map(SkBitmap* bm, const SkIRect& dst) {
319
0
    const SkPoint center =
320
0
            SkPoint::Make(dst.fLeft + (dst.width() / 2.0f), dst.fTop + (dst.height() / 2.0f));
321
322
0
    SkIRect inner = dst;
323
0
    inner.inset(dst.width() / 4, dst.height() / 4);
324
325
0
    SkPoint3       norm;
326
0
    const SkPoint3 left  = SkPoint3::Make(-SK_ScalarRoot2Over2, 0.0f, SK_ScalarRoot2Over2);
327
0
    const SkPoint3 up    = SkPoint3::Make(0.0f, -SK_ScalarRoot2Over2, SK_ScalarRoot2Over2);
328
0
    const SkPoint3 right = SkPoint3::Make(SK_ScalarRoot2Over2, 0.0f, SK_ScalarRoot2Over2);
329
0
    const SkPoint3 down  = SkPoint3::Make(0.0f, SK_ScalarRoot2Over2, SK_ScalarRoot2Over2);
330
331
0
    for (int y = dst.fTop; y < dst.fBottom; ++y) {
332
0
        for (int x = dst.fLeft; x < dst.fRight; ++x) {
333
0
            if (inner.contains(x, y)) {
334
0
                norm.set(0.0f, 0.0f, 1.0f);
335
0
            } else {
336
0
                SkScalar locX = x + 0.5f - center.fX;
337
0
                SkScalar locY = y + 0.5f - center.fY;
338
339
0
                if (locX >= 0.0f) {
340
0
                    if (locY > 0.0f) {
341
0
                        norm = locX >= locY ? right : down;  // LR corner
342
0
                    } else {
343
0
                        norm = locX > -locY ? right : up;  // UR corner
344
0
                    }
345
0
                } else {
346
0
                    if (locY > 0.0f) {
347
0
                        norm = -locX > locY ? left : down;  // LL corner
348
0
                    } else {
349
0
                        norm = locX > locY ? up : left;  // UL corner
350
0
                    }
351
0
                }
352
0
            }
353
354
0
            norm_to_rgb(bm, x, y, norm);
355
0
        }
356
0
    }
357
0
}
358
359
0
void create_tetra_normal_map(SkBitmap* bm, const SkIRect& dst) {
360
0
    const SkPoint center =
361
0
            SkPoint::Make(dst.fLeft + (dst.width() / 2.0f), dst.fTop + (dst.height() / 2.0f));
362
363
0
    static const SkScalar k1OverRoot3 = 0.5773502692f;
364
365
0
    SkPoint3       norm;
366
0
    const SkPoint3 leftUp  = SkPoint3::Make(-k1OverRoot3, -k1OverRoot3, k1OverRoot3);
367
0
    const SkPoint3 rightUp = SkPoint3::Make(k1OverRoot3, -k1OverRoot3, k1OverRoot3);
368
0
    const SkPoint3 down    = SkPoint3::Make(0.0f, SK_ScalarRoot2Over2, SK_ScalarRoot2Over2);
369
370
0
    for (int y = dst.fTop; y < dst.fBottom; ++y) {
371
0
        for (int x = dst.fLeft; x < dst.fRight; ++x) {
372
0
            SkScalar locX = x + 0.5f - center.fX;
373
0
            SkScalar locY = y + 0.5f - center.fY;
374
375
0
            if (locX >= 0.0f) {
376
0
                if (locY > 0.0f) {
377
0
                    norm = locX >= locY ? rightUp : down;  // LR corner
378
0
                } else {
379
0
                    norm = rightUp;
380
0
                }
381
0
            } else {
382
0
                if (locY > 0.0f) {
383
0
                    norm = -locX > locY ? leftUp : down;  // LL corner
384
0
                } else {
385
0
                    norm = leftUp;
386
0
                }
387
0
            }
388
389
0
            norm_to_rgb(bm, x, y, norm);
390
0
        }
391
0
    }
392
0
}
393
394
0
bool copy_to(SkBitmap* dst, SkColorType dstColorType, const SkBitmap& src) {
395
0
    SkPixmap srcPM;
396
0
    if (!src.peekPixels(&srcPM)) {
397
0
        return false;
398
0
    }
399
400
0
    SkBitmap    tmpDst;
401
0
    SkImageInfo dstInfo = srcPM.info().makeColorType(dstColorType);
402
0
    if (!tmpDst.setInfo(dstInfo)) {
403
0
        return false;
404
0
    }
405
406
0
    if (!tmpDst.tryAllocPixels()) {
407
0
        return false;
408
0
    }
409
410
0
    SkPixmap dstPM;
411
0
    if (!tmpDst.peekPixels(&dstPM)) {
412
0
        return false;
413
0
    }
414
415
0
    if (!srcPM.readPixels(dstPM)) {
416
0
        return false;
417
0
    }
418
419
0
    dst->swap(tmpDst);
420
0
    return true;
421
0
}
422
423
0
void copy_to_g8(SkBitmap* dst, const SkBitmap& src) {
424
0
    SkASSERT(kBGRA_8888_SkColorType == src.colorType() ||
425
0
             kRGBA_8888_SkColorType == src.colorType());
426
427
0
    SkImageInfo grayInfo = src.info().makeColorType(kGray_8_SkColorType);
428
0
    dst->allocPixels(grayInfo);
429
0
    uint8_t*        dst8  = (uint8_t*)dst->getPixels();
430
0
    const uint32_t* src32 = (const uint32_t*)src.getPixels();
431
432
0
    const int  w      = src.width();
433
0
    const int  h      = src.height();
434
0
    const bool isBGRA = (kBGRA_8888_SkColorType == src.colorType());
435
0
    for (int y = 0; y < h; ++y) {
436
0
        if (isBGRA) {
437
            // BGRA
438
0
            for (int x = 0; x < w; ++x) {
439
0
                uint32_t s = src32[x];
440
0
                dst8[x]    = SkComputeLuminance((s >> 16) & 0xFF, (s >> 8) & 0xFF, s & 0xFF);
441
0
            }
442
0
        } else {
443
            // RGBA
444
0
            for (int x = 0; x < w; ++x) {
445
0
                uint32_t s = src32[x];
446
0
                dst8[x]    = SkComputeLuminance(s & 0xFF, (s >> 8) & 0xFF, (s >> 16) & 0xFF);
447
0
            }
448
0
        }
449
0
        src32 = (const uint32_t*)((const char*)src32 + src.rowBytes());
450
0
        dst8 += dst->rowBytes();
451
0
    }
452
0
}
Unexecuted instantiation: ToolUtils::copy_to_g8(SkBitmap*, SkBitmap const&)
Unexecuted instantiation: ToolUtils::copy_to_g8(SkBitmap*, SkBitmap const&)
453
454
//////////////////////////////////////////////////////////////////////////////////////////////
455
456
0
bool equal_pixels(const SkPixmap& a, const SkPixmap& b) {
457
0
    if (a.width() != b.width() || a.height() != b.height()) {
458
0
        SkDebugf("[ToolUtils::equal_pixels] Dimensions do not match (%d x %d) != (%d x %d)\n",
459
0
                 a.width(), a.height(), b.width(), b.height());
460
0
        return false;
461
0
    }
462
463
0
    if (a.colorType() != b.colorType()) {
464
0
        SkDebugf("[ToolUtils::equal_pixels] colorType does not match %d != %d\n",
465
0
                 (int) a.colorType(), (int) b.colorType());
466
0
        return false;
467
0
    }
468
469
0
    for (int y = 0; y < a.height(); ++y) {
470
0
        const char* aptr = (const char*)a.addr(0, y);
471
0
        const char* bptr = (const char*)b.addr(0, y);
472
0
        if (0 != memcmp(aptr, bptr, a.width() * a.info().bytesPerPixel())) {
473
0
            SkDebugf("[ToolUtils::equal_pixels] row %d does not match byte for byte\n", y);
474
0
            return false;
475
0
        }
476
0
    }
477
0
    return true;
478
0
}
479
480
0
bool equal_pixels(const SkBitmap& bm0, const SkBitmap& bm1) {
481
0
    SkPixmap pm0, pm1;
482
0
    if (!bm0.peekPixels(&pm0)) {
483
0
        SkDebugf("Could not read pixels from A\n");
484
0
        return false;
485
0
    }
486
0
    if (!bm1.peekPixels(&pm1)) {
487
0
        SkDebugf("Could not read pixels from B\n");
488
0
        return false;
489
0
    }
490
0
    return equal_pixels(pm0, pm1);
491
0
}
492
493
0
bool equal_pixels(const SkImage* a, const SkImage* b) {
494
0
    SkASSERT_RELEASE(a);
495
0
    SkASSERT_RELEASE(b);
496
    // ensure that peekPixels will succeed
497
0
    auto imga = a->makeRasterImage();
498
0
    auto imgb = b->makeRasterImage();
499
500
0
    SkPixmap pm0, pm1;
501
0
    if (!imga->peekPixels(&pm0)) {
502
0
        SkDebugf("Could not read pixels from A\n");
503
0
        return false;
504
0
    }
505
0
    if (!imgb->peekPixels(&pm1)) {
506
0
        SkDebugf("Could not read pixels from B\n");
507
0
        return false;
508
0
    }
509
0
    return equal_pixels(pm0, pm1);
510
0
}
511
512
sk_sp<SkSurface> makeSurface(SkCanvas*             canvas,
513
                             const SkImageInfo&    info,
514
0
                             const SkSurfaceProps* props) {
515
0
    auto surf = canvas->makeSurface(info, props);
516
0
    if (!surf) {
517
0
        surf = SkSurfaces::Raster(info, props);
518
0
    }
519
0
    return surf;
520
0
}
521
522
VariationSliders::VariationSliders(SkTypeface* typeface,
523
0
                                   SkFontArguments::VariationPosition variationPosition) {
524
0
    if (!typeface) {
525
0
        return;
526
0
    }
527
528
0
    int numAxes = typeface->getVariationDesignParameters(nullptr, 0);
529
0
    if (numAxes < 0) {
530
0
        return;
531
0
    }
532
533
0
    std::unique_ptr<SkFontParameters::Variation::Axis[]> copiedAxes =
534
0
            std::make_unique<SkFontParameters::Variation::Axis[]>(numAxes);
535
536
0
    numAxes = typeface->getVariationDesignParameters(copiedAxes.get(), numAxes);
537
0
    if (numAxes < 0) {
538
0
        return;
539
0
    }
540
541
0
    auto argVariationPositionOrDefault = [&variationPosition](SkFourByteTag tag,
542
0
                                                              SkScalar defaultValue) -> SkScalar {
543
0
        for (int i = 0; i < variationPosition.coordinateCount; ++i) {
544
0
            if (variationPosition.coordinates[i].axis == tag) {
545
0
                return variationPosition.coordinates[i].value;
546
0
            }
547
0
        }
548
0
        return defaultValue;
549
0
    };
550
551
0
    fAxisSliders.resize(numAxes);
552
0
    fCoords = std::make_unique<SkFontArguments::VariationPosition::Coordinate[]>(numAxes);
553
0
    for (int i = 0; i < numAxes; ++i) {
554
0
        fAxisSliders[i].axis = copiedAxes[i];
555
0
        fAxisSliders[i].current =
556
0
                argVariationPositionOrDefault(copiedAxes[i].tag, copiedAxes[i].def);
557
0
        fAxisSliders[i].name = tagToString(fAxisSliders[i].axis.tag);
558
0
        fCoords[i] = { fAxisSliders[i].axis.tag, fAxisSliders[i].current };
559
0
    }
560
0
}
561
562
/* static */
563
0
SkString VariationSliders::tagToString(SkFourByteTag tag) {
564
0
    char tagAsString[5];
565
0
    tagAsString[4] = 0;
566
0
    tagAsString[0] = (char)(uint8_t)(tag >> 24);
567
0
    tagAsString[1] = (char)(uint8_t)(tag >> 16);
568
0
    tagAsString[2] = (char)(uint8_t)(tag >> 8);
569
0
    tagAsString[3] = (char)(uint8_t)(tag >> 0);
570
0
    return SkString(tagAsString);
571
0
}
572
573
0
bool VariationSliders::writeControls(SkMetaData* controls) {
574
0
    for (size_t i = 0; i < fAxisSliders.size(); ++i) {
575
0
        SkScalar axisVars[kAxisVarsSize];
576
577
0
        axisVars[0] = fAxisSliders[i].current;
578
0
        axisVars[1] = fAxisSliders[i].axis.min;
579
0
        axisVars[2] = fAxisSliders[i].axis.max;
580
0
        controls->setScalars(fAxisSliders[i].name.c_str(), kAxisVarsSize, axisVars);
581
0
    }
582
0
    return true;
583
0
}
584
585
0
void VariationSliders::readControls(const SkMetaData& controls, bool* changed) {
586
0
    for (size_t i = 0; i < fAxisSliders.size(); ++i) {
587
0
        SkScalar axisVars[kAxisVarsSize] = {0};
588
0
        int resultAxisVarsSize = 0;
589
0
        SkASSERT_RELEASE(controls.findScalars(
590
0
                tagToString(fAxisSliders[i].axis.tag).c_str(), &resultAxisVarsSize, axisVars));
591
0
        SkASSERT_RELEASE(resultAxisVarsSize == kAxisVarsSize);
592
0
        if (changed) {
593
0
            *changed |= fAxisSliders[i].current != axisVars[0];
594
0
        }
595
0
        fAxisSliders[i].current = axisVars[0];
596
0
        fCoords[i] = { fAxisSliders[i].axis.tag, fAxisSliders[i].current };
597
0
    }
598
0
}
599
600
0
SkSpan<const SkFontArguments::VariationPosition::Coordinate> VariationSliders::getCoordinates() {
601
0
    return SkSpan<const SkFontArguments::VariationPosition::Coordinate>{fCoords.get(),
602
0
                                                                        fAxisSliders.size()};
603
0
}
604
605
////////////////////////////////////////////////////////////////////////////////////////////////////
606
HilbertGenerator::HilbertGenerator(float desiredSize, float desiredLineWidth, int desiredDepth)
607
        : fDesiredSize(desiredSize)
608
        , fDesiredDepth(desiredDepth)
609
        , fSegmentLength(fDesiredSize / ((0x1 << fDesiredDepth) - 1.0f))
610
        , fDesiredLineWidth(desiredLineWidth)
611
        , fActualBounds(SkRect::MakeEmpty())
612
        , fCurPos(SkPoint::Make(0.0f, 0.0f))
613
        , fCurDir(0)
614
        , fExpectedLen(fSegmentLength * ((0x1 << (2*fDesiredDepth)) - 1.0f))
615
0
        , fCurLen(0.0f) {
616
0
}
617
618
0
void HilbertGenerator::draw(SkCanvas* canvas) {
619
0
    this->recursiveDraw(canvas, /* curDepth= */ 0, /* turnLeft= */ true);
620
621
0
    SkScalarNearlyEqual(fExpectedLen, fCurLen, 0.01f);
622
0
    SkScalarNearlyEqual(fDesiredSize, fActualBounds.width(), 0.01f);
623
0
    SkScalarNearlyEqual(fDesiredSize, fActualBounds.height(), 0.01f);
624
0
}
625
626
0
void HilbertGenerator::turn90(bool turnLeft) {
627
0
    fCurDir += turnLeft ? 90 : -90;
628
0
    if (fCurDir >= 360) {
629
0
        fCurDir = 0;
630
0
    } else if (fCurDir < 0) {
631
0
        fCurDir = 270;
632
0
    }
633
634
0
    SkASSERT(fCurDir == 0 || fCurDir == 90 || fCurDir == 180 || fCurDir == 270);
635
0
}
Unexecuted instantiation: ToolUtils::HilbertGenerator::turn90(bool)
Unexecuted instantiation: ToolUtils::HilbertGenerator::turn90(bool)
636
637
0
void HilbertGenerator::line(SkCanvas* canvas) {
638
639
0
    SkPoint before = fCurPos;
640
641
0
    SkRect r;
642
0
    switch (fCurDir) {
643
0
        case 0:
644
0
            r.fLeft = fCurPos.fX;
645
0
            r.fTop = fCurPos.fY - fDesiredLineWidth / 2.0f;
646
0
            r.fRight = fCurPos.fX + fSegmentLength;
647
0
            r.fBottom = fCurPos.fY + fDesiredLineWidth / 2.0f;
648
0
            fCurPos.fX += fSegmentLength;
649
0
            break;
650
0
        case 90:
651
0
            r.fLeft = fCurPos.fX - fDesiredLineWidth / 2.0f;
652
0
            r.fTop = fCurPos.fY - fSegmentLength;
653
0
            r.fRight = fCurPos.fX + fDesiredLineWidth / 2.0f;
654
0
            r.fBottom = fCurPos.fY;
655
0
            fCurPos.fY -= fSegmentLength;
656
0
            break;
657
0
        case 180:
658
0
            r.fLeft = fCurPos.fX - fSegmentLength;
659
0
            r.fTop = fCurPos.fY - fDesiredLineWidth / 2.0f;
660
0
            r.fRight = fCurPos.fX;
661
0
            r.fBottom = fCurPos.fY + fDesiredLineWidth / 2.0f;
662
0
            fCurPos.fX -= fSegmentLength;
663
0
            break;
664
0
        case 270:
665
0
            r.fLeft = fCurPos.fX - fDesiredLineWidth / 2.0f;
666
0
            r.fTop = fCurPos.fY;
667
0
            r.fRight = fCurPos.fX + fDesiredLineWidth / 2.0f;
668
0
            r.fBottom = fCurPos.fY + fSegmentLength;
669
0
            fCurPos.fY += fSegmentLength;
670
0
            break;
671
0
        default:
672
0
            return;
673
0
    }
674
675
0
    SkPoint pts[2] = { before, fCurPos };
676
677
0
    SkColor4f colors[2] = {
678
0
            this->getColor(fCurLen),
679
0
            this->getColor(fCurLen + fSegmentLength),
680
0
    };
681
682
0
    fCurLen += fSegmentLength;
683
0
    if (fActualBounds.isEmpty()) {
684
0
        fActualBounds = r;
685
0
    } else {
686
0
        fActualBounds.join(r);
687
0
    }
688
689
0
    SkPaint paint;
690
0
    paint.setShader(SkGradientShader::MakeLinear(pts, colors, /* colorSpace= */ nullptr,
691
0
                                                 /* pos= */ nullptr, 2, SkTileMode::kClamp));
692
0
    canvas->drawRect(r, paint);
693
0
}
694
695
0
void HilbertGenerator::recursiveDraw(SkCanvas* canvas, int curDepth, bool turnLeft) {
696
0
    if (curDepth >= fDesiredDepth) {
697
0
        return;
698
0
    }
699
700
0
    this->turn90(turnLeft);
701
0
    this->recursiveDraw(canvas, curDepth + 1, !turnLeft);
702
0
    this->line(canvas);
703
0
    this->turn90(!turnLeft);
704
0
    this->recursiveDraw(canvas, curDepth + 1, turnLeft);
705
0
    this->line(canvas);
706
0
    this->recursiveDraw(canvas, curDepth + 1, turnLeft);
707
0
    this->turn90(!turnLeft);
708
0
    this->line(canvas);
709
0
    this->recursiveDraw(canvas, curDepth + 1, !turnLeft);
710
0
    this->turn90(turnLeft);
711
0
}
712
713
0
SkColor4f HilbertGenerator::getColor(float curLen) {
714
0
    static const SkColor4f kColors[] = {
715
0
            SkColors::kBlack,
716
0
            SkColors::kBlue,
717
0
            SkColors::kCyan,
718
0
            SkColors::kGreen,
719
0
            SkColors::kYellow,
720
0
            SkColors::kRed,
721
0
            SkColors::kWhite,
722
0
    };
723
724
0
    static const float kStops[] = {
725
0
            0.0f,
726
0
            1.0f/6.0f,
727
0
            2.0f/6.0f,
728
0
            0.5f,
729
0
            4.0f/6.0f,
730
0
            5.0f/6.0f,
731
0
            1.0f,
732
0
    };
733
0
    static_assert(std::size(kColors) == std::size(kStops));
734
735
0
    float t = curLen / fExpectedLen;
736
0
    if (t <= 0.0f) {
737
0
        return kColors[0];
738
0
    } else if (t >= 1.0f) {
739
0
        return kColors[std::size(kColors)-1];
740
0
    }
741
742
0
    for (unsigned int i = 0; i < std::size(kColors)-1; ++i) {
743
0
        if (kStops[i] <= t && t <= kStops[i+1]) {
744
0
            t = (t - kStops[i]) / (kStops[i+1] - kStops[i]);
745
0
            SkASSERT(0.0f <= t && t <= 1.0f);
746
0
            return { kColors[i].fR * (1 - t) + kColors[i+1].fR * t,
747
0
                     kColors[i].fG * (1 - t) + kColors[i+1].fG * t,
748
0
                     kColors[i].fB * (1 - t) + kColors[i+1].fB * t,
749
0
                     kColors[i].fA * (1 - t) + kColors[i+1].fA * t };
750
751
0
        }
752
0
    }
753
754
0
    return SkColors::kBlack;
755
0
}
Unexecuted instantiation: ToolUtils::HilbertGenerator::getColor(float)
Unexecuted instantiation: ToolUtils::HilbertGenerator::getColor(float)
756
757
0
void ExtractPathsFromSKP(const char filepath[], std::function<PathSniffCallback> callback) {
758
0
    SkFILEStream stream(filepath);
759
0
    if (!stream.isValid()) {
760
0
        SkDebugf("ExtractPaths: invalid input file at \"%s\"\n", filepath);
761
0
        return;
762
0
    }
763
764
0
    class PathSniffer : public SkCanvas {
765
0
    public:
766
0
        PathSniffer(std::function<PathSniffCallback> callback)
767
0
                : SkCanvas(4096, 4096, nullptr)
768
0
                , fPathSniffCallback(callback) {}
769
0
    private:
770
0
        void onDrawPath(const SkPath& path, const SkPaint& paint) override {
771
0
            fPathSniffCallback(this->getTotalMatrix(), path, paint);
772
0
        }
773
0
        std::function<PathSniffCallback> fPathSniffCallback;
774
0
    };
775
776
0
    sk_sp<SkPicture> skp = SkPicture::MakeFromStream(&stream);
777
0
    if (!skp) {
778
0
        SkDebugf("ExtractPaths: couldn't load skp at \"%s\"\n", filepath);
779
0
        return;
780
0
    }
781
0
    PathSniffer pathSniffer(callback);
782
0
    skp->playback(&pathSniffer);
783
0
}
784
785
}  // namespace ToolUtils