PathCache.cpp revision 4b505376cb1d77de39d12f4f8bc88e111fbbdc5f
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#define LOG_TAG "OpenGLRenderer" 18#define ATRACE_TAG ATRACE_TAG_VIEW 19 20#include <SkBitmap.h> 21#include <SkCanvas.h> 22#include <SkColor.h> 23#include <SkPaint.h> 24#include <SkPath.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 36namespace android { 37namespace uirenderer { 38 39/////////////////////////////////////////////////////////////////////////////// 40// Cache entries 41/////////////////////////////////////////////////////////////////////////////// 42 43PathDescription::PathDescription() 44 : type(kShapeNone) 45 , join(SkPaint::kDefault_Join) 46 , cap(SkPaint::kDefault_Cap) 47 , style(SkPaint::kFill_Style) 48 , miter(4.0f) 49 , strokeWidth(1.0f) 50 , pathEffect(nullptr) { 51 memset(&shape, 0, sizeof(Shape)); 52} 53 54PathDescription::PathDescription(ShapeType type, const SkPaint* paint) 55 : type(type) 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)); 63} 64 65hash_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); 75} 76 77/////////////////////////////////////////////////////////////////////////////// 78// Utilities 79/////////////////////////////////////////////////////////////////////////////// 80 81bool 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; 84} 85 86void 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); 90} 91 92void 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 = std::max(bounds.width(), 1.0f); 95 const float pathHeight = std::max(bounds.height(), 1.0f); 96 97 left = bounds.fLeft; 98 top = bounds.fTop; 99 100 offset = (int) floorf(std::max(paint->getStrokeWidth(), 1.0f) * 1.5f + 0.5f); 101 102 width = uint32_t(pathWidth + offset * 2.0 + 0.5); 103 height = uint32_t(pathHeight + offset * 2.0 + 0.5); 104} 105 106static void initBitmap(SkBitmap& bitmap, uint32_t width, uint32_t height) { 107 bitmap.allocPixels(SkImageInfo::MakeA8(width, height)); 108 bitmap.eraseColor(0); 109} 110 111static 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); 115 paint.setAlpha(255); 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)); 121} 122 123static 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); 126 127 SkPaint pathPaint(*paint); 128 initPaint(pathPaint); 129 130 SkCanvas canvas(bitmap); 131 canvas.translate(-left + offset, -top + offset); 132 canvas.drawPath(*path, pathPaint); 133} 134 135/////////////////////////////////////////////////////////////////////////////// 136// Cache constructor/destructor 137/////////////////////////////////////////////////////////////////////////////// 138 139PathCache::PathCache(): 140 mCache(LruCache<PathDescription, PathTexture*>::kUnlimitedCapacity), 141 mSize(0), mMaxSize(MB(DEFAULT_PATH_CACHE_SIZE)), mTexNum(0) { 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 mMaxSize = MB(atof(property)); 146 } else { 147 INIT_LOGD(" Using default %s cache size of %.2fMB", name, DEFAULT_PATH_CACHE_SIZE); 148 } 149 150 mCache.setOnEntryRemovedListener(this); 151 152 GLint maxTextureSize; 153 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); 154 mMaxTextureSize = maxTextureSize; 155 156 mDebugEnabled = Properties::debugLevel & kDebugCaches; 157} 158 159PathCache::~PathCache() { 160 mCache.clear(); 161} 162 163/////////////////////////////////////////////////////////////////////////////// 164// Size management 165/////////////////////////////////////////////////////////////////////////////// 166 167uint32_t PathCache::getSize() { 168 return mSize; 169} 170 171uint32_t PathCache::getMaxSize() { 172 return mMaxSize; 173} 174 175/////////////////////////////////////////////////////////////////////////////// 176// Callbacks 177/////////////////////////////////////////////////////////////////////////////// 178 179void PathCache::operator()(PathDescription& entry, PathTexture*& texture) { 180 removeTexture(texture); 181} 182 183/////////////////////////////////////////////////////////////////////////////// 184// Caching 185/////////////////////////////////////////////////////////////////////////////// 186 187void PathCache::removeTexture(PathTexture* texture) { 188 if (texture) { 189 const uint32_t size = texture->width * texture->height; 190 191 // If there is a pending task we must wait for it to return 192 // before attempting our cleanup 193 const sp<Task<SkBitmap*> >& task = texture->task(); 194 if (task != nullptr) { 195 task->getResult(); 196 texture->clearTask(); 197 } else { 198 // If there is a pending task, the path was not added 199 // to the cache and the size wasn't increased 200 if (size > mSize) { 201 ALOGE("Removing path texture of size %d will leave " 202 "the cache in an inconsistent state", size); 203 } 204 mSize -= size; 205 mTexNum--; 206 } 207 208 PATH_LOGD("PathCache::delete name, size, mSize = %d, %d, %d", 209 texture->id, size, mSize); 210 if (mDebugEnabled) { 211 ALOGD("Shape deleted, size = %d", size); 212 } 213 214 if (texture->id) { 215 Caches::getInstance().textureState().deleteTexture(texture->id); 216 } 217 delete texture; 218 } 219} 220 221void PathCache::purgeCache(uint32_t width, uint32_t height) { 222 const uint32_t size = width * height; 223 // Don't even try to cache a bitmap that's bigger than the cache 224 if (size < mMaxSize) { 225 while (mSize + size > mMaxSize) { 226 mCache.removeOldest(); 227 } 228 } 229} 230 231void PathCache::trim() { 232 while (mSize > mMaxSize || mTexNum > DEFAULT_PATH_TEXTURE_CAP) { 233 mCache.removeOldest(); 234 } 235} 236 237PathTexture* PathCache::addTexture(const PathDescription& entry, const SkPath *path, 238 const SkPaint* paint) { 239 ATRACE_NAME("Generate Path Texture"); 240 241 float left, top, offset; 242 uint32_t width, height; 243 computePathBounds(path, paint, left, top, offset, width, height); 244 245 if (!checkTextureSize(width, height)) return nullptr; 246 247 purgeCache(width, height); 248 249 SkBitmap bitmap; 250 drawPath(path, paint, bitmap, left, top, offset, width, height); 251 252 PathTexture* texture = new PathTexture(Caches::getInstance(), 253 left, top, offset, width, height, 254 path->getGenerationID()); 255 generateTexture(entry, &bitmap, texture); 256 257 return texture; 258} 259 260void PathCache::generateTexture(const PathDescription& entry, SkBitmap* bitmap, 261 PathTexture* texture, bool addToCache) { 262 generateTexture(*bitmap, texture); 263 264 // Note here that we upload to a texture even if it's bigger than mMaxSize. 265 // Such an entry in mCache will only be temporary, since it will be evicted 266 // immediately on trim, or on any other Path entering the cache. 267 uint32_t size = texture->width * texture->height; 268 mSize += size; 269 PATH_LOGD("PathCache::get/create: name, size, mSize = %d, %d, %d", 270 texture->id, size, mSize); 271 if (mDebugEnabled) { 272 ALOGD("Shape created, size = %d", size); 273 } 274 if (addToCache) { 275 mCache.put(entry, texture); 276 } 277} 278 279void PathCache::clear() { 280 mCache.clear(); 281} 282 283void PathCache::generateTexture(SkBitmap& bitmap, Texture* texture) { 284 ATRACE_NAME("Upload Path Texture"); 285 SkAutoLockPixels alp(bitmap); 286 if (!bitmap.readyToDraw()) { 287 ALOGE("Cannot generate texture from bitmap"); 288 return; 289 } 290 291 glGenTextures(1, &texture->id); 292 293 Caches::getInstance().textureState().bindTexture(texture->id); 294 // Textures are Alpha8 295 glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 296 297 texture->blend = true; 298 glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texture->width, texture->height, 0, 299 GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.getPixels()); 300 301 texture->setFilter(GL_LINEAR); 302 texture->setWrap(GL_CLAMP_TO_EDGE); 303 mTexNum++; 304} 305 306/////////////////////////////////////////////////////////////////////////////// 307// Path precaching 308/////////////////////////////////////////////////////////////////////////////// 309 310PathCache::PathProcessor::PathProcessor(Caches& caches): 311 TaskProcessor<SkBitmap*>(&caches.tasks), mMaxTextureSize(caches.maxTextureSize) { 312} 313 314void PathCache::PathProcessor::onProcess(const sp<Task<SkBitmap*> >& task) { 315 PathTask* t = static_cast<PathTask*>(task.get()); 316 ATRACE_NAME("pathPrecache"); 317 318 float left, top, offset; 319 uint32_t width, height; 320 PathCache::computePathBounds(&t->path, &t->paint, left, top, offset, width, height); 321 322 PathTexture* texture = t->texture; 323 texture->left = left; 324 texture->top = top; 325 texture->offset = offset; 326 texture->width = width; 327 texture->height = height; 328 329 if (width <= mMaxTextureSize && height <= mMaxTextureSize) { 330 SkBitmap* bitmap = new SkBitmap(); 331 drawPath(&t->path, &t->paint, *bitmap, left, top, offset, width, height); 332 t->setResult(bitmap); 333 } else { 334 texture->width = 0; 335 texture->height = 0; 336 t->setResult(nullptr); 337 } 338} 339 340/////////////////////////////////////////////////////////////////////////////// 341// Paths 342/////////////////////////////////////////////////////////////////////////////// 343 344void PathCache::removeDeferred(const SkPath* path) { 345 Mutex::Autolock l(mLock); 346 mGarbage.push(path->getGenerationID()); 347} 348 349void PathCache::clearGarbage() { 350 Vector<PathDescription> pathsToRemove; 351 352 { // scope for the mutex 353 Mutex::Autolock l(mLock); 354 size_t count = mGarbage.size(); 355 for (size_t i = 0; i < count; i++) { 356 const uint32_t generationID = mGarbage.itemAt(i); 357 358 LruCache<PathDescription, PathTexture*>::Iterator iter(mCache); 359 while (iter.next()) { 360 const PathDescription& key = iter.key(); 361 if (key.type == kShapePath && key.shape.path.mGenerationID == generationID) { 362 pathsToRemove.push(key); 363 } 364 } 365 } 366 mGarbage.clear(); 367 } 368 369 for (size_t i = 0; i < pathsToRemove.size(); i++) { 370 mCache.remove(pathsToRemove.itemAt(i)); 371 } 372} 373 374PathTexture* PathCache::get(const SkPath* path, const SkPaint* paint) { 375 PathDescription entry(kShapePath, paint); 376 entry.shape.path.mGenerationID = path->getGenerationID(); 377 378 PathTexture* texture = mCache.get(entry); 379 380 if (!texture) { 381 texture = addTexture(entry, path, paint); 382 } else { 383 // A bitmap is attached to the texture, this means we need to 384 // upload it as a GL texture 385 const sp<Task<SkBitmap*> >& task = texture->task(); 386 if (task != nullptr) { 387 // But we must first wait for the worker thread to be done 388 // producing the bitmap, so let's wait 389 SkBitmap* bitmap = task->getResult(); 390 if (bitmap) { 391 generateTexture(entry, bitmap, texture, false); 392 texture->clearTask(); 393 } else { 394 ALOGW("Path too large to be rendered into a texture"); 395 texture->clearTask(); 396 texture = nullptr; 397 mCache.remove(entry); 398 } 399 } 400 } 401 402 return texture; 403} 404 405void PathCache::remove(const SkPath* path, const SkPaint* paint) 406{ 407 PathDescription entry(kShapePath, paint); 408 entry.shape.path.mGenerationID = path->getGenerationID(); 409 mCache.remove(entry); 410} 411 412void PathCache::precache(const SkPath* path, const SkPaint* paint) { 413 if (!Caches::getInstance().tasks.canRunTasks()) { 414 return; 415 } 416 417 PathDescription entry(kShapePath, paint); 418 entry.shape.path.mGenerationID = path->getGenerationID(); 419 420 PathTexture* texture = mCache.get(entry); 421 422 bool generate = false; 423 if (!texture) { 424 generate = true; 425 } 426 427 if (generate) { 428 // It is important to specify the generation ID so we do not 429 // attempt to precache the same path several times 430 texture = new PathTexture(Caches::getInstance(), path->getGenerationID()); 431 sp<PathTask> task = new PathTask(path, paint, texture); 432 texture->setTask(task); 433 434 // During the precaching phase we insert path texture objects into 435 // the cache that do not point to any GL texture. They are instead 436 // treated as a task for the precaching worker thread. This is why 437 // we do not check the cache limit when inserting these objects. 438 // The conversion into GL texture will happen in get(), when a client 439 // asks for a path texture. This is also when the cache limit will 440 // be enforced. 441 mCache.put(entry, texture); 442 443 if (mProcessor == nullptr) { 444 mProcessor = new PathProcessor(Caches::getInstance()); 445 } 446 mProcessor->add(task); 447 } 448} 449 450/////////////////////////////////////////////////////////////////////////////// 451// Rounded rects 452/////////////////////////////////////////////////////////////////////////////// 453 454PathTexture* PathCache::getRoundRect(float width, float height, 455 float rx, float ry, const SkPaint* paint) { 456 PathDescription entry(kShapeRoundRect, paint); 457 entry.shape.roundRect.mWidth = width; 458 entry.shape.roundRect.mHeight = height; 459 entry.shape.roundRect.mRx = rx; 460 entry.shape.roundRect.mRy = ry; 461 462 PathTexture* texture = get(entry); 463 464 if (!texture) { 465 SkPath path; 466 SkRect r; 467 r.set(0.0f, 0.0f, width, height); 468 path.addRoundRect(r, rx, ry, SkPath::kCW_Direction); 469 470 texture = addTexture(entry, &path, paint); 471 } 472 473 return texture; 474} 475 476/////////////////////////////////////////////////////////////////////////////// 477// Circles 478/////////////////////////////////////////////////////////////////////////////// 479 480PathTexture* PathCache::getCircle(float radius, const SkPaint* paint) { 481 PathDescription entry(kShapeCircle, paint); 482 entry.shape.circle.mRadius = radius; 483 484 PathTexture* texture = get(entry); 485 486 if (!texture) { 487 SkPath path; 488 path.addCircle(radius, radius, radius, SkPath::kCW_Direction); 489 490 texture = addTexture(entry, &path, paint); 491 } 492 493 return texture; 494} 495 496/////////////////////////////////////////////////////////////////////////////// 497// Ovals 498/////////////////////////////////////////////////////////////////////////////// 499 500PathTexture* PathCache::getOval(float width, float height, const SkPaint* paint) { 501 PathDescription entry(kShapeOval, paint); 502 entry.shape.oval.mWidth = width; 503 entry.shape.oval.mHeight = height; 504 505 PathTexture* texture = get(entry); 506 507 if (!texture) { 508 SkPath path; 509 SkRect r; 510 r.set(0.0f, 0.0f, width, height); 511 path.addOval(r, SkPath::kCW_Direction); 512 513 texture = addTexture(entry, &path, paint); 514 } 515 516 return texture; 517} 518 519/////////////////////////////////////////////////////////////////////////////// 520// Rects 521/////////////////////////////////////////////////////////////////////////////// 522 523PathTexture* PathCache::getRect(float width, float height, const SkPaint* paint) { 524 PathDescription entry(kShapeRect, paint); 525 entry.shape.rect.mWidth = width; 526 entry.shape.rect.mHeight = height; 527 528 PathTexture* texture = get(entry); 529 530 if (!texture) { 531 SkPath path; 532 SkRect r; 533 r.set(0.0f, 0.0f, width, height); 534 path.addRect(r, SkPath::kCW_Direction); 535 536 texture = addTexture(entry, &path, paint); 537 } 538 539 return texture; 540} 541 542/////////////////////////////////////////////////////////////////////////////// 543// Arcs 544/////////////////////////////////////////////////////////////////////////////// 545 546PathTexture* PathCache::getArc(float width, float height, 547 float startAngle, float sweepAngle, bool useCenter, const SkPaint* paint) { 548 PathDescription entry(kShapeArc, paint); 549 entry.shape.arc.mWidth = width; 550 entry.shape.arc.mHeight = height; 551 entry.shape.arc.mStartAngle = startAngle; 552 entry.shape.arc.mSweepAngle = sweepAngle; 553 entry.shape.arc.mUseCenter = useCenter; 554 555 PathTexture* texture = get(entry); 556 557 if (!texture) { 558 SkPath path; 559 SkRect r; 560 r.set(0.0f, 0.0f, width, height); 561 if (useCenter) { 562 path.moveTo(r.centerX(), r.centerY()); 563 } 564 path.arcTo(r, startAngle, sweepAngle, !useCenter); 565 if (useCenter) { 566 path.close(); 567 } 568 569 texture = addTexture(entry, &path, paint); 570 } 571 572 return texture; 573} 574 575}; // namespace uirenderer 576}; // namespace android 577