VectorDrawable.cpp revision 28d4ea558435b1b245bd5774c0db056a2ffdb385
1/* 2 * Copyright (C) 2015 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 "VectorDrawable.h" 18 19#include "PathParser.h" 20#include "SkImageInfo.h" 21#include "SkShader.h" 22#include <utils/Log.h> 23#include "utils/Macros.h" 24#include "utils/VectorDrawableUtils.h" 25 26#include <math.h> 27#include <string.h> 28 29namespace android { 30namespace uirenderer { 31namespace VectorDrawable { 32 33const int Tree::MAX_CACHED_BITMAP_SIZE = 2048; 34 35void Path::draw(SkCanvas* outCanvas, const SkMatrix& groupStackedMatrix, float scaleX, float scaleY) { 36 float matrixScale = getMatrixScale(groupStackedMatrix); 37 if (matrixScale == 0) { 38 // When either x or y is scaled to 0, we don't need to draw anything. 39 return; 40 } 41 42 const SkPath updatedPath = getUpdatedPath(); 43 SkMatrix pathMatrix(groupStackedMatrix); 44 pathMatrix.postScale(scaleX, scaleY); 45 46 //TODO: try apply the path matrix to the canvas instead of creating a new path. 47 SkPath renderPath; 48 renderPath.reset(); 49 renderPath.addPath(updatedPath, pathMatrix); 50 51 float minScale = fmin(scaleX, scaleY); 52 float strokeScale = minScale * matrixScale; 53 drawPath(outCanvas, renderPath, strokeScale, pathMatrix); 54} 55 56void Path::setPathData(const Data& data) { 57 if (mData == data) { 58 return; 59 } 60 // Updates the path data. Note that we don't generate a new Skia path right away 61 // because there are cases where the animation is changing the path data, but the view 62 // that hosts the VD has gone off screen, in which case we won't even draw. So we 63 // postpone the Skia path generation to the draw time. 64 mData = data; 65 mSkPathDirty = true; 66} 67 68void Path::dump() { 69 ALOGD("Path: %s has %zu points", mName.c_str(), mData.points.size()); 70} 71 72float Path::getMatrixScale(const SkMatrix& groupStackedMatrix) { 73 // Given unit vectors A = (0, 1) and B = (1, 0). 74 // After matrix mapping, we got A' and B'. Let theta = the angel b/t A' and B'. 75 // Therefore, the final scale we want is min(|A'| * sin(theta), |B'| * sin(theta)), 76 // which is (|A'| * |B'| * sin(theta)) / max (|A'|, |B'|); 77 // If max (|A'|, |B'|) = 0, that means either x or y has a scale of 0. 78 // 79 // For non-skew case, which is most of the cases, matrix scale is computing exactly the 80 // scale on x and y axis, and take the minimal of these two. 81 // For skew case, an unit square will mapped to a parallelogram. And this function will 82 // return the minimal height of the 2 bases. 83 SkVector skVectors[2]; 84 skVectors[0].set(0, 1); 85 skVectors[1].set(1, 0); 86 groupStackedMatrix.mapVectors(skVectors, 2); 87 float scaleX = hypotf(skVectors[0].fX, skVectors[0].fY); 88 float scaleY = hypotf(skVectors[1].fX, skVectors[1].fY); 89 float crossProduct = skVectors[0].cross(skVectors[1]); 90 float maxScale = fmax(scaleX, scaleY); 91 92 float matrixScale = 0; 93 if (maxScale > 0) { 94 matrixScale = fabs(crossProduct) / maxScale; 95 } 96 return matrixScale; 97} 98Path::Path(const char* pathStr, size_t strLength) { 99 PathParser::ParseResult result; 100 PathParser::getPathDataFromString(&mData, &result, pathStr, strLength); 101 if (!result.failureOccurred) { 102 VectorDrawableUtils::verbsToPath(&mSkPath, mData); 103 } 104} 105 106Path::Path(const Data& data) { 107 mData = data; 108 // Now we need to construct a path 109 VectorDrawableUtils::verbsToPath(&mSkPath, data); 110} 111 112Path::Path(const Path& path) : Node(path) { 113 mData = path.mData; 114 VectorDrawableUtils::verbsToPath(&mSkPath, mData); 115} 116 117bool Path::canMorph(const Data& morphTo) { 118 return VectorDrawableUtils::canMorph(mData, morphTo); 119} 120 121bool Path::canMorph(const Path& path) { 122 return canMorph(path.mData); 123} 124 125const SkPath& Path::getUpdatedPath() { 126 if (mSkPathDirty) { 127 mSkPath.reset(); 128 VectorDrawableUtils::verbsToPath(&mSkPath, mData); 129 mSkPathDirty = false; 130 } 131 return mSkPath; 132} 133 134void Path::setPath(const char* pathStr, size_t strLength) { 135 PathParser::ParseResult result; 136 mSkPathDirty = true; 137 PathParser::getPathDataFromString(&mData, &result, pathStr, strLength); 138} 139 140FullPath::FullPath(const FullPath& path) : Path(path) { 141 mStrokeWidth = path.mStrokeWidth; 142 mStrokeColor = path.mStrokeColor; 143 mStrokeAlpha = path.mStrokeAlpha; 144 mFillColor = path.mFillColor; 145 mFillAlpha = path.mFillAlpha; 146 mTrimPathStart = path.mTrimPathStart; 147 mTrimPathEnd = path.mTrimPathEnd; 148 mTrimPathOffset = path.mTrimPathOffset; 149 mStrokeMiterLimit = path.mStrokeMiterLimit; 150 mStrokeLineCap = path.mStrokeLineCap; 151 mStrokeLineJoin = path.mStrokeLineJoin; 152 153 SkRefCnt_SafeAssign(mStrokeGradient, path.mStrokeGradient); 154 SkRefCnt_SafeAssign(mFillGradient, path.mFillGradient); 155} 156 157const SkPath& FullPath::getUpdatedPath() { 158 if (!mSkPathDirty && !mTrimDirty) { 159 return mTrimmedSkPath; 160 } 161 Path::getUpdatedPath(); 162 if (mTrimPathStart != 0.0f || mTrimPathEnd != 1.0f) { 163 applyTrim(); 164 return mTrimmedSkPath; 165 } else { 166 return mSkPath; 167 } 168} 169 170void FullPath::updateProperties(float strokeWidth, SkColor strokeColor, float strokeAlpha, 171 SkColor fillColor, float fillAlpha, float trimPathStart, float trimPathEnd, 172 float trimPathOffset, float strokeMiterLimit, int strokeLineCap, int strokeLineJoin) { 173 mStrokeWidth = strokeWidth; 174 mStrokeColor = strokeColor; 175 mStrokeAlpha = strokeAlpha; 176 mFillColor = fillColor; 177 mFillAlpha = fillAlpha; 178 mStrokeMiterLimit = strokeMiterLimit; 179 mStrokeLineCap = SkPaint::Cap(strokeLineCap); 180 mStrokeLineJoin = SkPaint::Join(strokeLineJoin); 181 182 // If any trim property changes, mark trim dirty and update the trim path 183 setTrimPathStart(trimPathStart); 184 setTrimPathEnd(trimPathEnd); 185 setTrimPathOffset(trimPathOffset); 186} 187 188inline SkColor applyAlpha(SkColor color, float alpha) { 189 int alphaBytes = SkColorGetA(color); 190 return SkColorSetA(color, alphaBytes * alpha); 191} 192 193void FullPath::drawPath(SkCanvas* outCanvas, const SkPath& renderPath, float strokeScale, 194 const SkMatrix& matrix){ 195 // Draw path's fill, if fill color or gradient is valid 196 bool needsFill = false; 197 if (mFillGradient != nullptr) { 198 mPaint.setColor(applyAlpha(SK_ColorBLACK, mFillAlpha)); 199 SkShader* newShader = mFillGradient->newWithLocalMatrix(matrix); 200 mPaint.setShader(newShader); 201 needsFill = true; 202 } else if (mFillColor != SK_ColorTRANSPARENT) { 203 mPaint.setColor(applyAlpha(mFillColor, mFillAlpha)); 204 needsFill = true; 205 } 206 207 if (needsFill) { 208 mPaint.setStyle(SkPaint::Style::kFill_Style); 209 mPaint.setAntiAlias(true); 210 outCanvas->drawPath(renderPath, mPaint); 211 } 212 213 // Draw path's stroke, if stroke color or gradient is valid 214 bool needsStroke = false; 215 if (mStrokeGradient != nullptr) { 216 mPaint.setColor(applyAlpha(SK_ColorBLACK, mStrokeAlpha)); 217 SkShader* newShader = mStrokeGradient->newWithLocalMatrix(matrix); 218 mPaint.setShader(newShader); 219 needsStroke = true; 220 } else if (mStrokeColor != SK_ColorTRANSPARENT) { 221 mPaint.setColor(applyAlpha(mStrokeColor, mStrokeAlpha)); 222 needsStroke = true; 223 } 224 if (needsStroke) { 225 mPaint.setStyle(SkPaint::Style::kStroke_Style); 226 mPaint.setAntiAlias(true); 227 mPaint.setStrokeJoin(mStrokeLineJoin); 228 mPaint.setStrokeCap(mStrokeLineCap); 229 mPaint.setStrokeMiter(mStrokeMiterLimit); 230 mPaint.setStrokeWidth(mStrokeWidth * strokeScale); 231 outCanvas->drawPath(renderPath, mPaint); 232 } 233} 234 235/** 236 * Applies trimming to the specified path. 237 */ 238void FullPath::applyTrim() { 239 if (mTrimPathStart == 0.0f && mTrimPathEnd == 1.0f) { 240 // No trimming necessary. 241 return; 242 } 243 SkPathMeasure measure(mSkPath, false); 244 float len = SkScalarToFloat(measure.getLength()); 245 float start = len * fmod((mTrimPathStart + mTrimPathOffset), 1.0f); 246 float end = len * fmod((mTrimPathEnd + mTrimPathOffset), 1.0f); 247 248 mTrimmedSkPath.reset(); 249 if (start > end) { 250 measure.getSegment(start, len, &mTrimmedSkPath, true); 251 measure.getSegment(0, end, &mTrimmedSkPath, true); 252 } else { 253 measure.getSegment(start, end, &mTrimmedSkPath, true); 254 } 255 mTrimDirty = false; 256} 257 258inline int putData(int8_t* outBytes, int startIndex, float value) { 259 int size = sizeof(float); 260 memcpy(&outBytes[startIndex], &value, size); 261 return size; 262} 263 264inline int putData(int8_t* outBytes, int startIndex, int value) { 265 int size = sizeof(int); 266 memcpy(&outBytes[startIndex], &value, size); 267 return size; 268} 269 270struct FullPathProperties { 271 // TODO: Consider storing full path properties in this struct instead of the fields. 272 float strokeWidth; 273 SkColor strokeColor; 274 float strokeAlpha; 275 SkColor fillColor; 276 float fillAlpha; 277 float trimPathStart; 278 float trimPathEnd; 279 float trimPathOffset; 280 int32_t strokeLineCap; 281 int32_t strokeLineJoin; 282 float strokeMiterLimit; 283}; 284 285REQUIRE_COMPATIBLE_LAYOUT(FullPathProperties); 286 287static_assert(sizeof(float) == sizeof(int32_t), "float is not the same size as int32_t"); 288static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor is not the same size as int32_t"); 289 290bool FullPath::getProperties(int8_t* outProperties, int length) { 291 int propertyDataSize = sizeof(FullPathProperties); 292 if (length != propertyDataSize) { 293 LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided", 294 propertyDataSize, length); 295 return false; 296 } 297 // TODO: consider replacing the property fields with a FullPathProperties struct. 298 FullPathProperties properties; 299 properties.strokeWidth = mStrokeWidth; 300 properties.strokeColor = mStrokeColor; 301 properties.strokeAlpha = mStrokeAlpha; 302 properties.fillColor = mFillColor; 303 properties.fillAlpha = mFillAlpha; 304 properties.trimPathStart = mTrimPathStart; 305 properties.trimPathEnd = mTrimPathEnd; 306 properties.trimPathOffset = mTrimPathOffset; 307 properties.strokeLineCap = mStrokeLineCap; 308 properties.strokeLineJoin = mStrokeLineJoin; 309 properties.strokeMiterLimit = mStrokeMiterLimit; 310 311 memcpy(outProperties, &properties, length); 312 return true; 313} 314 315void ClipPath::drawPath(SkCanvas* outCanvas, const SkPath& renderPath, 316 float strokeScale, const SkMatrix& matrix){ 317 outCanvas->clipPath(renderPath, SkRegion::kIntersect_Op); 318} 319 320Group::Group(const Group& group) : Node(group) { 321 mRotate = group.mRotate; 322 mPivotX = group.mPivotX; 323 mPivotY = group.mPivotY; 324 mScaleX = group.mScaleX; 325 mScaleY = group.mScaleY; 326 mTranslateX = group.mTranslateX; 327 mTranslateY = group.mTranslateY; 328} 329 330void Group::draw(SkCanvas* outCanvas, const SkMatrix& currentMatrix, float scaleX, 331 float scaleY) { 332 // TODO: Try apply the matrix to the canvas instead of passing it down the tree 333 334 // Calculate current group's matrix by preConcat the parent's and 335 // and the current one on the top of the stack. 336 // Basically the Mfinal = Mviewport * M0 * M1 * M2; 337 // Mi the local matrix at level i of the group tree. 338 SkMatrix stackedMatrix; 339 getLocalMatrix(&stackedMatrix); 340 stackedMatrix.postConcat(currentMatrix); 341 342 // Save the current clip information, which is local to this group. 343 outCanvas->save(); 344 // Draw the group tree in the same order as the XML file. 345 for (Node* child : mChildren) { 346 child->draw(outCanvas, stackedMatrix, scaleX, scaleY); 347 } 348 // Restore the previous clip information. 349 outCanvas->restore(); 350} 351 352void Group::dump() { 353 ALOGD("Group %s has %zu children: ", mName.c_str(), mChildren.size()); 354 for (size_t i = 0; i < mChildren.size(); i++) { 355 mChildren[i]->dump(); 356 } 357} 358 359void Group::updateLocalMatrix(float rotate, float pivotX, float pivotY, 360 float scaleX, float scaleY, float translateX, float translateY) { 361 setRotation(rotate); 362 setPivotX(pivotX); 363 setPivotY(pivotY); 364 setScaleX(scaleX); 365 setScaleY(scaleY); 366 setTranslateX(translateX); 367 setTranslateY(translateY); 368} 369 370void Group::getLocalMatrix(SkMatrix* outMatrix) { 371 outMatrix->reset(); 372 // TODO: use rotate(mRotate, mPivotX, mPivotY) and scale with pivot point, instead of 373 // translating to pivot for rotating and scaling, then translating back. 374 outMatrix->postTranslate(-mPivotX, -mPivotY); 375 outMatrix->postScale(mScaleX, mScaleY); 376 outMatrix->postRotate(mRotate, 0, 0); 377 outMatrix->postTranslate(mTranslateX + mPivotX, mTranslateY + mPivotY); 378} 379 380void Group::addChild(Node* child) { 381 mChildren.push_back(child); 382} 383 384bool Group::getProperties(float* outProperties, int length) { 385 int propertyCount = static_cast<int>(Property::Count); 386 if (length != propertyCount) { 387 LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided", 388 propertyCount, length); 389 return false; 390 } 391 for (int i = 0; i < propertyCount; i++) { 392 Property currentProperty = static_cast<Property>(i); 393 switch (currentProperty) { 394 case Property::Rotate_Property: 395 outProperties[i] = mRotate; 396 break; 397 case Property::PivotX_Property: 398 outProperties[i] = mPivotX; 399 break; 400 case Property::PivotY_Property: 401 outProperties[i] = mPivotY; 402 break; 403 case Property::ScaleX_Property: 404 outProperties[i] = mScaleX; 405 break; 406 case Property::ScaleY_Property: 407 outProperties[i] = mScaleY; 408 break; 409 case Property::TranslateX_Property: 410 outProperties[i] = mTranslateX; 411 break; 412 case Property::TranslateY_Property: 413 outProperties[i] = mTranslateY; 414 break; 415 default: 416 LOG_ALWAYS_FATAL("Invalid input index: %d", i); 417 return false; 418 } 419 } 420 return true; 421} 422 423void Tree::draw(Canvas* outCanvas, SkColorFilter* colorFilter, 424 const SkRect& bounds, bool needsMirroring, bool canReuseCache) { 425 // The imageView can scale the canvas in different ways, in order to 426 // avoid blurry scaling, we have to draw into a bitmap with exact pixel 427 // size first. This bitmap size is determined by the bounds and the 428 // canvas scale. 429 outCanvas->getMatrix(&mCanvasMatrix); 430 mBounds = bounds; 431 float canvasScaleX = 1.0f; 432 float canvasScaleY = 1.0f; 433 if (mCanvasMatrix.getSkewX() == 0 && mCanvasMatrix.getSkewY() == 0) { 434 // Only use the scale value when there's no skew or rotation in the canvas matrix. 435 // TODO: Add a cts test for drawing VD on a canvas with negative scaling factors. 436 canvasScaleX = fabs(mCanvasMatrix.getScaleX()); 437 canvasScaleY = fabs(mCanvasMatrix.getScaleY()); 438 } 439 int scaledWidth = (int) (mBounds.width() * canvasScaleX); 440 int scaledHeight = (int) (mBounds.height() * canvasScaleY); 441 scaledWidth = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledWidth); 442 scaledHeight = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledHeight); 443 444 if (scaledWidth <= 0 || scaledHeight <= 0) { 445 return; 446 } 447 448 int saveCount = outCanvas->save(SaveFlags::MatrixClip); 449 outCanvas->translate(mBounds.fLeft, mBounds.fTop); 450 451 // Handle RTL mirroring. 452 if (needsMirroring) { 453 outCanvas->translate(mBounds.width(), 0); 454 outCanvas->scale(-1.0f, 1.0f); 455 } 456 457 // At this point, canvas has been translated to the right position. 458 // And we use this bound for the destination rect for the drawBitmap, so 459 // we offset to (0, 0); 460 mBounds.offsetTo(0, 0); 461 462 createCachedBitmapIfNeeded(scaledWidth, scaledHeight); 463 if (!mAllowCaching) { 464 updateCachedBitmap(scaledWidth, scaledHeight); 465 } else { 466 if (!canReuseCache || mCacheDirty) { 467 updateCachedBitmap(scaledWidth, scaledHeight); 468 } 469 } 470 drawCachedBitmapWithRootAlpha(outCanvas, colorFilter, mBounds); 471 472 outCanvas->restoreToCount(saveCount); 473} 474 475void Tree::drawCachedBitmapWithRootAlpha(Canvas* outCanvas, SkColorFilter* filter, 476 const SkRect& originalBounds) { 477 SkPaint* paint; 478 if (mRootAlpha == 1.0f && filter == NULL) { 479 paint = NULL; 480 } else { 481 mPaint.setFilterQuality(kLow_SkFilterQuality); 482 mPaint.setAlpha(mRootAlpha * 255); 483 mPaint.setColorFilter(filter); 484 paint = &mPaint; 485 } 486 outCanvas->drawBitmap(mCachedBitmap, 0, 0, mCachedBitmap.width(), mCachedBitmap.height(), 487 originalBounds.fLeft, originalBounds.fTop, originalBounds.fRight, 488 originalBounds.fBottom, paint); 489} 490 491void Tree::updateCachedBitmap(int width, int height) { 492 mCachedBitmap.eraseColor(SK_ColorTRANSPARENT); 493 SkCanvas outCanvas(mCachedBitmap); 494 float scaleX = width / mViewportWidth; 495 float scaleY = height / mViewportHeight; 496 mRootNode->draw(&outCanvas, SkMatrix::I(), scaleX, scaleY); 497 mCacheDirty = false; 498} 499 500void Tree::createCachedBitmapIfNeeded(int width, int height) { 501 if (!canReuseBitmap(width, height)) { 502 SkImageInfo info = SkImageInfo::Make(width, height, 503 kN32_SkColorType, kPremul_SkAlphaType); 504 mCachedBitmap.setInfo(info); 505 // TODO: Count the bitmap cache against app's java heap 506 mCachedBitmap.allocPixels(info); 507 mCacheDirty = true; 508 } 509} 510 511bool Tree::canReuseBitmap(int width, int height) { 512 return width == mCachedBitmap.width() && height == mCachedBitmap.height(); 513} 514 515}; // namespace VectorDrawable 516 517}; // namespace uirenderer 518}; // namespace android 519