VectorDrawable.cpp revision dbee9bb342cdfaa5155b1918f90262c05e2464cb
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        outCanvas->drawPath(renderPath, mPaint);
205        needsFill = true;
206    }
207
208    if (needsFill) {
209        mPaint.setStyle(SkPaint::Style::kFill_Style);
210        mPaint.setAntiAlias(true);
211        outCanvas->drawPath(renderPath, mPaint);
212    }
213
214    // Draw path's stroke, if stroke color or gradient is valid
215    bool needsStroke = false;
216    if (mStrokeGradient != nullptr) {
217        mPaint.setColor(applyAlpha(SK_ColorBLACK, mStrokeAlpha));
218        SkShader* newShader = mStrokeGradient->newWithLocalMatrix(matrix);
219        mPaint.setShader(newShader);
220        needsStroke = true;
221    } else if (mStrokeColor != SK_ColorTRANSPARENT) {
222        mPaint.setColor(applyAlpha(mStrokeColor, mStrokeAlpha));
223        needsStroke = true;
224    }
225    if (needsStroke) {
226        mPaint.setStyle(SkPaint::Style::kStroke_Style);
227        mPaint.setAntiAlias(true);
228        mPaint.setStrokeJoin(mStrokeLineJoin);
229        mPaint.setStrokeCap(mStrokeLineCap);
230        mPaint.setStrokeMiter(mStrokeMiterLimit);
231        mPaint.setStrokeWidth(mStrokeWidth * strokeScale);
232        outCanvas->drawPath(renderPath, mPaint);
233    }
234}
235
236/**
237 * Applies trimming to the specified path.
238 */
239void FullPath::applyTrim() {
240    if (mTrimPathStart == 0.0f && mTrimPathEnd == 1.0f) {
241        // No trimming necessary.
242        return;
243    }
244    SkPathMeasure measure(mSkPath, false);
245    float len = SkScalarToFloat(measure.getLength());
246    float start = len * fmod((mTrimPathStart + mTrimPathOffset), 1.0f);
247    float end = len * fmod((mTrimPathEnd + mTrimPathOffset), 1.0f);
248
249    mTrimmedSkPath.reset();
250    if (start > end) {
251        measure.getSegment(start, len, &mTrimmedSkPath, true);
252        measure.getSegment(0, end, &mTrimmedSkPath, true);
253    } else {
254        measure.getSegment(start, end, &mTrimmedSkPath, true);
255    }
256    mTrimDirty = false;
257}
258
259inline int putData(int8_t* outBytes, int startIndex, float value) {
260    int size = sizeof(float);
261    memcpy(&outBytes[startIndex], &value, size);
262    return size;
263}
264
265inline int putData(int8_t* outBytes, int startIndex, int value) {
266    int size = sizeof(int);
267    memcpy(&outBytes[startIndex], &value, size);
268    return size;
269}
270
271struct FullPathProperties {
272    // TODO: Consider storing full path properties in this struct instead of the fields.
273    float strokeWidth;
274    SkColor strokeColor;
275    float strokeAlpha;
276    SkColor fillColor;
277    float fillAlpha;
278    float trimPathStart;
279    float trimPathEnd;
280    float trimPathOffset;
281    int32_t strokeLineCap;
282    int32_t strokeLineJoin;
283    float strokeMiterLimit;
284};
285
286REQUIRE_COMPATIBLE_LAYOUT(FullPathProperties);
287
288static_assert(sizeof(float) == sizeof(int32_t), "float is not the same size as int32_t");
289static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor is not the same size as int32_t");
290
291bool FullPath::getProperties(int8_t* outProperties, int length) {
292    int propertyDataSize = sizeof(FullPathProperties);
293    if (length != propertyDataSize) {
294        LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided",
295                propertyDataSize, length);
296        return false;
297    }
298    // TODO: consider replacing the property fields with a FullPathProperties struct.
299    FullPathProperties properties;
300    properties.strokeWidth = mStrokeWidth;
301    properties.strokeColor = mStrokeColor;
302    properties.strokeAlpha = mStrokeAlpha;
303    properties.fillColor = mFillColor;
304    properties.fillAlpha = mFillAlpha;
305    properties.trimPathStart = mTrimPathStart;
306    properties.trimPathEnd = mTrimPathEnd;
307    properties.trimPathOffset = mTrimPathOffset;
308    properties.strokeLineCap = mStrokeLineCap;
309    properties.strokeLineJoin = mStrokeLineJoin;
310    properties.strokeMiterLimit = mStrokeMiterLimit;
311
312    memcpy(outProperties, &properties, length);
313    return true;
314}
315
316void ClipPath::drawPath(SkCanvas* outCanvas, const SkPath& renderPath,
317        float strokeScale, const SkMatrix& matrix){
318    outCanvas->clipPath(renderPath, SkRegion::kIntersect_Op);
319}
320
321Group::Group(const Group& group) : Node(group) {
322    mRotate = group.mRotate;
323    mPivotX = group.mPivotX;
324    mPivotY = group.mPivotY;
325    mScaleX = group.mScaleX;
326    mScaleY = group.mScaleY;
327    mTranslateX = group.mTranslateX;
328    mTranslateY = group.mTranslateY;
329}
330
331void Group::draw(SkCanvas* outCanvas, const SkMatrix& currentMatrix, float scaleX,
332        float scaleY) {
333    // TODO: Try apply the matrix to the canvas instead of passing it down the tree
334
335    // Calculate current group's matrix by preConcat the parent's and
336    // and the current one on the top of the stack.
337    // Basically the Mfinal = Mviewport * M0 * M1 * M2;
338    // Mi the local matrix at level i of the group tree.
339    SkMatrix stackedMatrix;
340    getLocalMatrix(&stackedMatrix);
341    stackedMatrix.postConcat(currentMatrix);
342
343    // Save the current clip information, which is local to this group.
344    outCanvas->save();
345    // Draw the group tree in the same order as the XML file.
346    for (Node* child : mChildren) {
347        child->draw(outCanvas, stackedMatrix, scaleX, scaleY);
348    }
349    // Restore the previous clip information.
350    outCanvas->restore();
351}
352
353void Group::dump() {
354    ALOGD("Group %s has %zu children: ", mName.c_str(), mChildren.size());
355    for (size_t i = 0; i < mChildren.size(); i++) {
356        mChildren[i]->dump();
357    }
358}
359
360void Group::updateLocalMatrix(float rotate, float pivotX, float pivotY,
361        float scaleX, float scaleY, float translateX, float translateY) {
362    setRotation(rotate);
363    setPivotX(pivotX);
364    setPivotY(pivotY);
365    setScaleX(scaleX);
366    setScaleY(scaleY);
367    setTranslateX(translateX);
368    setTranslateY(translateY);
369}
370
371void Group::getLocalMatrix(SkMatrix* outMatrix) {
372    outMatrix->reset();
373    // TODO: use rotate(mRotate, mPivotX, mPivotY) and scale with pivot point, instead of
374    // translating to pivot for rotating and scaling, then translating back.
375    outMatrix->postTranslate(-mPivotX, -mPivotY);
376    outMatrix->postScale(mScaleX, mScaleY);
377    outMatrix->postRotate(mRotate, 0, 0);
378    outMatrix->postTranslate(mTranslateX + mPivotX, mTranslateY + mPivotY);
379}
380
381void Group::addChild(Node* child) {
382    mChildren.push_back(child);
383}
384
385bool Group::getProperties(float* outProperties, int length) {
386    int propertyCount = static_cast<int>(Property::Count);
387    if (length != propertyCount) {
388        LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided",
389                propertyCount, length);
390        return false;
391    }
392    for (int i = 0; i < propertyCount; i++) {
393        Property currentProperty = static_cast<Property>(i);
394        switch (currentProperty) {
395        case Property::Rotate_Property:
396            outProperties[i] = mRotate;
397            break;
398        case Property::PivotX_Property:
399            outProperties[i] = mPivotX;
400            break;
401        case Property::PivotY_Property:
402            outProperties[i] = mPivotY;
403            break;
404        case Property::ScaleX_Property:
405            outProperties[i] = mScaleX;
406            break;
407        case Property::ScaleY_Property:
408            outProperties[i] = mScaleY;
409            break;
410        case Property::TranslateX_Property:
411            outProperties[i] = mTranslateX;
412            break;
413        case Property::TranslateY_Property:
414            outProperties[i] = mTranslateY;
415            break;
416        default:
417            LOG_ALWAYS_FATAL("Invalid input index: %d", i);
418            return false;
419        }
420    }
421    return true;
422}
423
424void Tree::draw(Canvas* outCanvas, SkColorFilter* colorFilter,
425        const SkRect& bounds, bool needsMirroring, bool canReuseCache) {
426    // The imageView can scale the canvas in different ways, in order to
427    // avoid blurry scaling, we have to draw into a bitmap with exact pixel
428    // size first. This bitmap size is determined by the bounds and the
429    // canvas scale.
430    outCanvas->getMatrix(&mCanvasMatrix);
431    mBounds = bounds;
432    float canvasScaleX = 1.0f;
433    float canvasScaleY = 1.0f;
434    if (mCanvasMatrix.getSkewX() == 0 && mCanvasMatrix.getSkewY() == 0) {
435        // Only use the scale value when there's no skew or rotation in the canvas matrix.
436        // TODO: Add a cts test for drawing VD on a canvas with negative scaling factors.
437        canvasScaleX = fabs(mCanvasMatrix.getScaleX());
438        canvasScaleY = fabs(mCanvasMatrix.getScaleY());
439    }
440    int scaledWidth = (int) (mBounds.width() * canvasScaleX);
441    int scaledHeight = (int) (mBounds.height() * canvasScaleY);
442    scaledWidth = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledWidth);
443    scaledHeight = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledHeight);
444
445    if (scaledWidth <= 0 || scaledHeight <= 0) {
446        return;
447    }
448
449    int saveCount = outCanvas->save(SaveFlags::MatrixClip);
450    outCanvas->translate(mBounds.fLeft, mBounds.fTop);
451
452    // Handle RTL mirroring.
453    if (needsMirroring) {
454        outCanvas->translate(mBounds.width(), 0);
455        outCanvas->scale(-1.0f, 1.0f);
456    }
457
458    // At this point, canvas has been translated to the right position.
459    // And we use this bound for the destination rect for the drawBitmap, so
460    // we offset to (0, 0);
461    mBounds.offsetTo(0, 0);
462
463    createCachedBitmapIfNeeded(scaledWidth, scaledHeight);
464    if (!mAllowCaching) {
465        updateCachedBitmap(scaledWidth, scaledHeight);
466    } else {
467        if (!canReuseCache || mCacheDirty) {
468            updateCachedBitmap(scaledWidth, scaledHeight);
469        }
470    }
471    drawCachedBitmapWithRootAlpha(outCanvas, colorFilter, mBounds);
472
473    outCanvas->restoreToCount(saveCount);
474}
475
476void Tree::drawCachedBitmapWithRootAlpha(Canvas* outCanvas, SkColorFilter* filter,
477        const SkRect& originalBounds) {
478    SkPaint* paint;
479    if (mRootAlpha == 1.0f && filter == NULL) {
480        paint = NULL;
481    } else {
482        mPaint.setFilterQuality(kLow_SkFilterQuality);
483        mPaint.setAlpha(mRootAlpha * 255);
484        mPaint.setColorFilter(filter);
485        paint = &mPaint;
486    }
487    outCanvas->drawBitmap(mCachedBitmap, 0, 0, mCachedBitmap.width(), mCachedBitmap.height(),
488            originalBounds.fLeft, originalBounds.fTop, originalBounds.fRight,
489            originalBounds.fBottom, paint);
490}
491
492void Tree::updateCachedBitmap(int width, int height) {
493    mCachedBitmap.eraseColor(SK_ColorTRANSPARENT);
494    SkCanvas outCanvas(mCachedBitmap);
495    float scaleX = width / mViewportWidth;
496    float scaleY = height / mViewportHeight;
497    mRootNode->draw(&outCanvas, SkMatrix::I(), scaleX, scaleY);
498    mCacheDirty = false;
499}
500
501void Tree::createCachedBitmapIfNeeded(int width, int height) {
502    if (!canReuseBitmap(width, height)) {
503        SkImageInfo info = SkImageInfo::Make(width, height,
504                kN32_SkColorType, kPremul_SkAlphaType);
505        mCachedBitmap.setInfo(info);
506        // TODO: Count the bitmap cache against app's java heap
507        mCachedBitmap.allocPixels(info);
508        mCacheDirty = true;
509    }
510}
511
512bool Tree::canReuseBitmap(int width, int height) {
513    return width == mCachedBitmap.width() && height == mCachedBitmap.height();
514}
515
516}; // namespace VectorDrawable
517
518}; // namespace uirenderer
519}; // namespace android
520