2 * Copyright (C) 2013 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "OpenGLRenderer"
18 #define ATRACE_TAG ATRACE_TAG_VIEW
27 #include <utils/JenkinsHash.h>
28 #include <utils/Trace.h>
31 #include "PathCache.h"
33 #include "thread/Signal.h"
34 #include "thread/TaskProcessor.h"
37 namespace uirenderer {
39 ///////////////////////////////////////////////////////////////////////////////
41 ///////////////////////////////////////////////////////////////////////////////
43 PathDescription::PathDescription()
45 , join(SkPaint::kDefault_Join)
46 , cap(SkPaint::kDefault_Cap)
47 , style(SkPaint::kFill_Style)
50 , pathEffect(nullptr) {
51 memset(&shape, 0, sizeof(Shape));
54 PathDescription::PathDescription(ShapeType type, const SkPaint* paint)
56 , join(paint->getStrokeJoin())
57 , cap(paint->getStrokeCap())
58 , style(paint->getStyle())
59 , miter(paint->getStrokeMiter())
60 , strokeWidth(paint->getStrokeWidth())
61 , pathEffect(paint->getPathEffect()) {
62 memset(&shape, 0, sizeof(Shape));
65 hash_t PathDescription::hash() const {
66 uint32_t hash = JenkinsHashMix(0, type);
67 hash = JenkinsHashMix(hash, join);
68 hash = JenkinsHashMix(hash, cap);
69 hash = JenkinsHashMix(hash, style);
70 hash = JenkinsHashMix(hash, android::hash_type(miter));
71 hash = JenkinsHashMix(hash, android::hash_type(strokeWidth));
72 hash = JenkinsHashMix(hash, android::hash_type(pathEffect));
73 hash = JenkinsHashMixBytes(hash, (uint8_t*) &shape, sizeof(Shape));
74 return JenkinsHashWhiten(hash);
77 ///////////////////////////////////////////////////////////////////////////////
79 ///////////////////////////////////////////////////////////////////////////////
81 bool PathCache::canDrawAsConvexPath(SkPath* path, const SkPaint* paint) {
82 // NOTE: This should only be used after PathTessellator handles joins properly
83 return paint->getPathEffect() == nullptr && path->getConvexity() == SkPath::kConvex_Convexity;
86 void PathCache::computePathBounds(const SkPath* path, const SkPaint* paint,
87 float& left, float& top, float& offset, uint32_t& width, uint32_t& height) {
88 const SkRect& bounds = path->getBounds();
89 PathCache::computeBounds(bounds, paint, left, top, offset, width, height);
92 void PathCache::computeBounds(const SkRect& bounds, const SkPaint* paint,
93 float& left, float& top, float& offset, uint32_t& width, uint32_t& height) {
94 const float pathWidth = fmax(bounds.width(), 1.0f);
95 const float pathHeight = fmax(bounds.height(), 1.0f);
100 offset = (int) floorf(fmax(paint->getStrokeWidth(), 1.0f) * 1.5f + 0.5f);
102 width = uint32_t(pathWidth + offset * 2.0 + 0.5);
103 height = uint32_t(pathHeight + offset * 2.0 + 0.5);
106 static void initBitmap(SkBitmap& bitmap, uint32_t width, uint32_t height) {
107 bitmap.allocPixels(SkImageInfo::MakeA8(width, height));
108 bitmap.eraseColor(0);
111 static void initPaint(SkPaint& paint) {
112 // Make sure the paint is opaque, color, alpha, filter, etc.
113 // will be applied later when compositing the alpha8 texture
114 paint.setColor(SK_ColorBLACK);
116 paint.setColorFilter(nullptr);
117 paint.setMaskFilter(nullptr);
118 paint.setShader(nullptr);
119 SkXfermode* mode = SkXfermode::Create(SkXfermode::kSrc_Mode);
120 SkSafeUnref(paint.setXfermode(mode));
123 static void drawPath(const SkPath *path, const SkPaint* paint, SkBitmap& bitmap,
124 float left, float top, float offset, uint32_t width, uint32_t height) {
125 initBitmap(bitmap, width, height);
127 SkPaint pathPaint(*paint);
128 initPaint(pathPaint);
130 SkCanvas canvas(bitmap);
131 canvas.translate(-left + offset, -top + offset);
132 canvas.drawPath(*path, pathPaint);
135 ///////////////////////////////////////////////////////////////////////////////
136 // Cache constructor/destructor
137 ///////////////////////////////////////////////////////////////////////////////
139 PathCache::PathCache():
140 mCache(LruCache<PathDescription, PathTexture*>::kUnlimitedCapacity),
141 mSize(0), mMaxSize(MB(DEFAULT_PATH_CACHE_SIZE)) {
142 char property[PROPERTY_VALUE_MAX];
143 if (property_get(PROPERTY_PATH_CACHE_SIZE, property, nullptr) > 0) {
144 INIT_LOGD(" Setting %s cache size to %sMB", name, property);
145 setMaxSize(MB(atof(property)));
147 INIT_LOGD(" Using default %s cache size of %.2fMB", name, DEFAULT_PATH_CACHE_SIZE);
150 mCache.setOnEntryRemovedListener(this);
152 GLint maxTextureSize;
153 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
154 mMaxTextureSize = maxTextureSize;
156 mDebugEnabled = readDebugLevel() & kDebugCaches;
159 PathCache::~PathCache() {
163 ///////////////////////////////////////////////////////////////////////////////
165 ///////////////////////////////////////////////////////////////////////////////
167 uint32_t PathCache::getSize() {
171 uint32_t PathCache::getMaxSize() {
175 void PathCache::setMaxSize(uint32_t maxSize) {
177 while (mSize > mMaxSize) {
178 mCache.removeOldest();
182 ///////////////////////////////////////////////////////////////////////////////
184 ///////////////////////////////////////////////////////////////////////////////
186 void PathCache::operator()(PathDescription& entry, PathTexture*& texture) {
187 removeTexture(texture);
190 ///////////////////////////////////////////////////////////////////////////////
192 ///////////////////////////////////////////////////////////////////////////////
194 void PathCache::removeTexture(PathTexture* texture) {
196 const uint32_t size = texture->width * texture->height;
198 // If there is a pending task we must wait for it to return
199 // before attempting our cleanup
200 const sp<Task<SkBitmap*> >& task = texture->task();
201 if (task != nullptr) {
203 texture->clearTask();
205 // If there is a pending task, the path was not added
206 // to the cache and the size wasn't increased
208 ALOGE("Removing path texture of size %d will leave "
209 "the cache in an inconsistent state", size);
214 PATH_LOGD("PathCache::delete name, size, mSize = %d, %d, %d",
215 texture->id, size, mSize);
217 ALOGD("Shape deleted, size = %d", size);
221 Caches::getInstance().textureState().deleteTexture(texture->id);
227 void PathCache::purgeCache(uint32_t width, uint32_t height) {
228 const uint32_t size = width * height;
229 // Don't even try to cache a bitmap that's bigger than the cache
230 if (size < mMaxSize) {
231 while (mSize + size > mMaxSize) {
232 mCache.removeOldest();
237 void PathCache::trim() {
238 while (mSize > mMaxSize) {
239 mCache.removeOldest();
243 PathTexture* PathCache::addTexture(const PathDescription& entry, const SkPath *path,
244 const SkPaint* paint) {
245 ATRACE_NAME("Generate Path Texture");
247 float left, top, offset;
248 uint32_t width, height;
249 computePathBounds(path, paint, left, top, offset, width, height);
251 if (!checkTextureSize(width, height)) return nullptr;
253 purgeCache(width, height);
256 drawPath(path, paint, bitmap, left, top, offset, width, height);
258 PathTexture* texture = new PathTexture(Caches::getInstance(),
259 left, top, offset, width, height,
260 path->getGenerationID());
261 generateTexture(entry, &bitmap, texture);
266 void PathCache::generateTexture(const PathDescription& entry, SkBitmap* bitmap,
267 PathTexture* texture, bool addToCache) {
268 generateTexture(*bitmap, texture);
270 uint32_t size = texture->width * texture->height;
271 if (size < mMaxSize) {
273 PATH_LOGD("PathCache::get/create: name, size, mSize = %d, %d, %d",
274 texture->id, size, mSize);
276 ALOGD("Shape created, size = %d", size);
279 mCache.put(entry, texture);
282 // It's okay to add a texture that's bigger than the cache since
283 // we'll trim the cache later when addToCache is set to false
287 texture->cleanup = true;
291 void PathCache::clear() {
295 void PathCache::generateTexture(SkBitmap& bitmap, Texture* texture) {
296 SkAutoLockPixels alp(bitmap);
297 if (!bitmap.readyToDraw()) {
298 ALOGE("Cannot generate texture from bitmap");
302 glGenTextures(1, &texture->id);
304 Caches::getInstance().textureState().bindTexture(texture->id);
305 // Textures are Alpha8
306 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
308 texture->blend = true;
309 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texture->width, texture->height, 0,
310 GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.getPixels());
312 texture->setFilter(GL_LINEAR);
313 texture->setWrap(GL_CLAMP_TO_EDGE);
316 ///////////////////////////////////////////////////////////////////////////////
318 ///////////////////////////////////////////////////////////////////////////////
320 PathCache::PathProcessor::PathProcessor(Caches& caches):
321 TaskProcessor<SkBitmap*>(&caches.tasks), mMaxTextureSize(caches.maxTextureSize) {
324 void PathCache::PathProcessor::onProcess(const sp<Task<SkBitmap*> >& task) {
325 PathTask* t = static_cast<PathTask*>(task.get());
326 ATRACE_NAME("pathPrecache");
328 float left, top, offset;
329 uint32_t width, height;
330 PathCache::computePathBounds(&t->path, &t->paint, left, top, offset, width, height);
332 PathTexture* texture = t->texture;
333 texture->left = left;
335 texture->offset = offset;
336 texture->width = width;
337 texture->height = height;
339 if (width <= mMaxTextureSize && height <= mMaxTextureSize) {
340 SkBitmap* bitmap = new SkBitmap();
341 drawPath(&t->path, &t->paint, *bitmap, left, top, offset, width, height);
342 t->setResult(bitmap);
346 t->setResult(nullptr);
350 ///////////////////////////////////////////////////////////////////////////////
352 ///////////////////////////////////////////////////////////////////////////////
354 void PathCache::removeDeferred(const SkPath* path) {
355 Mutex::Autolock l(mLock);
356 mGarbage.push(path->getGenerationID());
359 void PathCache::clearGarbage() {
360 Vector<PathDescription> pathsToRemove;
362 { // scope for the mutex
363 Mutex::Autolock l(mLock);
364 size_t count = mGarbage.size();
365 for (size_t i = 0; i < count; i++) {
366 const uint32_t generationID = mGarbage.itemAt(i);
368 LruCache<PathDescription, PathTexture*>::Iterator iter(mCache);
369 while (iter.next()) {
370 const PathDescription& key = iter.key();
371 if (key.type == kShapePath && key.shape.path.mGenerationID == generationID) {
372 pathsToRemove.push(key);
379 for (size_t i = 0; i < pathsToRemove.size(); i++) {
380 mCache.remove(pathsToRemove.itemAt(i));
384 PathTexture* PathCache::get(const SkPath* path, const SkPaint* paint) {
385 PathDescription entry(kShapePath, paint);
386 entry.shape.path.mGenerationID = path->getGenerationID();
388 PathTexture* texture = mCache.get(entry);
391 texture = addTexture(entry, path, paint);
393 // A bitmap is attached to the texture, this means we need to
394 // upload it as a GL texture
395 const sp<Task<SkBitmap*> >& task = texture->task();
396 if (task != nullptr) {
397 // But we must first wait for the worker thread to be done
398 // producing the bitmap, so let's wait
399 SkBitmap* bitmap = task->getResult();
401 generateTexture(entry, bitmap, texture, false);
402 texture->clearTask();
404 ALOGW("Path too large to be rendered into a texture");
405 texture->clearTask();
407 mCache.remove(entry);
415 void PathCache::precache(const SkPath* path, const SkPaint* paint) {
416 if (!Caches::getInstance().tasks.canRunTasks()) {
420 PathDescription entry(kShapePath, paint);
421 entry.shape.path.mGenerationID = path->getGenerationID();
423 PathTexture* texture = mCache.get(entry);
425 bool generate = false;
431 // It is important to specify the generation ID so we do not
432 // attempt to precache the same path several times
433 texture = new PathTexture(Caches::getInstance(), path->getGenerationID());
434 sp<PathTask> task = new PathTask(path, paint, texture);
435 texture->setTask(task);
437 // During the precaching phase we insert path texture objects into
438 // the cache that do not point to any GL texture. They are instead
439 // treated as a task for the precaching worker thread. This is why
440 // we do not check the cache limit when inserting these objects.
441 // The conversion into GL texture will happen in get(), when a client
442 // asks for a path texture. This is also when the cache limit will
444 mCache.put(entry, texture);
446 if (mProcessor == nullptr) {
447 mProcessor = new PathProcessor(Caches::getInstance());
449 if (!mProcessor->add(task)) {
450 mProcessor->process(task);
455 ///////////////////////////////////////////////////////////////////////////////
457 ///////////////////////////////////////////////////////////////////////////////
459 PathTexture* PathCache::getRoundRect(float width, float height,
460 float rx, float ry, const SkPaint* paint) {
461 PathDescription entry(kShapeRoundRect, paint);
462 entry.shape.roundRect.mWidth = width;
463 entry.shape.roundRect.mHeight = height;
464 entry.shape.roundRect.mRx = rx;
465 entry.shape.roundRect.mRy = ry;
467 PathTexture* texture = get(entry);
472 r.set(0.0f, 0.0f, width, height);
473 path.addRoundRect(r, rx, ry, SkPath::kCW_Direction);
475 texture = addTexture(entry, &path, paint);
481 ///////////////////////////////////////////////////////////////////////////////
483 ///////////////////////////////////////////////////////////////////////////////
485 PathTexture* PathCache::getCircle(float radius, const SkPaint* paint) {
486 PathDescription entry(kShapeCircle, paint);
487 entry.shape.circle.mRadius = radius;
489 PathTexture* texture = get(entry);
493 path.addCircle(radius, radius, radius, SkPath::kCW_Direction);
495 texture = addTexture(entry, &path, paint);
501 ///////////////////////////////////////////////////////////////////////////////
503 ///////////////////////////////////////////////////////////////////////////////
505 PathTexture* PathCache::getOval(float width, float height, const SkPaint* paint) {
506 PathDescription entry(kShapeOval, paint);
507 entry.shape.oval.mWidth = width;
508 entry.shape.oval.mHeight = height;
510 PathTexture* texture = get(entry);
515 r.set(0.0f, 0.0f, width, height);
516 path.addOval(r, SkPath::kCW_Direction);
518 texture = addTexture(entry, &path, paint);
524 ///////////////////////////////////////////////////////////////////////////////
526 ///////////////////////////////////////////////////////////////////////////////
528 PathTexture* PathCache::getRect(float width, float height, const SkPaint* paint) {
529 PathDescription entry(kShapeRect, paint);
530 entry.shape.rect.mWidth = width;
531 entry.shape.rect.mHeight = height;
533 PathTexture* texture = get(entry);
538 r.set(0.0f, 0.0f, width, height);
539 path.addRect(r, SkPath::kCW_Direction);
541 texture = addTexture(entry, &path, paint);
547 ///////////////////////////////////////////////////////////////////////////////
549 ///////////////////////////////////////////////////////////////////////////////
551 PathTexture* PathCache::getArc(float width, float height,
552 float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint) {
553 PathDescription entry(kShapeArc, paint);
554 entry.shape.arc.mWidth = width;
555 entry.shape.arc.mHeight = height;
556 entry.shape.arc.mStartAngle = startAngle;
557 entry.shape.arc.mSweepAngle = sweepAngle;
558 entry.shape.arc.mUseCenter = useCenter;
560 PathTexture* texture = get(entry);
565 r.set(0.0f, 0.0f, width, height);
567 path.moveTo(r.centerX(), r.centerY());
569 path.arcTo(r, startAngle, sweepAngle, !useCenter);
574 texture = addTexture(entry, &path, paint);
580 }; // namespace uirenderer
581 }; // namespace android