VectorDrawable.cpp revision fc9999505a36c66892d7ccce85187936105f4f36
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 "SkColorFilter.h"
21#include "SkImageInfo.h"
22#include "SkShader.h"
23#include <utils/Log.h>
24#include "utils/Macros.h"
25#include "utils/VectorDrawableUtils.h"
26
27#include <math.h>
28#include <string.h>
29
30namespace android {
31namespace uirenderer {
32namespace VectorDrawable {
33
34const int Tree::MAX_CACHED_BITMAP_SIZE = 2048;
35
36void Path::draw(SkCanvas* outCanvas, const SkMatrix& groupStackedMatrix, float scaleX, float scaleY,
37        bool useStagingData) {
38    float matrixScale = getMatrixScale(groupStackedMatrix);
39    if (matrixScale == 0) {
40        // When either x or y is scaled to 0, we don't need to draw anything.
41        return;
42    }
43
44    SkMatrix pathMatrix(groupStackedMatrix);
45    pathMatrix.postScale(scaleX, scaleY);
46
47    //TODO: try apply the path matrix to the canvas instead of creating a new path.
48    SkPath renderPath;
49    renderPath.reset();
50
51    if (useStagingData) {
52        SkPath tmpPath;
53        getStagingPath(&tmpPath);
54        renderPath.addPath(tmpPath, pathMatrix);
55    } else {
56        renderPath.addPath(getUpdatedPath(), pathMatrix);
57    }
58
59    float minScale = fmin(scaleX, scaleY);
60    float strokeScale = minScale * matrixScale;
61    drawPath(outCanvas, renderPath, strokeScale, pathMatrix, useStagingData);
62}
63
64void Path::dump() {
65    ALOGD("Path: %s has %zu points", mName.c_str(), mProperties.getData().points.size());
66}
67
68float Path::getMatrixScale(const SkMatrix& groupStackedMatrix) {
69    // Given unit vectors A = (0, 1) and B = (1, 0).
70    // After matrix mapping, we got A' and B'. Let theta = the angel b/t A' and B'.
71    // Therefore, the final scale we want is min(|A'| * sin(theta), |B'| * sin(theta)),
72    // which is (|A'| * |B'| * sin(theta)) / max (|A'|, |B'|);
73    // If  max (|A'|, |B'|) = 0, that means either x or y has a scale of 0.
74    //
75    // For non-skew case, which is most of the cases, matrix scale is computing exactly the
76    // scale on x and y axis, and take the minimal of these two.
77    // For skew case, an unit square will mapped to a parallelogram. And this function will
78    // return the minimal height of the 2 bases.
79    SkVector skVectors[2];
80    skVectors[0].set(0, 1);
81    skVectors[1].set(1, 0);
82    groupStackedMatrix.mapVectors(skVectors, 2);
83    float scaleX = hypotf(skVectors[0].fX, skVectors[0].fY);
84    float scaleY = hypotf(skVectors[1].fX, skVectors[1].fY);
85    float crossProduct = skVectors[0].cross(skVectors[1]);
86    float maxScale = fmax(scaleX, scaleY);
87
88    float matrixScale = 0;
89    if (maxScale > 0) {
90        matrixScale = fabs(crossProduct) / maxScale;
91    }
92    return matrixScale;
93}
94
95// Called from UI thread during the initial setup/theme change.
96Path::Path(const char* pathStr, size_t strLength) {
97    PathParser::ParseResult result;
98    Data data;
99    PathParser::getPathDataFromAsciiString(&data, &result, pathStr, strLength);
100    mStagingProperties.setData(data);
101}
102
103Path::Path(const Path& path) : Node(path) {
104    mStagingProperties.syncProperties(path.mStagingProperties);
105}
106
107const SkPath& Path::getUpdatedPath() {
108    if (mSkPathDirty) {
109        mSkPath.reset();
110        VectorDrawableUtils::verbsToPath(&mSkPath, mProperties.getData());
111        mSkPathDirty = false;
112    }
113    return mSkPath;
114}
115
116void Path::getStagingPath(SkPath* outPath) {
117    outPath->reset();
118    VectorDrawableUtils::verbsToPath(outPath, mStagingProperties.getData());
119}
120
121void Path::syncProperties() {
122    if (mStagingPropertiesDirty) {
123        mProperties.syncProperties(mStagingProperties);
124    } else {
125        mStagingProperties.syncProperties(mProperties);
126    }
127    mStagingPropertiesDirty = false;
128}
129
130FullPath::FullPath(const FullPath& path) : Path(path) {
131    mStagingProperties.syncProperties(path.mStagingProperties);
132}
133
134static void applyTrim(SkPath* outPath, const SkPath& inPath, float trimPathStart, float trimPathEnd,
135        float trimPathOffset) {
136    if (trimPathStart == 0.0f && trimPathEnd == 1.0f) {
137        *outPath = inPath;
138        return;
139    }
140    outPath->reset();
141    if (trimPathStart == trimPathEnd) {
142        // Trimmed path should be empty.
143        return;
144    }
145    SkPathMeasure measure(inPath, false);
146    float len = SkScalarToFloat(measure.getLength());
147    float start = len * fmod((trimPathStart + trimPathOffset), 1.0f);
148    float end = len * fmod((trimPathEnd + trimPathOffset), 1.0f);
149
150    if (start > end) {
151        measure.getSegment(start, len, outPath, true);
152        if (end > 0) {
153            measure.getSegment(0, end, outPath, true);
154        }
155    } else {
156        measure.getSegment(start, end, outPath, true);
157    }
158}
159
160const SkPath& FullPath::getUpdatedPath() {
161    if (!mSkPathDirty && !mProperties.mTrimDirty) {
162        return mTrimmedSkPath;
163    }
164    Path::getUpdatedPath();
165    if (mProperties.getTrimPathStart() != 0.0f || mProperties.getTrimPathEnd() != 1.0f) {
166        mProperties.mTrimDirty = false;
167        applyTrim(&mTrimmedSkPath, mSkPath, mProperties.getTrimPathStart(),
168                mProperties.getTrimPathEnd(), mProperties.getTrimPathOffset());
169        return mTrimmedSkPath;
170    } else {
171        return mSkPath;
172    }
173}
174
175void FullPath::getStagingPath(SkPath* outPath) {
176    Path::getStagingPath(outPath);
177    SkPath inPath = *outPath;
178    applyTrim(outPath, inPath, mStagingProperties.getTrimPathStart(),
179            mStagingProperties.getTrimPathEnd(), mStagingProperties.getTrimPathOffset());
180}
181
182void FullPath::dump() {
183    Path::dump();
184    ALOGD("stroke width, color, alpha: %f, %d, %f, fill color, alpha: %d, %f",
185            mProperties.getStrokeWidth(), mProperties.getStrokeColor(), mProperties.getStrokeAlpha(),
186            mProperties.getFillColor(), mProperties.getFillAlpha());
187}
188
189
190inline SkColor applyAlpha(SkColor color, float alpha) {
191    int alphaBytes = SkColorGetA(color);
192    return SkColorSetA(color, alphaBytes * alpha);
193}
194
195void FullPath::drawPath(SkCanvas* outCanvas, SkPath& renderPath, float strokeScale,
196                        const SkMatrix& matrix, bool useStagingData){
197    const FullPathProperties& properties = useStagingData ? mStagingProperties : mProperties;
198
199    // Draw path's fill, if fill color or gradient is valid
200    bool needsFill = false;
201    SkPaint paint;
202    if (properties.getFillGradient() != nullptr) {
203        paint.setColor(applyAlpha(SK_ColorBLACK, properties.getFillAlpha()));
204        paint.setShader(properties.getFillGradient()->makeWithLocalMatrix(matrix));
205        needsFill = true;
206    } else if (properties.getFillColor() != SK_ColorTRANSPARENT) {
207        paint.setColor(applyAlpha(properties.getFillColor(), properties.getFillAlpha()));
208        needsFill = true;
209    }
210
211    if (needsFill) {
212        paint.setStyle(SkPaint::Style::kFill_Style);
213        paint.setAntiAlias(true);
214        SkPath::FillType ft = static_cast<SkPath::FillType>(properties.getFillType());
215        renderPath.setFillType(ft);
216        outCanvas->drawPath(renderPath, paint);
217    }
218
219    // Draw path's stroke, if stroke color or Gradient is valid
220    bool needsStroke = false;
221    if (properties.getStrokeGradient() != nullptr) {
222        paint.setColor(applyAlpha(SK_ColorBLACK, properties.getStrokeAlpha()));
223        paint.setShader(properties.getStrokeGradient()->makeWithLocalMatrix(matrix));
224        needsStroke = true;
225    } else if (properties.getStrokeColor() != SK_ColorTRANSPARENT) {
226        paint.setColor(applyAlpha(properties.getStrokeColor(), properties.getStrokeAlpha()));
227        needsStroke = true;
228    }
229    if (needsStroke) {
230        paint.setStyle(SkPaint::Style::kStroke_Style);
231        paint.setAntiAlias(true);
232        paint.setStrokeJoin(SkPaint::Join(properties.getStrokeLineJoin()));
233        paint.setStrokeCap(SkPaint::Cap(properties.getStrokeLineCap()));
234        paint.setStrokeMiter(properties.getStrokeMiterLimit());
235        paint.setStrokeWidth(properties.getStrokeWidth() * strokeScale);
236        outCanvas->drawPath(renderPath, paint);
237    }
238}
239
240void FullPath::syncProperties() {
241    Path::syncProperties();
242
243    if (mStagingPropertiesDirty) {
244        mProperties.syncProperties(mStagingProperties);
245    } else {
246        // Update staging property with property values from animation.
247        mStagingProperties.syncProperties(mProperties);
248    }
249    mStagingPropertiesDirty = false;
250}
251
252REQUIRE_COMPATIBLE_LAYOUT(FullPath::FullPathProperties::PrimitiveFields);
253
254static_assert(sizeof(float) == sizeof(int32_t), "float is not the same size as int32_t");
255static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor is not the same size as int32_t");
256
257bool FullPath::FullPathProperties::copyProperties(int8_t* outProperties, int length) const {
258    int propertyDataSize = sizeof(FullPathProperties::PrimitiveFields);
259    if (length != propertyDataSize) {
260        LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided",
261                propertyDataSize, length);
262        return false;
263    }
264
265    PrimitiveFields* out = reinterpret_cast<PrimitiveFields*>(outProperties);
266    *out = mPrimitiveFields;
267    return true;
268}
269
270void FullPath::FullPathProperties::setColorPropertyValue(int propertyId, int32_t value) {
271    Property currentProperty = static_cast<Property>(propertyId);
272    if (currentProperty == Property::strokeColor) {
273        setStrokeColor(value);
274    } else if (currentProperty == Property::fillColor) {
275        setFillColor(value);
276    } else {
277        LOG_ALWAYS_FATAL("Error setting color property on FullPath: No valid property"
278                " with id: %d", propertyId);
279    }
280}
281
282void FullPath::FullPathProperties::setPropertyValue(int propertyId, float value) {
283    Property property = static_cast<Property>(propertyId);
284    switch (property) {
285    case Property::strokeWidth:
286        setStrokeWidth(value);
287        break;
288    case Property::strokeAlpha:
289        setStrokeAlpha(value);
290        break;
291    case Property::fillAlpha:
292        setFillAlpha(value);
293        break;
294    case Property::trimPathStart:
295        setTrimPathStart(value);
296        break;
297    case Property::trimPathEnd:
298        setTrimPathEnd(value);
299        break;
300    case Property::trimPathOffset:
301        setTrimPathOffset(value);
302        break;
303    default:
304        LOG_ALWAYS_FATAL("Invalid property id: %d for animation", propertyId);
305        break;
306    }
307}
308
309void ClipPath::drawPath(SkCanvas* outCanvas, SkPath& renderPath,
310        float strokeScale, const SkMatrix& matrix, bool useStagingData){
311    outCanvas->clipPath(renderPath, SkRegion::kIntersect_Op);
312}
313
314Group::Group(const Group& group) : Node(group) {
315    mStagingProperties.syncProperties(group.mStagingProperties);
316}
317
318void Group::draw(SkCanvas* outCanvas, const SkMatrix& currentMatrix, float scaleX,
319        float scaleY, bool useStagingData) {
320    // TODO: Try apply the matrix to the canvas instead of passing it down the tree
321
322    // Calculate current group's matrix by preConcat the parent's and
323    // and the current one on the top of the stack.
324    // Basically the Mfinal = Mviewport * M0 * M1 * M2;
325    // Mi the local matrix at level i of the group tree.
326    SkMatrix stackedMatrix;
327    const GroupProperties& prop = useStagingData ? mStagingProperties : mProperties;
328    getLocalMatrix(&stackedMatrix, prop);
329    stackedMatrix.postConcat(currentMatrix);
330
331    // Save the current clip information, which is local to this group.
332    outCanvas->save();
333    // Draw the group tree in the same order as the XML file.
334    for (auto& child : mChildren) {
335        child->draw(outCanvas, stackedMatrix, scaleX, scaleY, useStagingData);
336    }
337    // Restore the previous clip information.
338    outCanvas->restore();
339}
340
341void Group::dump() {
342    ALOGD("Group %s has %zu children: ", mName.c_str(), mChildren.size());
343    ALOGD("Group translateX, Y : %f, %f, scaleX, Y: %f, %f", mProperties.getTranslateX(),
344            mProperties.getTranslateY(), mProperties.getScaleX(), mProperties.getScaleY());
345    for (size_t i = 0; i < mChildren.size(); i++) {
346        mChildren[i]->dump();
347    }
348}
349
350void Group::syncProperties() {
351    // Copy over the dirty staging properties
352    if (mStagingPropertiesDirty) {
353        mProperties.syncProperties(mStagingProperties);
354    } else {
355        mStagingProperties.syncProperties(mProperties);
356    }
357    mStagingPropertiesDirty = false;
358    for (auto& child : mChildren) {
359        child->syncProperties();
360    }
361}
362
363void Group::getLocalMatrix(SkMatrix* outMatrix, const GroupProperties& properties) {
364    outMatrix->reset();
365    // TODO: use rotate(mRotate, mPivotX, mPivotY) and scale with pivot point, instead of
366    // translating to pivot for rotating and scaling, then translating back.
367    outMatrix->postTranslate(-properties.getPivotX(), -properties.getPivotY());
368    outMatrix->postScale(properties.getScaleX(), properties.getScaleY());
369    outMatrix->postRotate(properties.getRotation(), 0, 0);
370    outMatrix->postTranslate(properties.getTranslateX() + properties.getPivotX(),
371            properties.getTranslateY() + properties.getPivotY());
372}
373
374void Group::addChild(Node* child) {
375    mChildren.emplace_back(child);
376    if (mPropertyChangedListener != nullptr) {
377        child->setPropertyChangedListener(mPropertyChangedListener);
378    }
379}
380
381bool Group::GroupProperties::copyProperties(float* outProperties, int length) const {
382    int propertyCount = static_cast<int>(Property::count);
383    if (length != propertyCount) {
384        LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided",
385                propertyCount, length);
386        return false;
387    }
388
389    PrimitiveFields* out = reinterpret_cast<PrimitiveFields*>(outProperties);
390    *out = mPrimitiveFields;
391    return true;
392}
393
394// TODO: Consider animating the properties as float pointers
395// Called on render thread
396float Group::GroupProperties::getPropertyValue(int propertyId) const {
397    Property currentProperty = static_cast<Property>(propertyId);
398    switch (currentProperty) {
399    case Property::rotate:
400        return getRotation();
401    case Property::pivotX:
402        return getPivotX();
403    case Property::pivotY:
404        return getPivotY();
405    case Property::scaleX:
406        return getScaleX();
407    case Property::scaleY:
408        return getScaleY();
409    case Property::translateX:
410        return getTranslateX();
411    case Property::translateY:
412        return getTranslateY();
413    default:
414        LOG_ALWAYS_FATAL("Invalid property index: %d", propertyId);
415        return 0;
416    }
417}
418
419// Called on render thread
420void Group::GroupProperties::setPropertyValue(int propertyId, float value) {
421    Property currentProperty = static_cast<Property>(propertyId);
422    switch (currentProperty) {
423    case Property::rotate:
424        setRotation(value);
425        break;
426    case Property::pivotX:
427        setPivotX(value);
428        break;
429    case Property::pivotY:
430        setPivotY(value);
431        break;
432    case Property::scaleX:
433        setScaleX(value);
434        break;
435    case Property::scaleY:
436        setScaleY(value);
437        break;
438    case Property::translateX:
439        setTranslateX(value);
440        break;
441    case Property::translateY:
442        setTranslateY(value);
443        break;
444    default:
445        LOG_ALWAYS_FATAL("Invalid property index: %d", propertyId);
446    }
447}
448
449bool Group::isValidProperty(int propertyId) {
450    return GroupProperties::isValidProperty(propertyId);
451}
452
453bool Group::GroupProperties::isValidProperty(int propertyId) {
454    return propertyId >= 0 && propertyId < static_cast<int>(Property::count);
455}
456
457int Tree::draw(Canvas* outCanvas, SkColorFilter* colorFilter,
458        const SkRect& bounds, bool needsMirroring, bool canReuseCache) {
459    // The imageView can scale the canvas in different ways, in order to
460    // avoid blurry scaling, we have to draw into a bitmap with exact pixel
461    // size first. This bitmap size is determined by the bounds and the
462    // canvas scale.
463    SkMatrix canvasMatrix;
464    outCanvas->getMatrix(&canvasMatrix);
465    float canvasScaleX = 1.0f;
466    float canvasScaleY = 1.0f;
467    if (canvasMatrix.getSkewX() == 0 && canvasMatrix.getSkewY() == 0) {
468        // Only use the scale value when there's no skew or rotation in the canvas matrix.
469        // TODO: Add a cts test for drawing VD on a canvas with negative scaling factors.
470        canvasScaleX = fabs(canvasMatrix.getScaleX());
471        canvasScaleY = fabs(canvasMatrix.getScaleY());
472    }
473    int scaledWidth = (int) (bounds.width() * canvasScaleX);
474    int scaledHeight = (int) (bounds.height() * canvasScaleY);
475    scaledWidth = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledWidth);
476    scaledHeight = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledHeight);
477
478    if (scaledWidth <= 0 || scaledHeight <= 0) {
479        return 0;
480    }
481
482    mStagingProperties.setScaledSize(scaledWidth, scaledHeight);
483    int saveCount = outCanvas->save(SaveFlags::MatrixClip);
484    outCanvas->translate(bounds.fLeft, bounds.fTop);
485
486    // Handle RTL mirroring.
487    if (needsMirroring) {
488        outCanvas->translate(bounds.width(), 0);
489        outCanvas->scale(-1.0f, 1.0f);
490    }
491    mStagingProperties.setColorFilter(colorFilter);
492
493    // At this point, canvas has been translated to the right position.
494    // And we use this bound for the destination rect for the drawBitmap, so
495    // we offset to (0, 0);
496    SkRect tmpBounds = bounds;
497    tmpBounds.offsetTo(0, 0);
498    mStagingProperties.setBounds(tmpBounds);
499    outCanvas->drawVectorDrawable(this);
500    outCanvas->restoreToCount(saveCount);
501    return scaledWidth * scaledHeight;
502}
503
504void Tree::drawStaging(Canvas* outCanvas) {
505    bool redrawNeeded = allocateBitmapIfNeeded(mStagingCache,
506            mStagingProperties.getScaledWidth(), mStagingProperties.getScaledHeight());
507    // draw bitmap cache
508    if (redrawNeeded || mStagingCache.dirty) {
509        updateBitmapCache(*mStagingCache.bitmap, true);
510        mStagingCache.dirty = false;
511    }
512
513    SkPaint tmpPaint;
514    SkPaint* paint = updatePaint(&tmpPaint, &mStagingProperties);
515    outCanvas->drawBitmap(*mStagingCache.bitmap, 0, 0,
516            mStagingCache.bitmap->width(), mStagingCache.bitmap->height(),
517            mStagingProperties.getBounds().left(), mStagingProperties.getBounds().top(),
518            mStagingProperties.getBounds().right(), mStagingProperties.getBounds().bottom(), paint);
519}
520
521SkPaint* Tree::getPaint() {
522    return updatePaint(&mPaint, &mProperties);
523}
524
525// Update the given paint with alpha and color filter. Return nullptr if no color filter is
526// specified and root alpha is 1. Otherwise, return updated paint.
527SkPaint* Tree::updatePaint(SkPaint* outPaint, TreeProperties* prop) {
528    if (prop->getRootAlpha() == 1.0f && prop->getColorFilter() == nullptr) {
529        return nullptr;
530    } else {
531        outPaint->setColorFilter(sk_ref_sp(prop->getColorFilter()));
532        outPaint->setFilterQuality(kLow_SkFilterQuality);
533        outPaint->setAlpha(prop->getRootAlpha() * 255);
534        return outPaint;
535    }
536}
537
538Bitmap& Tree::getBitmapUpdateIfDirty() {
539    bool redrawNeeded = allocateBitmapIfNeeded(mCache, mProperties.getScaledWidth(),
540            mProperties.getScaledHeight());
541    if (redrawNeeded || mCache.dirty) {
542        updateBitmapCache(*mCache.bitmap, false);
543        mCache.dirty = false;
544    }
545    return *mCache.bitmap;
546}
547
548void Tree::updateBitmapCache(Bitmap& bitmap, bool useStagingData) {
549    SkBitmap outCache;
550    bitmap.getSkBitmap(&outCache);
551    outCache.eraseColor(SK_ColorTRANSPARENT);
552    SkCanvas outCanvas(outCache);
553    float viewportWidth = useStagingData ?
554            mStagingProperties.getViewportWidth() : mProperties.getViewportWidth();
555    float viewportHeight = useStagingData ?
556            mStagingProperties.getViewportHeight() : mProperties.getViewportHeight();
557    float scaleX = outCache.width() / viewportWidth;
558    float scaleY = outCache.height() / viewportHeight;
559    mRootNode->draw(&outCanvas, SkMatrix::I(), scaleX, scaleY, useStagingData);
560}
561
562bool Tree::allocateBitmapIfNeeded(Cache& cache, int width, int height) {
563    if (!canReuseBitmap(cache.bitmap.get(), width, height)) {
564#ifndef ANDROID_ENABLE_LINEAR_BLENDING
565        sk_sp<SkColorSpace> colorSpace = nullptr;
566#else
567        sk_sp<SkColorSpace> colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
568#endif
569        SkImageInfo info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType, colorSpace);
570        cache.bitmap = Bitmap::allocateHeapBitmap(info);
571        return true;
572    }
573    return false;
574}
575
576bool Tree::canReuseBitmap(Bitmap* bitmap, int width, int height) {
577    return bitmap && width == bitmap->width() && height == bitmap->height();
578}
579
580void Tree::onPropertyChanged(TreeProperties* prop) {
581    if (prop == &mStagingProperties) {
582        mStagingCache.dirty = true;
583    } else {
584        mCache.dirty = true;
585    }
586}
587
588}; // namespace VectorDrawable
589
590}; // namespace uirenderer
591}; // namespace android
592