• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <math.h>
20 #include <string.h>
21 #include <utils/Log.h>
22 
23 #include "PathParser.h"
24 #include "SkImage.h"
25 #include "SkImageInfo.h"
26 #include "SkSamplingOptions.h"
27 #include "SkScalar.h"
28 #include "hwui/Paint.h"
29 
30 #ifdef __ANDROID__
31 #include "renderthread/RenderThread.h"
32 #endif
33 
34 #include <gui/TraceUtils.h>
35 #include "utils/Macros.h"
36 #include "utils/VectorDrawableUtils.h"
37 
38 namespace android {
39 namespace uirenderer {
40 namespace VectorDrawable {
41 
42 const int Tree::MAX_CACHED_BITMAP_SIZE = 2048;
43 
dump()44 void Path::dump() {
45     ALOGD("Path: %s has %zu points", mName.c_str(), mProperties.getData().points.size());
46 }
47 
48 // Called from UI thread during the initial setup/theme change.
Path(const char * pathStr,size_t strLength)49 Path::Path(const char* pathStr, size_t strLength) {
50     PathParser::ParseResult result;
51     Data data;
52     PathParser::getPathDataFromAsciiString(&data, &result, pathStr, strLength);
53     mStagingProperties.setData(data);
54 }
55 
Path(const Path & path)56 Path::Path(const Path& path) : Node(path) {
57     mStagingProperties.syncProperties(path.mStagingProperties);
58 }
59 
getUpdatedPath(bool useStagingData,SkPath * tempStagingPath)60 const SkPath& Path::getUpdatedPath(bool useStagingData, SkPath* tempStagingPath) {
61     if (useStagingData) {
62         tempStagingPath->reset();
63         VectorDrawableUtils::verbsToPath(tempStagingPath, mStagingProperties.getData());
64         return *tempStagingPath;
65     } else {
66         if (mSkPathDirty) {
67             mSkPath.reset();
68             VectorDrawableUtils::verbsToPath(&mSkPath, mProperties.getData());
69             mSkPathDirty = false;
70         }
71         return mSkPath;
72     }
73 }
74 
syncProperties()75 void Path::syncProperties() {
76     if (mStagingPropertiesDirty) {
77         mProperties.syncProperties(mStagingProperties);
78     } else {
79         mStagingProperties.syncProperties(mProperties);
80     }
81     mStagingPropertiesDirty = false;
82 }
83 
FullPath(const FullPath & path)84 FullPath::FullPath(const FullPath& path) : Path(path) {
85     mStagingProperties.syncProperties(path.mStagingProperties);
86 }
87 
applyTrim(SkPath * outPath,const SkPath & inPath,float trimPathStart,float trimPathEnd,float trimPathOffset)88 static void applyTrim(SkPath* outPath, const SkPath& inPath, float trimPathStart, float trimPathEnd,
89                       float trimPathOffset) {
90     if (trimPathStart == 0.0f && trimPathEnd == 1.0f) {
91         *outPath = inPath;
92         return;
93     }
94     outPath->reset();
95     if (trimPathStart == trimPathEnd) {
96         // Trimmed path should be empty.
97         return;
98     }
99     SkPathMeasure measure(inPath, false);
100     float len = SkScalarToFloat(measure.getLength());
101     float start = len * fmod((trimPathStart + trimPathOffset), 1.0f);
102     float end = len * fmod((trimPathEnd + trimPathOffset), 1.0f);
103 
104     if (start > end) {
105         measure.getSegment(start, len, outPath, true);
106         if (end > 0) {
107             measure.getSegment(0, end, outPath, true);
108         }
109     } else {
110         measure.getSegment(start, end, outPath, true);
111     }
112 }
113 
getUpdatedPath(bool useStagingData,SkPath * tempStagingPath)114 const SkPath& FullPath::getUpdatedPath(bool useStagingData, SkPath* tempStagingPath) {
115     if (!useStagingData && !mSkPathDirty && !mProperties.mTrimDirty) {
116         return mTrimmedSkPath;
117     }
118     Path::getUpdatedPath(useStagingData, tempStagingPath);
119     SkPath* outPath;
120     if (useStagingData) {
121         SkPath inPath = *tempStagingPath;
122         applyTrim(tempStagingPath, inPath, mStagingProperties.getTrimPathStart(),
123                   mStagingProperties.getTrimPathEnd(), mStagingProperties.getTrimPathOffset());
124         outPath = tempStagingPath;
125     } else {
126         if (mProperties.getTrimPathStart() != 0.0f || mProperties.getTrimPathEnd() != 1.0f) {
127             mProperties.mTrimDirty = false;
128             applyTrim(&mTrimmedSkPath, mSkPath, mProperties.getTrimPathStart(),
129                       mProperties.getTrimPathEnd(), mProperties.getTrimPathOffset());
130             outPath = &mTrimmedSkPath;
131         } else {
132             outPath = &mSkPath;
133         }
134     }
135     const FullPathProperties& properties = useStagingData ? mStagingProperties : mProperties;
136     bool setFillPath = properties.getFillGradient() != nullptr ||
137                        properties.getFillColor() != SK_ColorTRANSPARENT;
138     if (setFillPath) {
139         outPath->setFillType(static_cast<SkPathFillType>(properties.getFillType()));
140     }
141     return *outPath;
142 }
143 
dump()144 void FullPath::dump() {
145     Path::dump();
146     ALOGD("stroke width, color, alpha: %f, %d, %f, fill color, alpha: %d, %f",
147           mProperties.getStrokeWidth(), mProperties.getStrokeColor(), mProperties.getStrokeAlpha(),
148           mProperties.getFillColor(), mProperties.getFillAlpha());
149 }
150 
applyAlpha(SkColor color,float alpha)151 inline SkColor applyAlpha(SkColor color, float alpha) {
152     int alphaBytes = SkColorGetA(color);
153     return SkColorSetA(color, alphaBytes * alpha);
154 }
155 
draw(SkCanvas * outCanvas,bool useStagingData)156 void FullPath::draw(SkCanvas* outCanvas, bool useStagingData) {
157     const FullPathProperties& properties = useStagingData ? mStagingProperties : mProperties;
158     SkPath tempStagingPath;
159     const SkPath& renderPath = getUpdatedPath(useStagingData, &tempStagingPath);
160 
161     // Draw path's fill, if fill color or gradient is valid
162     bool needsFill = false;
163     SkPaint paint;
164     if (properties.getFillGradient() != nullptr) {
165         paint.setColor(applyAlpha(SK_ColorBLACK, properties.getFillAlpha()));
166         paint.setShader(sk_sp<SkShader>(SkSafeRef(properties.getFillGradient())));
167         needsFill = true;
168     } else if (properties.getFillColor() != SK_ColorTRANSPARENT) {
169         paint.setColor(applyAlpha(properties.getFillColor(), properties.getFillAlpha()));
170         needsFill = true;
171     }
172 
173     if (needsFill) {
174         paint.setStyle(SkPaint::Style::kFill_Style);
175         paint.setAntiAlias(mAntiAlias);
176         outCanvas->drawPath(renderPath, paint);
177     }
178 
179     // Draw path's stroke, if stroke color or Gradient is valid
180     bool needsStroke = false;
181     if (properties.getStrokeGradient() != nullptr) {
182         paint.setColor(applyAlpha(SK_ColorBLACK, properties.getStrokeAlpha()));
183         paint.setShader(sk_sp<SkShader>(SkSafeRef(properties.getStrokeGradient())));
184         needsStroke = true;
185     } else if (properties.getStrokeColor() != SK_ColorTRANSPARENT) {
186         paint.setColor(applyAlpha(properties.getStrokeColor(), properties.getStrokeAlpha()));
187         needsStroke = true;
188     }
189     if (needsStroke) {
190         paint.setStyle(SkPaint::Style::kStroke_Style);
191         paint.setAntiAlias(mAntiAlias);
192         paint.setStrokeJoin(SkPaint::Join(properties.getStrokeLineJoin()));
193         paint.setStrokeCap(SkPaint::Cap(properties.getStrokeLineCap()));
194         paint.setStrokeMiter(properties.getStrokeMiterLimit());
195         paint.setStrokeWidth(properties.getStrokeWidth());
196         outCanvas->drawPath(renderPath, paint);
197     }
198 }
199 
syncProperties()200 void FullPath::syncProperties() {
201     Path::syncProperties();
202 
203     if (mStagingPropertiesDirty) {
204         mProperties.syncProperties(mStagingProperties);
205     } else {
206         // Update staging property with property values from animation.
207         mStagingProperties.syncProperties(mProperties);
208     }
209     mStagingPropertiesDirty = false;
210 }
211 
212 REQUIRE_COMPATIBLE_LAYOUT(FullPath::FullPathProperties::PrimitiveFields);
213 
214 static_assert(sizeof(float) == sizeof(int32_t), "float is not the same size as int32_t");
215 static_assert(sizeof(SkColor) == sizeof(int32_t), "SkColor is not the same size as int32_t");
216 
copyProperties(int8_t * outProperties,int length) const217 bool FullPath::FullPathProperties::copyProperties(int8_t* outProperties, int length) const {
218     int propertyDataSize = sizeof(FullPathProperties::PrimitiveFields);
219     if (length != propertyDataSize) {
220         LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided",
221                          propertyDataSize, length);
222         return false;
223     }
224 
225     PrimitiveFields* out = reinterpret_cast<PrimitiveFields*>(outProperties);
226     *out = mPrimitiveFields;
227     return true;
228 }
229 
setColorPropertyValue(int propertyId,int32_t value)230 void FullPath::FullPathProperties::setColorPropertyValue(int propertyId, int32_t value) {
231     Property currentProperty = static_cast<Property>(propertyId);
232     if (currentProperty == Property::strokeColor) {
233         setStrokeColor(value);
234     } else if (currentProperty == Property::fillColor) {
235         setFillColor(value);
236     } else {
237         LOG_ALWAYS_FATAL(
238                 "Error setting color property on FullPath: No valid property"
239                 " with id: %d",
240                 propertyId);
241     }
242 }
243 
setPropertyValue(int propertyId,float value)244 void FullPath::FullPathProperties::setPropertyValue(int propertyId, float value) {
245     Property property = static_cast<Property>(propertyId);
246     switch (property) {
247         case Property::strokeWidth:
248             setStrokeWidth(value);
249             break;
250         case Property::strokeAlpha:
251             setStrokeAlpha(value);
252             break;
253         case Property::fillAlpha:
254             setFillAlpha(value);
255             break;
256         case Property::trimPathStart:
257             setTrimPathStart(value);
258             break;
259         case Property::trimPathEnd:
260             setTrimPathEnd(value);
261             break;
262         case Property::trimPathOffset:
263             setTrimPathOffset(value);
264             break;
265         default:
266             LOG_ALWAYS_FATAL("Invalid property id: %d for animation", propertyId);
267             break;
268     }
269 }
270 
draw(SkCanvas * outCanvas,bool useStagingData)271 void ClipPath::draw(SkCanvas* outCanvas, bool useStagingData) {
272     SkPath tempStagingPath;
273     outCanvas->clipPath(getUpdatedPath(useStagingData, &tempStagingPath), true);
274 }
275 
Group(const Group & group)276 Group::Group(const Group& group) : Node(group) {
277     mStagingProperties.syncProperties(group.mStagingProperties);
278 }
279 
draw(SkCanvas * outCanvas,bool useStagingData)280 void Group::draw(SkCanvas* outCanvas, bool useStagingData) {
281     // Save the current clip and matrix information, which is local to this group.
282     SkAutoCanvasRestore saver(outCanvas, true);
283     // apply the current group's matrix to the canvas
284     SkMatrix stackedMatrix;
285     const GroupProperties& prop = useStagingData ? mStagingProperties : mProperties;
286     getLocalMatrix(&stackedMatrix, prop);
287     outCanvas->concat(stackedMatrix);
288     // Draw the group tree in the same order as the XML file.
289     for (auto& child : mChildren) {
290         child->draw(outCanvas, useStagingData);
291     }
292     // Restore the previous clip and matrix information.
293 }
294 
dump()295 void Group::dump() {
296     ALOGD("Group %s has %zu children: ", mName.c_str(), mChildren.size());
297     ALOGD("Group translateX, Y : %f, %f, scaleX, Y: %f, %f", mProperties.getTranslateX(),
298           mProperties.getTranslateY(), mProperties.getScaleX(), mProperties.getScaleY());
299     for (size_t i = 0; i < mChildren.size(); i++) {
300         mChildren[i]->dump();
301     }
302 }
303 
syncProperties()304 void Group::syncProperties() {
305     // Copy over the dirty staging properties
306     if (mStagingPropertiesDirty) {
307         mProperties.syncProperties(mStagingProperties);
308     } else {
309         mStagingProperties.syncProperties(mProperties);
310     }
311     mStagingPropertiesDirty = false;
312     for (auto& child : mChildren) {
313         child->syncProperties();
314     }
315 }
316 
getLocalMatrix(SkMatrix * outMatrix,const GroupProperties & properties)317 void Group::getLocalMatrix(SkMatrix* outMatrix, const GroupProperties& properties) {
318     outMatrix->reset();
319     // TODO: use rotate(mRotate, mPivotX, mPivotY) and scale with pivot point, instead of
320     // translating to pivot for rotating and scaling, then translating back.
321     outMatrix->postTranslate(-properties.getPivotX(), -properties.getPivotY());
322     outMatrix->postScale(properties.getScaleX(), properties.getScaleY());
323     outMatrix->postRotate(properties.getRotation(), 0, 0);
324     outMatrix->postTranslate(properties.getTranslateX() + properties.getPivotX(),
325                              properties.getTranslateY() + properties.getPivotY());
326 }
327 
addChild(Node * child)328 void Group::addChild(Node* child) {
329     mChildren.emplace_back(child);
330     if (mPropertyChangedListener != nullptr) {
331         child->setPropertyChangedListener(mPropertyChangedListener);
332     }
333 }
334 
copyProperties(float * outProperties,int length) const335 bool Group::GroupProperties::copyProperties(float* outProperties, int length) const {
336     int propertyCount = static_cast<int>(Property::count);
337     if (length != propertyCount) {
338         LOG_ALWAYS_FATAL("Properties needs exactly %d bytes, a byte array of size %d is provided",
339                          propertyCount, length);
340         return false;
341     }
342 
343     PrimitiveFields* out = reinterpret_cast<PrimitiveFields*>(outProperties);
344     *out = mPrimitiveFields;
345     return true;
346 }
347 
348 // TODO: Consider animating the properties as float pointers
349 // Called on render thread
getPropertyValue(int propertyId) const350 float Group::GroupProperties::getPropertyValue(int propertyId) const {
351     Property currentProperty = static_cast<Property>(propertyId);
352     switch (currentProperty) {
353         case Property::rotate:
354             return getRotation();
355         case Property::pivotX:
356             return getPivotX();
357         case Property::pivotY:
358             return getPivotY();
359         case Property::scaleX:
360             return getScaleX();
361         case Property::scaleY:
362             return getScaleY();
363         case Property::translateX:
364             return getTranslateX();
365         case Property::translateY:
366             return getTranslateY();
367         default:
368             LOG_ALWAYS_FATAL("Invalid property index: %d", propertyId);
369             return 0;
370     }
371 }
372 
373 // Called on render thread
setPropertyValue(int propertyId,float value)374 void Group::GroupProperties::setPropertyValue(int propertyId, float value) {
375     Property currentProperty = static_cast<Property>(propertyId);
376     switch (currentProperty) {
377         case Property::rotate:
378             setRotation(value);
379             break;
380         case Property::pivotX:
381             setPivotX(value);
382             break;
383         case Property::pivotY:
384             setPivotY(value);
385             break;
386         case Property::scaleX:
387             setScaleX(value);
388             break;
389         case Property::scaleY:
390             setScaleY(value);
391             break;
392         case Property::translateX:
393             setTranslateX(value);
394             break;
395         case Property::translateY:
396             setTranslateY(value);
397             break;
398         default:
399             LOG_ALWAYS_FATAL("Invalid property index: %d", propertyId);
400     }
401 }
402 
isValidProperty(int propertyId)403 bool Group::isValidProperty(int propertyId) {
404     return GroupProperties::isValidProperty(propertyId);
405 }
406 
isValidProperty(int propertyId)407 bool Group::GroupProperties::isValidProperty(int propertyId) {
408     return propertyId >= 0 && propertyId < static_cast<int>(Property::count);
409 }
410 
draw(Canvas * outCanvas,SkColorFilter * colorFilter,const SkRect & bounds,bool needsMirroring,bool canReuseCache)411 int Tree::draw(Canvas* outCanvas, SkColorFilter* colorFilter, const SkRect& bounds,
412                bool needsMirroring, bool canReuseCache) {
413     // The imageView can scale the canvas in different ways, in order to
414     // avoid blurry scaling, we have to draw into a bitmap with exact pixel
415     // size first. This bitmap size is determined by the bounds and the
416     // canvas scale.
417     SkMatrix canvasMatrix;
418     outCanvas->getMatrix(&canvasMatrix);
419     float canvasScaleX = 1.0f;
420     float canvasScaleY = 1.0f;
421     if (canvasMatrix.getSkewX() == 0 && canvasMatrix.getSkewY() == 0) {
422         // Only use the scale value when there's no skew or rotation in the canvas matrix.
423         // TODO: Add a cts test for drawing VD on a canvas with negative scaling factors.
424         canvasScaleX = fabs(canvasMatrix.getScaleX());
425         canvasScaleY = fabs(canvasMatrix.getScaleY());
426     }
427     int scaledWidth = (int)(bounds.width() * canvasScaleX);
428     int scaledHeight = (int)(bounds.height() * canvasScaleY);
429     scaledWidth = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledWidth);
430     scaledHeight = std::min(Tree::MAX_CACHED_BITMAP_SIZE, scaledHeight);
431 
432     if (scaledWidth <= 0 || scaledHeight <= 0) {
433         return 0;
434     }
435 
436     mStagingProperties.setScaledSize(scaledWidth, scaledHeight);
437     int saveCount = outCanvas->save(SaveFlags::MatrixClip);
438     outCanvas->translate(bounds.fLeft, bounds.fTop);
439 
440     // Handle RTL mirroring.
441     if (needsMirroring) {
442         outCanvas->translate(bounds.width(), 0);
443         outCanvas->scale(-1.0f, 1.0f);
444     }
445     mStagingProperties.setColorFilter(colorFilter);
446 
447     // At this point, canvas has been translated to the right position.
448     // And we use this bound for the destination rect for the drawBitmap, so
449     // we offset to (0, 0);
450     SkRect tmpBounds = bounds;
451     tmpBounds.offsetTo(0, 0);
452     mStagingProperties.setBounds(tmpBounds);
453     outCanvas->drawVectorDrawable(this);
454     outCanvas->restoreToCount(saveCount);
455     return scaledWidth * scaledHeight;
456 }
457 
drawStaging(Canvas * outCanvas)458 void Tree::drawStaging(Canvas* outCanvas) {
459     bool redrawNeeded = allocateBitmapIfNeeded(mStagingCache, mStagingProperties.getScaledWidth(),
460                                                mStagingProperties.getScaledHeight());
461     // draw bitmap cache
462     if (redrawNeeded || mStagingCache.dirty) {
463         updateBitmapCache(*mStagingCache.bitmap, true);
464         mStagingCache.dirty = false;
465     }
466 
467     Paint skp;
468     getPaintFor(&skp, mStagingProperties);
469     Paint paint;
470     paint.setFilterBitmap(skp.isFilterBitmap());
471     paint.setColorFilter(skp.refColorFilter());
472     paint.setAlpha(skp.getAlpha());
473     outCanvas->drawBitmap(*mStagingCache.bitmap, 0, 0, mStagingCache.bitmap->width(),
474                           mStagingCache.bitmap->height(), mStagingProperties.getBounds().left(),
475                           mStagingProperties.getBounds().top(),
476                           mStagingProperties.getBounds().right(),
477                           mStagingProperties.getBounds().bottom(), &paint);
478 }
479 
getPaintFor(Paint * outPaint,const TreeProperties & prop) const480 void Tree::getPaintFor(Paint* outPaint, const TreeProperties& prop) const {
481     // HWUI always draws VD with bilinear filtering.
482     outPaint->setFilterBitmap(true);
483     if (prop.getColorFilter() != nullptr) {
484         outPaint->setColorFilter(sk_ref_sp(prop.getColorFilter()));
485     }
486     outPaint->setAlpha(prop.getRootAlpha() * 255);
487 }
488 
getBitmapUpdateIfDirty()489 Bitmap& Tree::getBitmapUpdateIfDirty() {
490     bool redrawNeeded = allocateBitmapIfNeeded(mCache, mProperties.getScaledWidth(),
491                                                mProperties.getScaledHeight());
492     if (redrawNeeded || mCache.dirty) {
493         updateBitmapCache(*mCache.bitmap, false);
494         mCache.dirty = false;
495     }
496     return *mCache.bitmap;
497 }
498 
draw(SkCanvas * canvas,const SkRect & bounds,const SkPaint & inPaint)499 void Tree::draw(SkCanvas* canvas, const SkRect& bounds, const SkPaint& inPaint) {
500     if (canvas->quickReject(bounds)) {
501         // The RenderNode is on screen, but the AVD is not.
502         return;
503     }
504 
505     // Update the paint for any animatable properties
506     SkPaint paint = inPaint;
507     paint.setAlpha(mProperties.getRootAlpha() * 255);
508 
509     sk_sp<SkImage> cachedBitmap = getBitmapUpdateIfDirty().makeImage();
510 
511     // HWUI always draws VD with bilinear filtering.
512     auto sampling = SkSamplingOptions(SkFilterMode::kLinear);
513     int scaledWidth = SkScalarCeilToInt(mProperties.getScaledWidth());
514     int scaledHeight = SkScalarCeilToInt(mProperties.getScaledHeight());
515     canvas->drawImageRect(cachedBitmap, SkRect::MakeWH(scaledWidth, scaledHeight), bounds,
516                           sampling, &paint, SkCanvas::kFast_SrcRectConstraint);
517 }
518 
updateBitmapCache(Bitmap & bitmap,bool useStagingData)519 void Tree::updateBitmapCache(Bitmap& bitmap, bool useStagingData) {
520     SkBitmap outCache;
521     bitmap.getSkBitmap(&outCache);
522     int cacheWidth = outCache.width();
523     int cacheHeight = outCache.height();
524     ATRACE_FORMAT("VectorDrawable repaint %dx%d", cacheWidth, cacheHeight);
525     outCache.eraseColor(SK_ColorTRANSPARENT);
526     SkCanvas outCanvas(outCache);
527     float viewportWidth =
528             useStagingData ? mStagingProperties.getViewportWidth() : mProperties.getViewportWidth();
529     float viewportHeight = useStagingData ? mStagingProperties.getViewportHeight()
530                                           : mProperties.getViewportHeight();
531     float scaleX = cacheWidth / viewportWidth;
532     float scaleY = cacheHeight / viewportHeight;
533     outCanvas.scale(scaleX, scaleY);
534     mRootNode->draw(&outCanvas, useStagingData);
535 }
536 
allocateBitmapIfNeeded(Cache & cache,int width,int height)537 bool Tree::allocateBitmapIfNeeded(Cache& cache, int width, int height) {
538     if (!canReuseBitmap(cache.bitmap.get(), width, height)) {
539         SkImageInfo info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType);
540         cache.bitmap = Bitmap::allocateHeapBitmap(info);
541         return true;
542     }
543     return false;
544 }
545 
canReuseBitmap(Bitmap * bitmap,int width,int height)546 bool Tree::canReuseBitmap(Bitmap* bitmap, int width, int height) {
547     return bitmap && width <= bitmap->width() && height <= bitmap->height();
548 }
549 
onPropertyChanged(TreeProperties * prop)550 void Tree::onPropertyChanged(TreeProperties* prop) {
551     if (prop == &mStagingProperties) {
552         mStagingCache.dirty = true;
553     } else {
554         mCache.dirty = true;
555     }
556 }
557 
558 class MinMaxAverage {
559 public:
add(float sample)560     void add(float sample) {
561         if (mCount == 0) {
562             mMin = sample;
563             mMax = sample;
564         } else {
565             mMin = std::min(mMin, sample);
566             mMax = std::max(mMax, sample);
567         }
568         mTotal += sample;
569         mCount++;
570     }
571 
average()572     float average() { return mTotal / mCount; }
573 
min()574     float min() { return mMin; }
575 
max()576     float max() { return mMax; }
577 
delta()578     float delta() { return mMax - mMin; }
579 
580 private:
581     float mMin = 0.0f;
582     float mMax = 0.0f;
583     float mTotal = 0.0f;
584     int mCount = 0;
585 };
586 
computePalette()587 BitmapPalette Tree::computePalette() {
588     // TODO Cache this and share the code with Bitmap.cpp
589 
590     ATRACE_CALL();
591 
592     // TODO: This calculation of converting to HSV & tracking min/max is probably overkill
593     // Experiment with something simpler since we just want to figure out if it's "color-ful"
594     // and then the average perceptual lightness.
595 
596     MinMaxAverage hue, saturation, value;
597     int sampledCount = 0;
598 
599     // Sample a grid of 100 pixels to get an overall estimation of the colors in play
600     mRootNode->forEachFillColor([&](SkColor color) {
601         if (SkColorGetA(color) < 75) {
602             return;
603         }
604         sampledCount++;
605         float hsv[3];
606         SkColorToHSV(color, hsv);
607         hue.add(hsv[0]);
608         saturation.add(hsv[1]);
609         value.add(hsv[2]);
610     });
611 
612     if (sampledCount == 0) {
613         ALOGV("VectorDrawable is mostly translucent");
614         return BitmapPalette::Unknown;
615     }
616 
617     ALOGV("samples = %d, hue [min = %f, max = %f, avg = %f]; saturation [min = %f, max = %f, avg = "
618           "%f]; value [min = %f, max = %f, avg = %f]",
619           sampledCount, hue.min(), hue.max(), hue.average(), saturation.min(), saturation.max(),
620           saturation.average(), value.min(), value.max(), value.average());
621 
622     if (hue.delta() <= 20 && saturation.delta() <= .1f) {
623         if (value.average() >= .5f) {
624             return BitmapPalette::Light;
625         } else {
626             return BitmapPalette::Dark;
627         }
628     }
629     return BitmapPalette::Unknown;
630 }
631 
632 }  // namespace VectorDrawable
633 
634 }  // namespace uirenderer
635 }  // namespace android
636