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