PathCache.cpp revision 4a3b0c7587dc995e00ed4e7d7ed61544f7715d2c
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 = floorf(bounds.fLeft); 131 texture->top = floorf(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 , mTexNum(0) { 187 mCache.setOnEntryRemovedListener(this); 188 189 GLint maxTextureSize; 190 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); 191 mMaxTextureSize = maxTextureSize; 192 193 mDebugEnabled = Properties::debugLevel & kDebugCaches; 194} 195 196PathCache::~PathCache() { 197 mCache.clear(); 198} 199 200/////////////////////////////////////////////////////////////////////////////// 201// Size management 202/////////////////////////////////////////////////////////////////////////////// 203 204uint32_t PathCache::getSize() { 205 return mSize; 206} 207 208uint32_t PathCache::getMaxSize() { 209 return mMaxSize; 210} 211 212/////////////////////////////////////////////////////////////////////////////// 213// Callbacks 214/////////////////////////////////////////////////////////////////////////////// 215 216void PathCache::operator()(PathDescription& entry, PathTexture*& texture) { 217 removeTexture(texture); 218} 219 220/////////////////////////////////////////////////////////////////////////////// 221// Caching 222/////////////////////////////////////////////////////////////////////////////// 223 224void PathCache::removeTexture(PathTexture* texture) { 225 if (texture) { 226 const uint32_t size = texture->width() * texture->height(); 227 228 // If there is a pending task we must wait for it to return 229 // before attempting our cleanup 230 const sp<Task<SkBitmap*> >& task = texture->task(); 231 if (task != nullptr) { 232 task->getResult(); 233 texture->clearTask(); 234 } else { 235 // If there is a pending task, the path was not added 236 // to the cache and the size wasn't increased 237 if (size > mSize) { 238 ALOGE("Removing path texture of size %d will leave " 239 "the cache in an inconsistent state", size); 240 } 241 mSize -= size; 242 mTexNum--; 243 } 244 245 PATH_LOGD("PathCache::delete name, size, mSize = %d, %d, %d", 246 texture->id, size, mSize); 247 if (mDebugEnabled) { 248 ALOGD("Shape deleted, size = %d", size); 249 } 250 251 texture->deleteTexture(); 252 delete texture; 253 } 254} 255 256void PathCache::purgeCache(uint32_t width, uint32_t height) { 257 const uint32_t size = width * height; 258 // Don't even try to cache a bitmap that's bigger than the cache 259 if (size < mMaxSize) { 260 while (mSize + size > mMaxSize) { 261 mCache.removeOldest(); 262 } 263 } 264} 265 266void PathCache::trim() { 267 while (mSize > mMaxSize || mTexNum > DEFAULT_PATH_TEXTURE_CAP) { 268 mCache.removeOldest(); 269 } 270} 271 272PathTexture* PathCache::addTexture(const PathDescription& entry, const SkPath *path, 273 const SkPaint* paint) { 274 ATRACE_NAME("Generate Path Texture"); 275 276 PathTexture* texture = new PathTexture(Caches::getInstance(), path->getGenerationID()); 277 std::unique_ptr<SkBitmap> bitmap(drawPath(path, paint, texture, mMaxTextureSize)); 278 if (!bitmap.get()) { 279 delete texture; 280 return nullptr; 281 } 282 283 purgeCache(bitmap->width(), bitmap->height()); 284 generateTexture(entry, bitmap.get(), texture); 285 return texture; 286} 287 288void PathCache::generateTexture(const PathDescription& entry, SkBitmap* bitmap, 289 PathTexture* texture, bool addToCache) { 290 generateTexture(*bitmap, texture); 291 292 // Note here that we upload to a texture even if it's bigger than mMaxSize. 293 // Such an entry in mCache will only be temporary, since it will be evicted 294 // immediately on trim, or on any other Path entering the cache. 295 uint32_t size = texture->width() * texture->height(); 296 mSize += size; 297 PATH_LOGD("PathCache::get/create: name, size, mSize = %d, %d, %d", 298 texture->id, size, mSize); 299 if (mDebugEnabled) { 300 ALOGD("Shape created, size = %d", size); 301 } 302 if (addToCache) { 303 mCache.put(entry, texture); 304 } 305} 306 307void PathCache::clear() { 308 mCache.clear(); 309} 310 311void PathCache::generateTexture(SkBitmap& bitmap, Texture* texture) { 312 ATRACE_NAME("Upload Path Texture"); 313 texture->upload(bitmap); 314 texture->setFilter(GL_LINEAR); 315 mTexNum++; 316} 317 318/////////////////////////////////////////////////////////////////////////////// 319// Path precaching 320/////////////////////////////////////////////////////////////////////////////// 321 322PathCache::PathProcessor::PathProcessor(Caches& caches): 323 TaskProcessor<SkBitmap*>(&caches.tasks), mMaxTextureSize(caches.maxTextureSize) { 324} 325 326void PathCache::PathProcessor::onProcess(const sp<Task<SkBitmap*> >& task) { 327 PathTask* t = static_cast<PathTask*>(task.get()); 328 ATRACE_NAME("pathPrecache"); 329 330 t->setResult(drawPath(&t->path, &t->paint, t->texture, mMaxTextureSize)); 331} 332 333/////////////////////////////////////////////////////////////////////////////// 334// Paths 335/////////////////////////////////////////////////////////////////////////////// 336 337void PathCache::removeDeferred(const SkPath* path) { 338 Mutex::Autolock l(mLock); 339 mGarbage.push_back(path->getGenerationID()); 340} 341 342void PathCache::clearGarbage() { 343 Vector<PathDescription> pathsToRemove; 344 345 { // scope for the mutex 346 Mutex::Autolock l(mLock); 347 for (const uint32_t generationID : mGarbage) { 348 LruCache<PathDescription, PathTexture*>::Iterator iter(mCache); 349 while (iter.next()) { 350 const PathDescription& key = iter.key(); 351 if (key.type == ShapeType::Path && key.shape.path.mGenerationID == generationID) { 352 pathsToRemove.push(key); 353 } 354 } 355 } 356 mGarbage.clear(); 357 } 358 359 for (size_t i = 0; i < pathsToRemove.size(); i++) { 360 mCache.remove(pathsToRemove.itemAt(i)); 361 } 362} 363 364PathTexture* PathCache::get(const SkPath* path, const SkPaint* paint) { 365 PathDescription entry(ShapeType::Path, paint); 366 entry.shape.path.mGenerationID = path->getGenerationID(); 367 368 PathTexture* texture = mCache.get(entry); 369 370 if (!texture) { 371 texture = addTexture(entry, path, paint); 372 } else { 373 // A bitmap is attached to the texture, this means we need to 374 // upload it as a GL texture 375 const sp<Task<SkBitmap*> >& task = texture->task(); 376 if (task != nullptr) { 377 // But we must first wait for the worker thread to be done 378 // producing the bitmap, so let's wait 379 SkBitmap* bitmap = task->getResult(); 380 if (bitmap) { 381 generateTexture(entry, bitmap, texture, false); 382 texture->clearTask(); 383 } else { 384 texture->clearTask(); 385 texture = nullptr; 386 mCache.remove(entry); 387 } 388 } 389 } 390 391 return texture; 392} 393 394void PathCache::remove(const SkPath* path, const SkPaint* paint) { 395 PathDescription entry(ShapeType::Path, paint); 396 entry.shape.path.mGenerationID = path->getGenerationID(); 397 mCache.remove(entry); 398} 399 400void PathCache::precache(const SkPath* path, const SkPaint* paint) { 401 if (!Caches::getInstance().tasks.canRunTasks()) { 402 return; 403 } 404 405 PathDescription entry(ShapeType::Path, paint); 406 entry.shape.path.mGenerationID = path->getGenerationID(); 407 408 PathTexture* texture = mCache.get(entry); 409 410 bool generate = false; 411 if (!texture) { 412 generate = true; 413 } 414 415 if (generate) { 416 // It is important to specify the generation ID so we do not 417 // attempt to precache the same path several times 418 texture = new PathTexture(Caches::getInstance(), path->getGenerationID()); 419 sp<PathTask> task = new PathTask(path, paint, texture); 420 texture->setTask(task); 421 422 // During the precaching phase we insert path texture objects into 423 // the cache that do not point to any GL texture. They are instead 424 // treated as a task for the precaching worker thread. This is why 425 // we do not check the cache limit when inserting these objects. 426 // The conversion into GL texture will happen in get(), when a client 427 // asks for a path texture. This is also when the cache limit will 428 // be enforced. 429 mCache.put(entry, texture); 430 431 if (mProcessor == nullptr) { 432 mProcessor = new PathProcessor(Caches::getInstance()); 433 } 434 mProcessor->add(task); 435 } 436} 437 438/////////////////////////////////////////////////////////////////////////////// 439// Rounded rects 440/////////////////////////////////////////////////////////////////////////////// 441 442PathTexture* PathCache::getRoundRect(float width, float height, 443 float rx, float ry, const SkPaint* paint) { 444 PathDescription entry(ShapeType::RoundRect, paint); 445 entry.shape.roundRect.mWidth = width; 446 entry.shape.roundRect.mHeight = height; 447 entry.shape.roundRect.mRx = rx; 448 entry.shape.roundRect.mRy = ry; 449 450 PathTexture* texture = get(entry); 451 452 if (!texture) { 453 SkPath path; 454 SkRect r; 455 r.set(0.0f, 0.0f, width, height); 456 path.addRoundRect(r, rx, ry, SkPath::kCW_Direction); 457 458 texture = addTexture(entry, &path, paint); 459 } 460 461 return texture; 462} 463 464/////////////////////////////////////////////////////////////////////////////// 465// Circles 466/////////////////////////////////////////////////////////////////////////////// 467 468PathTexture* PathCache::getCircle(float radius, const SkPaint* paint) { 469 PathDescription entry(ShapeType::Circle, paint); 470 entry.shape.circle.mRadius = radius; 471 472 PathTexture* texture = get(entry); 473 474 if (!texture) { 475 SkPath path; 476 path.addCircle(radius, radius, radius, SkPath::kCW_Direction); 477 478 texture = addTexture(entry, &path, paint); 479 } 480 481 return texture; 482} 483 484/////////////////////////////////////////////////////////////////////////////// 485// Ovals 486/////////////////////////////////////////////////////////////////////////////// 487 488PathTexture* PathCache::getOval(float width, float height, const SkPaint* paint) { 489 PathDescription entry(ShapeType::Oval, paint); 490 entry.shape.oval.mWidth = width; 491 entry.shape.oval.mHeight = height; 492 493 PathTexture* texture = get(entry); 494 495 if (!texture) { 496 SkPath path; 497 SkRect r; 498 r.set(0.0f, 0.0f, width, height); 499 path.addOval(r, SkPath::kCW_Direction); 500 501 texture = addTexture(entry, &path, paint); 502 } 503 504 return texture; 505} 506 507/////////////////////////////////////////////////////////////////////////////// 508// Rects 509/////////////////////////////////////////////////////////////////////////////// 510 511PathTexture* PathCache::getRect(float width, float height, const SkPaint* paint) { 512 PathDescription entry(ShapeType::Rect, paint); 513 entry.shape.rect.mWidth = width; 514 entry.shape.rect.mHeight = height; 515 516 PathTexture* texture = get(entry); 517 518 if (!texture) { 519 SkPath path; 520 SkRect r; 521 r.set(0.0f, 0.0f, width, height); 522 path.addRect(r, SkPath::kCW_Direction); 523 524 texture = addTexture(entry, &path, paint); 525 } 526 527 return texture; 528} 529 530/////////////////////////////////////////////////////////////////////////////// 531// Arcs 532/////////////////////////////////////////////////////////////////////////////// 533 534PathTexture* PathCache::getArc(float width, float height, 535 float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint) { 536 PathDescription entry(ShapeType::Arc, paint); 537 entry.shape.arc.mWidth = width; 538 entry.shape.arc.mHeight = height; 539 entry.shape.arc.mStartAngle = startAngle; 540 entry.shape.arc.mSweepAngle = sweepAngle; 541 entry.shape.arc.mUseCenter = useCenter; 542 543 PathTexture* texture = get(entry); 544 545 if (!texture) { 546 SkPath path; 547 SkRect r; 548 r.set(0.0f, 0.0f, width, height); 549 if (useCenter) { 550 path.moveTo(r.centerX(), r.centerY()); 551 } 552 path.arcTo(r, startAngle, sweepAngle, !useCenter); 553 if (useCenter) { 554 path.close(); 555 } 556 557 texture = addTexture(entry, &path, paint); 558 } 559 560 return texture; 561} 562 563}; // namespace uirenderer 564}; // namespace android 565