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