1 /*
2 * Copyright (C) 2016 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 "RenderNodeDrawable.h"
18 #include <SkPaintFilterCanvas.h>
19 #include <gui/TraceUtils.h>
20 #include "RenderNode.h"
21 #include "SkiaDisplayList.h"
22 #include "StretchMask.h"
23 #include "TransformCanvas.h"
24
25 #include <include/effects/SkImageFilters.h>
26
27 #include <optional>
28
29 namespace android {
30 namespace uirenderer {
31 namespace skiapipeline {
32
RenderNodeDrawable(RenderNode * node,SkCanvas * canvas,bool composeLayer,bool inReorderingSection)33 RenderNodeDrawable::RenderNodeDrawable(RenderNode* node, SkCanvas* canvas, bool composeLayer,
34 bool inReorderingSection)
35 : mRenderNode(node)
36 , mRecordedTransform(canvas->getTotalMatrix())
37 , mComposeLayer(composeLayer)
38 , mInReorderingSection(inReorderingSection) {}
39
~RenderNodeDrawable()40 RenderNodeDrawable::~RenderNodeDrawable() {
41 // Just here to move the destructor into the cpp file where we can access RenderNode.
42
43 // TODO: Detangle the header nightmare.
44 }
45
drawBackwardsProjectedNodes(SkCanvas * canvas,const SkiaDisplayList & displayList,int nestLevel) const46 void RenderNodeDrawable::drawBackwardsProjectedNodes(SkCanvas* canvas,
47 const SkiaDisplayList& displayList,
48 int nestLevel) const {
49 LOG_ALWAYS_FATAL_IF(0 == nestLevel && !displayList.mProjectionReceiver);
50 for (auto& child : displayList.mChildNodes) {
51 const RenderProperties& childProperties = child.getNodeProperties();
52
53 // immediate children cannot be projected on their parent
54 if (childProperties.getProjectBackwards() && nestLevel > 0) {
55 SkAutoCanvasRestore acr2(canvas, true);
56 // Apply recorded matrix, which is a total matrix saved at recording time to avoid
57 // replaying all DL commands.
58 canvas->concat(child.getRecordedMatrix());
59 child.drawContent(canvas);
60 }
61
62 // skip walking sub-nodes if current display list contains a receiver with exception of
63 // level 0, which is a known receiver
64 if (0 == nestLevel || !displayList.containsProjectionReceiver()) {
65 SkAutoCanvasRestore acr(canvas, true);
66 SkMatrix nodeMatrix;
67 mat4 hwuiMatrix(child.getRecordedMatrix());
68 const RenderNode* childNode = child.getRenderNode();
69 childNode->applyViewPropertyTransforms(hwuiMatrix);
70 hwuiMatrix.copyTo(nodeMatrix);
71 canvas->concat(nodeMatrix);
72 const SkiaDisplayList* childDisplayList = childNode->getDisplayList().asSkiaDl();
73 if (childDisplayList) {
74 drawBackwardsProjectedNodes(canvas, *childDisplayList, nestLevel + 1);
75 }
76 }
77 }
78 }
79
clipOutline(const Outline & outline,SkCanvas * canvas,const SkRect * pendingClip)80 static void clipOutline(const Outline& outline, SkCanvas* canvas, const SkRect* pendingClip) {
81 Rect possibleRect;
82 float radius;
83
84 /* To match the existing HWUI behavior we only supports rectangles or
85 * rounded rectangles; passing in a more complicated outline fails silently.
86 */
87 if (!outline.getAsRoundRect(&possibleRect, &radius)) {
88 if (pendingClip) {
89 canvas->clipRect(*pendingClip);
90 }
91 return;
92 }
93
94 SkRect rect = possibleRect.toSkRect();
95 if (radius != 0.0f) {
96 if (pendingClip && !pendingClip->contains(rect)) {
97 canvas->clipRect(*pendingClip);
98 }
99 canvas->clipRRect(SkRRect::MakeRectXY(rect, radius, radius), SkClipOp::kIntersect, true);
100 } else {
101 if (pendingClip) {
102 (void)rect.intersect(*pendingClip);
103 }
104 canvas->clipRect(rect);
105 }
106 }
107
getNodeProperties() const108 const RenderProperties& RenderNodeDrawable::getNodeProperties() const {
109 return mRenderNode->properties();
110 }
111
onDraw(SkCanvas * canvas)112 void RenderNodeDrawable::onDraw(SkCanvas* canvas) {
113 // negative and positive Z order are drawn out of order, if this render node drawable is in
114 // a reordering section
115 if ((!mInReorderingSection) || MathUtils::isZero(mRenderNode->properties().getZ())) {
116 this->forceDraw(canvas);
117 }
118 }
119
120 class MarkDraw {
121 public:
MarkDraw(SkCanvas & canvas,RenderNode & node)122 explicit MarkDraw(SkCanvas& canvas, RenderNode& node) : mCanvas(canvas), mNode(node) {
123 if (CC_UNLIKELY(Properties::skpCaptureEnabled)) {
124 mNode.markDrawStart(mCanvas);
125 }
126 }
~MarkDraw()127 ~MarkDraw() {
128 if (CC_UNLIKELY(Properties::skpCaptureEnabled)) {
129 mNode.markDrawEnd(mCanvas);
130 }
131 }
132
133 private:
134 SkCanvas& mCanvas;
135 RenderNode& mNode;
136 };
137
forceDraw(SkCanvas * canvas) const138 void RenderNodeDrawable::forceDraw(SkCanvas* canvas) const {
139 RenderNode* renderNode = mRenderNode.get();
140 MarkDraw _marker{*canvas, *renderNode};
141
142 // We only respect the nothingToDraw check when we are composing a layer. This
143 // ensures that we paint the layer even if it is not currently visible in the
144 // event that the properties change and it becomes visible.
145 if ((mProjectedDisplayList == nullptr && !renderNode->isRenderable()) ||
146 (renderNode->nothingToDraw() && mComposeLayer)) {
147 return;
148 }
149
150 SkiaDisplayList* displayList = renderNode->getDisplayList().asSkiaDl();
151
152 SkAutoCanvasRestore acr(canvas, true);
153 const RenderProperties& properties = this->getNodeProperties();
154 // pass this outline to the children that may clip backward projected nodes
155 displayList->mProjectedOutline =
156 displayList->containsProjectionReceiver() ? &properties.getOutline() : nullptr;
157 if (!properties.getProjectBackwards()) {
158 drawContent(canvas);
159 if (mProjectedDisplayList) {
160 acr.restore(); // draw projected children using parent matrix
161 LOG_ALWAYS_FATAL_IF(!mProjectedDisplayList->mProjectedOutline);
162 const bool shouldClip = mProjectedDisplayList->mProjectedOutline->getPath();
163 SkAutoCanvasRestore acr2(canvas, shouldClip);
164 canvas->setMatrix(mProjectedDisplayList->mParentMatrix);
165 if (shouldClip) {
166 canvas->clipPath(*mProjectedDisplayList->mProjectedOutline->getPath());
167 }
168 drawBackwardsProjectedNodes(canvas, *mProjectedDisplayList);
169 }
170 }
171 displayList->mProjectedOutline = nullptr;
172 }
173
layerNeedsPaint(const LayerProperties & properties,float alphaMultiplier,SkPaint * paint)174 static bool layerNeedsPaint(const LayerProperties& properties, float alphaMultiplier,
175 SkPaint* paint) {
176 if (alphaMultiplier < 1.0f || properties.alpha() < 255 ||
177 properties.xferMode() != SkBlendMode::kSrcOver || properties.getColorFilter() != nullptr ||
178 properties.getStretchEffect().requiresLayer()) {
179 paint->setAlpha(properties.alpha() * alphaMultiplier);
180 paint->setBlendMode(properties.xferMode());
181 paint->setColorFilter(sk_ref_sp(properties.getColorFilter()));
182 return true;
183 }
184 return false;
185 }
186
187 class AlphaFilterCanvas : public SkPaintFilterCanvas {
188 public:
AlphaFilterCanvas(SkCanvas * canvas,float alpha)189 AlphaFilterCanvas(SkCanvas* canvas, float alpha) : SkPaintFilterCanvas(canvas), mAlpha(alpha) {}
190
191 protected:
onFilter(SkPaint & paint) const192 bool onFilter(SkPaint& paint) const override {
193 paint.setAlpha((uint8_t)paint.getAlpha() * mAlpha);
194 return true;
195 }
onDrawDrawable(SkDrawable * drawable,const SkMatrix * matrix)196 void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {
197 // We unroll the drawable using "this" canvas, so that draw calls contained inside will
198 // get their alpha applied. The default SkPaintFilterCanvas::onDrawDrawable does not unroll.
199 drawable->draw(this, matrix);
200 }
201
202 private:
203 float mAlpha;
204 };
205
drawContent(SkCanvas * canvas) const206 void RenderNodeDrawable::drawContent(SkCanvas* canvas) const {
207 RenderNode* renderNode = mRenderNode.get();
208 float alphaMultiplier = 1.0f;
209 const RenderProperties& properties = renderNode->properties();
210
211 // If we are drawing the contents of layer, we don't want to apply any of
212 // the RenderNode's properties during this pass. Those will all be applied
213 // when the layer is composited.
214 if (mComposeLayer) {
215 setViewProperties(properties, canvas, &alphaMultiplier);
216 }
217 SkiaDisplayList* displayList = mRenderNode->getDisplayList().asSkiaDl();
218 displayList->mParentMatrix = canvas->getTotalMatrix();
219
220 // TODO should we let the bound of the drawable do this for us?
221 const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
222 bool quickRejected = properties.getClipToBounds() && canvas->quickReject(bounds);
223 auto clipBounds = canvas->getLocalClipBounds();
224 SkIRect srcBounds = SkIRect::MakeWH(bounds.width(), bounds.height());
225 SkIPoint offset = SkIPoint::Make(0.0f, 0.0f);
226 if (!quickRejected) {
227 SkiaDisplayList* displayList = renderNode->getDisplayList().asSkiaDl();
228 const LayerProperties& layerProperties = properties.layerProperties();
229 // composing a hardware layer
230 if (renderNode->getLayerSurface() && mComposeLayer) {
231 SkASSERT(properties.effectiveLayerType() == LayerType::RenderLayer);
232 SkPaint paint;
233 layerNeedsPaint(layerProperties, alphaMultiplier, &paint);
234 sk_sp<SkImage> snapshotImage;
235 auto* imageFilter = layerProperties.getImageFilter();
236 auto recordingContext = canvas->recordingContext();
237 // On some GL vendor implementations, caching the result of
238 // getLayerSurface->makeImageSnapshot() causes a call to
239 // Fence::waitForever without a corresponding signal. This would
240 // lead to ANRs throughout the system.
241 // Instead only cache the SkImage created with the SkImageFilter
242 // for supported devices. Otherwise just create a new SkImage with
243 // the corresponding SkImageFilter each time.
244 // See b/193145089 and b/197263715
245 if (!Properties::enableRenderEffectCache) {
246 snapshotImage = renderNode->getLayerSurface()->makeImageSnapshot();
247 if (imageFilter) {
248 auto subset = SkIRect::MakeWH(srcBounds.width(), srcBounds.height());
249 snapshotImage = snapshotImage->makeWithFilter(recordingContext, imageFilter,
250 subset, clipBounds.roundOut(),
251 &srcBounds, &offset);
252 }
253 } else {
254 const auto snapshotResult = renderNode->updateSnapshotIfRequired(
255 recordingContext, layerProperties.getImageFilter(), clipBounds.roundOut());
256 snapshotImage = snapshotResult->snapshot;
257 srcBounds = snapshotResult->outSubset;
258 offset = snapshotResult->outOffset;
259 }
260
261 const auto dstBounds = SkIRect::MakeXYWH(offset.x(),
262 offset.y(),
263 srcBounds.width(),
264 srcBounds.height());
265 SkSamplingOptions sampling(SkFilterMode::kLinear);
266
267 // surfaces for layers are created on LAYER_SIZE boundaries (which are >= layer size) so
268 // we need to restrict the portion of the surface drawn to the size of the renderNode.
269 SkASSERT(renderNode->getLayerSurface()->width() >= bounds.width());
270 SkASSERT(renderNode->getLayerSurface()->height() >= bounds.height());
271
272 // If SKP recording is active save an annotation that indicates this drawImageRect
273 // could also be rendered with the commands saved at ID associated with this node.
274 if (CC_UNLIKELY(Properties::skpCaptureEnabled)) {
275 canvas->drawAnnotation(bounds, String8::format(
276 "SurfaceID|%" PRId64, renderNode->uniqueId()).c_str(), nullptr);
277 }
278
279 const StretchEffect& stretch = properties.layerProperties().getStretchEffect();
280 if (stretch.isEmpty() ||
281 Properties::getStretchEffectBehavior() == StretchEffectBehavior::UniformScale) {
282 // If we don't have any stretch effects, issue the filtered
283 // canvas draw calls to make sure we still punch a hole
284 // with the same canvas transformation + clip into the target
285 // canvas then draw the layer on top
286 if (renderNode->hasHolePunches()) {
287 TransformCanvas transformCanvas(canvas, SkBlendMode::kClear);
288 displayList->draw(&transformCanvas);
289 }
290 canvas->drawImageRect(snapshotImage, SkRect::Make(srcBounds),
291 SkRect::Make(dstBounds), sampling, &paint,
292 SkCanvas::kStrict_SrcRectConstraint);
293 } else {
294 // If we do have stretch effects and have hole punches,
295 // then create a mask and issue the filtered draw calls to
296 // get the corresponding hole punches.
297 // Then apply the stretch to the mask and draw the mask to
298 // the destination
299 // Also if the stretchy container has an ImageFilter applied
300 // to it (i.e. blur) we need to take into account the offset
301 // that will be generated with this result. Ex blurs will "grow"
302 // the source image by the blur radius so we need to translate
303 // the shader by the same amount to render in the same location
304 SkMatrix matrix;
305 matrix.setTranslate(
306 offset.x() - srcBounds.left(),
307 offset.y() - srcBounds.top()
308 );
309 if (renderNode->hasHolePunches()) {
310 GrRecordingContext* context = canvas->recordingContext();
311 StretchMask& stretchMask = renderNode->getStretchMask();
312 stretchMask.draw(context,
313 stretch,
314 bounds,
315 displayList,
316 canvas);
317 }
318
319 sk_sp<SkShader> stretchShader =
320 stretch.getShader(bounds.width(), bounds.height(), snapshotImage, &matrix);
321 paint.setShader(stretchShader);
322 canvas->drawRect(SkRect::Make(dstBounds), paint);
323 }
324
325 if (!renderNode->getSkiaLayer()->hasRenderedSinceRepaint) {
326 renderNode->getSkiaLayer()->hasRenderedSinceRepaint = true;
327 if (CC_UNLIKELY(Properties::debugLayersUpdates)) {
328 SkPaint layerPaint;
329 layerPaint.setColor(0x7f00ff00);
330 canvas->drawRect(bounds, layerPaint);
331 } else if (CC_UNLIKELY(Properties::debugOverdraw)) {
332 // Render transparent rect to increment overdraw for repaint area.
333 // This can be "else if" because flashing green on layer updates
334 // will also increment the overdraw if it happens to be turned on.
335 SkPaint transparentPaint;
336 transparentPaint.setColor(SK_ColorTRANSPARENT);
337 canvas->drawRect(bounds, transparentPaint);
338 }
339 }
340 } else {
341 if (alphaMultiplier < 1.0f) {
342 // Non-layer draw for a view with getHasOverlappingRendering=false, will apply
343 // the alpha to the paint of each nested draw.
344 AlphaFilterCanvas alphaCanvas(canvas, alphaMultiplier);
345 displayList->draw(&alphaCanvas);
346 } else {
347 displayList->draw(canvas);
348 }
349 }
350 }
351 }
352
setViewProperties(const RenderProperties & properties,SkCanvas * canvas,float * alphaMultiplier)353 void RenderNodeDrawable::setViewProperties(const RenderProperties& properties, SkCanvas* canvas,
354 float* alphaMultiplier) {
355 if (properties.getLeft() != 0 || properties.getTop() != 0) {
356 canvas->translate(properties.getLeft(), properties.getTop());
357 }
358 if (properties.getStaticMatrix()) {
359 canvas->concat(*properties.getStaticMatrix());
360 } else if (properties.getAnimationMatrix()) {
361 canvas->concat(*properties.getAnimationMatrix());
362 }
363 if (properties.hasTransformMatrix()) {
364 if (properties.isTransformTranslateOnly()) {
365 canvas->translate(properties.getTranslationX(), properties.getTranslationY());
366 } else {
367 canvas->concat(*properties.getTransformMatrix());
368 }
369 }
370 if (Properties::getStretchEffectBehavior() == StretchEffectBehavior::UniformScale) {
371 const StretchEffect& stretch = properties.layerProperties().getStretchEffect();
372 if (!stretch.isEmpty()) {
373 canvas->concat(
374 stretch.makeLinearStretch(properties.getWidth(), properties.getHeight()));
375 }
376 }
377 const bool isLayer = properties.effectiveLayerType() != LayerType::None;
378 int clipFlags = properties.getClippingFlags();
379 if (properties.getAlpha() < 1) {
380 if (isLayer) {
381 clipFlags &= ~CLIP_TO_BOUNDS; // bounds clipping done by layer
382 }
383 if (CC_LIKELY(isLayer || !properties.getHasOverlappingRendering())) {
384 *alphaMultiplier = properties.getAlpha();
385 } else {
386 // savelayer needed to create an offscreen buffer
387 Rect layerBounds(0, 0, properties.getWidth(), properties.getHeight());
388 if (clipFlags) {
389 properties.getClippingRectForFlags(clipFlags, &layerBounds);
390 clipFlags = 0; // all clipping done by savelayer
391 }
392 SkRect bounds = SkRect::MakeLTRB(layerBounds.left, layerBounds.top, layerBounds.right,
393 layerBounds.bottom);
394 canvas->saveLayerAlpha(&bounds, (int)(properties.getAlpha() * 255));
395 }
396
397 if (CC_UNLIKELY(ATRACE_ENABLED() && properties.promotedToLayer())) {
398 // pretend alpha always causes savelayer to warn about
399 // performance problem affecting old versions
400 ATRACE_FORMAT("alpha caused saveLayer %dx%d", properties.getWidth(),
401 properties.getHeight());
402 }
403 }
404
405 const SkRect* pendingClip = nullptr;
406 SkRect clipRect;
407
408 if (clipFlags) {
409 Rect tmpRect;
410 properties.getClippingRectForFlags(clipFlags, &tmpRect);
411 clipRect = tmpRect.toSkRect();
412 pendingClip = &clipRect;
413 }
414
415 if (properties.getRevealClip().willClip()) {
416 canvas->clipPath(*properties.getRevealClip().getPath(), SkClipOp::kIntersect, true);
417 } else if (properties.getOutline().willClip()) {
418 clipOutline(properties.getOutline(), canvas, pendingClip);
419 pendingClip = nullptr;
420 }
421
422 if (pendingClip) {
423 canvas->clipRect(*pendingClip);
424 }
425 }
426
427 } // namespace skiapipeline
428 } // namespace uirenderer
429 } // namespace android
430