PathCache.cpp revision d93b9bde90522a7da6a0875a9f33ef9361088449
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <SkBitmap.h>
18#include <SkCanvas.h>
19#include <SkColor.h>
20#include <SkPaint.h>
21#include <SkPath.h>
22#include <SkPathEffect.h>
23#include <SkRect.h>
24
25#include <utils/JenkinsHash.h>
26#include <utils/Trace.h>
27
28#include "Caches.h"
29#include "PathCache.h"
30
31#include "thread/Signal.h"
32#include "thread/TaskProcessor.h"
33
34#include <cutils/properties.h>
35
36namespace android {
37namespace uirenderer {
38
39template <class T>
40static bool compareWidthHeight(const T& lhs, const T& rhs) {
41    return (lhs.mWidth == rhs.mWidth) && (lhs.mHeight == rhs.mHeight);
42}
43
44static bool compareRoundRects(const PathDescription::Shape::RoundRect& lhs,
45        const PathDescription::Shape::RoundRect& rhs) {
46    return compareWidthHeight(lhs, rhs) && lhs.mRx == rhs.mRx && lhs.mRy == rhs.mRy;
47}
48
49static bool compareArcs(const PathDescription::Shape::Arc& lhs, const PathDescription::Shape::Arc& rhs) {
50    return compareWidthHeight(lhs, rhs) && lhs.mStartAngle == rhs.mStartAngle &&
51            lhs.mSweepAngle == rhs.mSweepAngle && lhs.mUseCenter == rhs.mUseCenter;
52}
53
54///////////////////////////////////////////////////////////////////////////////
55// Cache entries
56///////////////////////////////////////////////////////////////////////////////
57
58PathDescription::PathDescription()
59        : type(ShapeType::None)
60        , join(SkPaint::kDefault_Join)
61        , cap(SkPaint::kDefault_Cap)
62        , style(SkPaint::kFill_Style)
63        , miter(4.0f)
64        , strokeWidth(1.0f)
65        , pathEffect(nullptr) {
66    // Shape bits should be set to zeroes, because they are used for hash calculation.
67    memset(&shape, 0, sizeof(Shape));
68}
69
70PathDescription::PathDescription(ShapeType type, const SkPaint* paint)
71        : type(type)
72        , join(paint->getStrokeJoin())
73        , cap(paint->getStrokeCap())
74        , style(paint->getStyle())
75        , miter(paint->getStrokeMiter())
76        , strokeWidth(paint->getStrokeWidth())
77        , pathEffect(paint->getPathEffect()) {
78    // Shape bits should be set to zeroes, because they are used for hash calculation.
79    memset(&shape, 0, sizeof(Shape));
80}
81
82hash_t PathDescription::hash() const {
83    uint32_t hash = JenkinsHashMix(0, static_cast<int>(type));
84    hash = JenkinsHashMix(hash, join);
85    hash = JenkinsHashMix(hash, cap);
86    hash = JenkinsHashMix(hash, style);
87    hash = JenkinsHashMix(hash, android::hash_type(miter));
88    hash = JenkinsHashMix(hash, android::hash_type(strokeWidth));
89    hash = JenkinsHashMix(hash, android::hash_type(pathEffect));
90    hash = JenkinsHashMixBytes(hash, (uint8_t*) &shape, sizeof(Shape));
91    return JenkinsHashWhiten(hash);
92}
93
94bool PathDescription::operator==(const PathDescription& rhs) const {
95    if (type != rhs.type) return false;
96    if (join != rhs.join) return false;
97    if (cap != rhs.cap) return false;
98    if (style != rhs.style) return false;
99    if (miter != rhs.miter) return false;
100    if (strokeWidth != rhs.strokeWidth) return false;
101    if (pathEffect != rhs.pathEffect) return false;
102    switch (type) {
103        case ShapeType::None:
104            return 0;
105        case ShapeType::Rect:
106            return compareWidthHeight(shape.rect, rhs.shape.rect);
107        case ShapeType::RoundRect:
108            return compareRoundRects(shape.roundRect, rhs.shape.roundRect);
109        case ShapeType::Circle:
110            return shape.circle.mRadius == rhs.shape.circle.mRadius;
111        case ShapeType::Oval:
112            return compareWidthHeight(shape.oval, rhs.shape.oval);
113        case ShapeType::Arc:
114            return compareArcs(shape.arc, rhs.shape.arc);
115        case ShapeType::Path:
116            return shape.path.mGenerationID == rhs.shape.path.mGenerationID;
117    }
118}
119
120///////////////////////////////////////////////////////////////////////////////
121// Utilities
122///////////////////////////////////////////////////////////////////////////////
123
124static void computePathBounds(const SkPath* path, const SkPaint* paint, PathTexture* texture,
125        uint32_t& width, uint32_t& height) {
126    const SkRect& bounds = path->getBounds();
127    const float pathWidth = std::max(bounds.width(), 1.0f);
128    const float pathHeight = std::max(bounds.height(), 1.0f);
129
130    texture->left = bounds.fLeft;
131    texture->top = bounds.fTop;
132
133    texture->offset = (int) floorf(std::max(paint->getStrokeWidth(), 1.0f) * 1.5f + 0.5f);
134
135    width = uint32_t(pathWidth + texture->offset * 2.0 + 0.5);
136    height = uint32_t(pathHeight + texture->offset * 2.0 + 0.5);
137}
138
139static void initBitmap(SkBitmap& bitmap, uint32_t width, uint32_t height) {
140    bitmap.allocPixels(SkImageInfo::MakeA8(width, height));
141    bitmap.eraseColor(0);
142}
143
144static void initPaint(SkPaint& paint) {
145    // Make sure the paint is opaque, color, alpha, filter, etc.
146    // will be applied later when compositing the alpha8 texture
147    paint.setColor(SK_ColorBLACK);
148    paint.setAlpha(255);
149    paint.setColorFilter(nullptr);
150    paint.setMaskFilter(nullptr);
151    paint.setShader(nullptr);
152    SkXfermode* mode = SkXfermode::Create(SkXfermode::kSrc_Mode);
153    SkSafeUnref(paint.setXfermode(mode));
154}
155
156static SkBitmap* drawPath(const SkPath* path, const SkPaint* paint, PathTexture* texture,
157        uint32_t maxTextureSize) {
158    uint32_t width, height;
159    computePathBounds(path, paint, texture, width, height);
160    if (width > maxTextureSize || height > maxTextureSize) {
161        ALOGW("Shape too large to be rendered into a texture (%dx%d, max=%dx%d)",
162                width, height, maxTextureSize, maxTextureSize);
163        return nullptr;
164    }
165
166    SkBitmap* bitmap = new SkBitmap();
167    initBitmap(*bitmap, width, height);
168
169    SkPaint pathPaint(*paint);
170    initPaint(pathPaint);
171
172    SkCanvas canvas(*bitmap);
173    canvas.translate(-texture->left + texture->offset, -texture->top + texture->offset);
174    canvas.drawPath(*path, pathPaint);
175    return bitmap;
176}
177
178///////////////////////////////////////////////////////////////////////////////
179// Cache constructor/destructor
180///////////////////////////////////////////////////////////////////////////////
181
182PathCache::PathCache()
183        : mCache(LruCache<PathDescription, PathTexture*>::kUnlimitedCapacity)
184        , mSize(0)
185        , mMaxSize(Properties::pathCacheSize) {
186    mCache.setOnEntryRemovedListener(this);
187
188    GLint maxTextureSize;
189    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
190    mMaxTextureSize = maxTextureSize;
191
192    mDebugEnabled = Properties::debugLevel & kDebugCaches;
193}
194
195PathCache::~PathCache() {
196    mCache.clear();
197}
198
199///////////////////////////////////////////////////////////////////////////////
200// Size management
201///////////////////////////////////////////////////////////////////////////////
202
203uint32_t PathCache::getSize() {
204    return mSize;
205}
206
207uint32_t PathCache::getMaxSize() {
208    return mMaxSize;
209}
210
211///////////////////////////////////////////////////////////////////////////////
212// Callbacks
213///////////////////////////////////////////////////////////////////////////////
214
215void PathCache::operator()(PathDescription& entry, PathTexture*& texture) {
216    removeTexture(texture);
217}
218
219///////////////////////////////////////////////////////////////////////////////
220// Caching
221///////////////////////////////////////////////////////////////////////////////
222
223void PathCache::removeTexture(PathTexture* texture) {
224    if (texture) {
225        const uint32_t size = texture->width() * texture->height();
226
227        // If there is a pending task we must wait for it to return
228        // before attempting our cleanup
229        const sp<Task<SkBitmap*> >& task = texture->task();
230        if (task != nullptr) {
231            task->getResult();
232            texture->clearTask();
233        } else {
234            // If there is a pending task, the path was not added
235            // to the cache and the size wasn't increased
236            if (size > mSize) {
237                ALOGE("Removing path texture of size %d will leave "
238                        "the cache in an inconsistent state", size);
239            }
240            mSize -= size;
241        }
242
243        PATH_LOGD("PathCache::delete name, size, mSize = %d, %d, %d",
244                texture->id, size, mSize);
245        if (mDebugEnabled) {
246            ALOGD("Shape deleted, size = %d", size);
247        }
248
249        texture->deleteTexture();
250        delete texture;
251    }
252}
253
254void PathCache::purgeCache(uint32_t width, uint32_t height) {
255    const uint32_t size = width * height;
256    // Don't even try to cache a bitmap that's bigger than the cache
257    if (size < mMaxSize) {
258        while (mSize + size > mMaxSize) {
259            mCache.removeOldest();
260        }
261    }
262}
263
264void PathCache::trim() {
265    while (mSize > mMaxSize) {
266        mCache.removeOldest();
267    }
268}
269
270PathTexture* PathCache::addTexture(const PathDescription& entry, const SkPath *path,
271        const SkPaint* paint) {
272    ATRACE_NAME("Generate Path Texture");
273
274    PathTexture* texture = new PathTexture(Caches::getInstance(), path->getGenerationID());
275    std::unique_ptr<SkBitmap> bitmap(drawPath(path, paint, texture, mMaxTextureSize));
276    if (!bitmap.get()) {
277        delete texture;
278        return nullptr;
279    }
280
281    purgeCache(bitmap->width(), bitmap->height());
282    generateTexture(entry, bitmap.get(), texture);
283    return texture;
284}
285
286void PathCache::generateTexture(const PathDescription& entry, SkBitmap* bitmap,
287        PathTexture* texture, bool addToCache) {
288    generateTexture(*bitmap, texture);
289
290    // Note here that we upload to a texture even if it's bigger than mMaxSize.
291    // Such an entry in mCache will only be temporary, since it will be evicted
292    // immediately on trim, or on any other Path entering the cache.
293    uint32_t size = texture->width() * texture->height();
294    mSize += size;
295    PATH_LOGD("PathCache::get/create: name, size, mSize = %d, %d, %d",
296            texture->id, size, mSize);
297    if (mDebugEnabled) {
298        ALOGD("Shape created, size = %d", size);
299    }
300    if (addToCache) {
301        mCache.put(entry, texture);
302    }
303}
304
305void PathCache::clear() {
306    mCache.clear();
307}
308
309void PathCache::generateTexture(SkBitmap& bitmap, Texture* texture) {
310    ATRACE_NAME("Upload Path Texture");
311    texture->upload(bitmap);
312    texture->setFilter(GL_LINEAR);
313}
314
315///////////////////////////////////////////////////////////////////////////////
316// Path precaching
317///////////////////////////////////////////////////////////////////////////////
318
319PathCache::PathProcessor::PathProcessor(Caches& caches):
320        TaskProcessor<SkBitmap*>(&caches.tasks), mMaxTextureSize(caches.maxTextureSize) {
321}
322
323void PathCache::PathProcessor::onProcess(const sp<Task<SkBitmap*> >& task) {
324    PathTask* t = static_cast<PathTask*>(task.get());
325    ATRACE_NAME("pathPrecache");
326
327    t->setResult(drawPath(&t->path, &t->paint, t->texture, mMaxTextureSize));
328}
329
330///////////////////////////////////////////////////////////////////////////////
331// Paths
332///////////////////////////////////////////////////////////////////////////////
333
334void PathCache::removeDeferred(const SkPath* path) {
335    Mutex::Autolock l(mLock);
336    mGarbage.push_back(path->getGenerationID());
337}
338
339void PathCache::clearGarbage() {
340    Vector<PathDescription> pathsToRemove;
341
342    { // scope for the mutex
343        Mutex::Autolock l(mLock);
344        for (const uint32_t generationID : mGarbage) {
345            LruCache<PathDescription, PathTexture*>::Iterator iter(mCache);
346            while (iter.next()) {
347                const PathDescription& key = iter.key();
348                if (key.type == ShapeType::Path && key.shape.path.mGenerationID == generationID) {
349                    pathsToRemove.push(key);
350                }
351            }
352        }
353        mGarbage.clear();
354    }
355
356    for (size_t i = 0; i < pathsToRemove.size(); i++) {
357        mCache.remove(pathsToRemove.itemAt(i));
358    }
359}
360
361PathTexture* PathCache::get(const SkPath* path, const SkPaint* paint) {
362    PathDescription entry(ShapeType::Path, paint);
363    entry.shape.path.mGenerationID = path->getGenerationID();
364
365    PathTexture* texture = mCache.get(entry);
366
367    if (!texture) {
368        texture = addTexture(entry, path, paint);
369    } else {
370        // A bitmap is attached to the texture, this means we need to
371        // upload it as a GL texture
372        const sp<Task<SkBitmap*> >& task = texture->task();
373        if (task != nullptr) {
374            // But we must first wait for the worker thread to be done
375            // producing the bitmap, so let's wait
376            SkBitmap* bitmap = task->getResult();
377            if (bitmap) {
378                generateTexture(entry, bitmap, texture, false);
379                texture->clearTask();
380            } else {
381                texture->clearTask();
382                texture = nullptr;
383                mCache.remove(entry);
384            }
385        }
386    }
387
388    return texture;
389}
390
391void PathCache::remove(const SkPath* path, const SkPaint* paint) {
392    PathDescription entry(ShapeType::Path, paint);
393    entry.shape.path.mGenerationID = path->getGenerationID();
394    mCache.remove(entry);
395}
396
397void PathCache::precache(const SkPath* path, const SkPaint* paint) {
398    if (!Caches::getInstance().tasks.canRunTasks()) {
399        return;
400    }
401
402    PathDescription entry(ShapeType::Path, paint);
403    entry.shape.path.mGenerationID = path->getGenerationID();
404
405    PathTexture* texture = mCache.get(entry);
406
407    bool generate = false;
408    if (!texture) {
409        generate = true;
410    }
411
412    if (generate) {
413        // It is important to specify the generation ID so we do not
414        // attempt to precache the same path several times
415        texture = new PathTexture(Caches::getInstance(), path->getGenerationID());
416        sp<PathTask> task = new PathTask(path, paint, texture);
417        texture->setTask(task);
418
419        // During the precaching phase we insert path texture objects into
420        // the cache that do not point to any GL texture. They are instead
421        // treated as a task for the precaching worker thread. This is why
422        // we do not check the cache limit when inserting these objects.
423        // The conversion into GL texture will happen in get(), when a client
424        // asks for a path texture. This is also when the cache limit will
425        // be enforced.
426        mCache.put(entry, texture);
427
428        if (mProcessor == nullptr) {
429            mProcessor = new PathProcessor(Caches::getInstance());
430        }
431        mProcessor->add(task);
432    }
433}
434
435///////////////////////////////////////////////////////////////////////////////
436// Rounded rects
437///////////////////////////////////////////////////////////////////////////////
438
439PathTexture* PathCache::getRoundRect(float width, float height,
440        float rx, float ry, const SkPaint* paint) {
441    PathDescription entry(ShapeType::RoundRect, paint);
442    entry.shape.roundRect.mWidth = width;
443    entry.shape.roundRect.mHeight = height;
444    entry.shape.roundRect.mRx = rx;
445    entry.shape.roundRect.mRy = ry;
446
447    PathTexture* texture = get(entry);
448
449    if (!texture) {
450        SkPath path;
451        SkRect r;
452        r.set(0.0f, 0.0f, width, height);
453        path.addRoundRect(r, rx, ry, SkPath::kCW_Direction);
454
455        texture = addTexture(entry, &path, paint);
456    }
457
458    return texture;
459}
460
461///////////////////////////////////////////////////////////////////////////////
462// Circles
463///////////////////////////////////////////////////////////////////////////////
464
465PathTexture* PathCache::getCircle(float radius, const SkPaint* paint) {
466    PathDescription entry(ShapeType::Circle, paint);
467    entry.shape.circle.mRadius = radius;
468
469    PathTexture* texture = get(entry);
470
471    if (!texture) {
472        SkPath path;
473        path.addCircle(radius, radius, radius, SkPath::kCW_Direction);
474
475        texture = addTexture(entry, &path, paint);
476    }
477
478    return texture;
479}
480
481///////////////////////////////////////////////////////////////////////////////
482// Ovals
483///////////////////////////////////////////////////////////////////////////////
484
485PathTexture* PathCache::getOval(float width, float height, const SkPaint* paint) {
486    PathDescription entry(ShapeType::Oval, paint);
487    entry.shape.oval.mWidth = width;
488    entry.shape.oval.mHeight = height;
489
490    PathTexture* texture = get(entry);
491
492    if (!texture) {
493        SkPath path;
494        SkRect r;
495        r.set(0.0f, 0.0f, width, height);
496        path.addOval(r, SkPath::kCW_Direction);
497
498        texture = addTexture(entry, &path, paint);
499    }
500
501    return texture;
502}
503
504///////////////////////////////////////////////////////////////////////////////
505// Rects
506///////////////////////////////////////////////////////////////////////////////
507
508PathTexture* PathCache::getRect(float width, float height, const SkPaint* paint) {
509    PathDescription entry(ShapeType::Rect, paint);
510    entry.shape.rect.mWidth = width;
511    entry.shape.rect.mHeight = height;
512
513    PathTexture* texture = get(entry);
514
515    if (!texture) {
516        SkPath path;
517        SkRect r;
518        r.set(0.0f, 0.0f, width, height);
519        path.addRect(r, SkPath::kCW_Direction);
520
521        texture = addTexture(entry, &path, paint);
522    }
523
524    return texture;
525}
526
527///////////////////////////////////////////////////////////////////////////////
528// Arcs
529///////////////////////////////////////////////////////////////////////////////
530
531PathTexture* PathCache::getArc(float width, float height,
532        float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint) {
533    PathDescription entry(ShapeType::Arc, paint);
534    entry.shape.arc.mWidth = width;
535    entry.shape.arc.mHeight = height;
536    entry.shape.arc.mStartAngle = startAngle;
537    entry.shape.arc.mSweepAngle = sweepAngle;
538    entry.shape.arc.mUseCenter = useCenter;
539
540    PathTexture* texture = get(entry);
541
542    if (!texture) {
543        SkPath path;
544        SkRect r;
545        r.set(0.0f, 0.0f, width, height);
546        if (useCenter) {
547            path.moveTo(r.centerX(), r.centerY());
548        }
549        path.arcTo(r, startAngle, sweepAngle, !useCenter);
550        if (useCenter) {
551            path.close();
552        }
553
554        texture = addTexture(entry, &path, paint);
555    }
556
557    return texture;
558}
559
560}; // namespace uirenderer
561}; // namespace android
562