blob: c11a2bb80ee54be49b2f1ee46cf187021cbe0fcb [file] [log] [blame]
Stan Iliev500a0c32016-10-26 10:30:09 -04001/*
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 "SkiaPipeline.h"
18
19#include "utils/TraceUtils.h"
20#include <SkOSFile.h>
21#include <SkPicture.h>
22#include <SkPictureRecorder.h>
23#include <SkPixelSerializer.h>
24#include <SkStream.h>
25
26using namespace android::uirenderer::renderthread;
27
28namespace android {
29namespace uirenderer {
30namespace skiapipeline {
31
32float SkiaPipeline::mLightRadius = 0;
33uint8_t SkiaPipeline::mAmbientShadowAlpha = 0;
34uint8_t SkiaPipeline::mSpotShadowAlpha = 0;
35
36Vector3 SkiaPipeline::mLightCenter = {FLT_MIN, FLT_MIN, FLT_MIN};
37
38SkiaPipeline::SkiaPipeline(RenderThread& thread) : mRenderThread(thread) { }
39
40TaskManager* SkiaPipeline::getTaskManager() {
41 return &mTaskManager;
42}
43
44void SkiaPipeline::onDestroyHardwareResources() {
45 // No need to flush the caches here. There is a timer
46 // which will flush temporary resources over time.
47}
48
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040049bool SkiaPipeline::pinImages(std::vector<SkImage*>& mutableImages) {
50 for (SkImage* image : mutableImages) {
Derek Sollenberger189e8742016-11-16 16:00:17 -050051 if (SkImage_pinAsTexture(image, mRenderThread.getGrContext())) {
52 mPinnedImages.emplace_back(sk_ref_sp(image));
53 } else {
54 return false;
55 }
Derek Sollenbergerb7d34b62016-11-04 10:46:18 -040056 }
57 return true;
58}
59
60void SkiaPipeline::unpinImages() {
61 for (auto& image : mPinnedImages) {
62 SkImage_unpinAsTexture(image.get(), mRenderThread.getGrContext());
63 }
64 mPinnedImages.clear();
65}
66
Stan Iliev500a0c32016-10-26 10:30:09 -040067void SkiaPipeline::renderLayers(const FrameBuilder::LightGeometry& lightGeometry,
68 LayerUpdateQueue* layerUpdateQueue, bool opaque,
69 const BakedOpRenderer::LightInfo& lightInfo) {
70 updateLighting(lightGeometry, lightInfo);
71 ATRACE_NAME("draw layers");
72 renderLayersImpl(*layerUpdateQueue, opaque);
73 layerUpdateQueue->clear();
74}
75
76void SkiaPipeline::renderLayersImpl(const LayerUpdateQueue& layers, bool opaque) {
77 // Render all layers that need to be updated, in order.
78 for (size_t i = 0; i < layers.entries().size(); i++) {
79 RenderNode* layerNode = layers.entries()[i].renderNode;
80 // only schedule repaint if node still on layer - possible it may have been
81 // removed during a dropped frame, but layers may still remain scheduled so
82 // as not to lose info on what portion is damaged
83 if (CC_LIKELY(layerNode->getLayerSurface() != nullptr)) {
84 SkASSERT(layerNode->getLayerSurface());
85 SkASSERT(layerNode->getDisplayList()->isSkiaDL());
86 SkiaDisplayList* displayList = (SkiaDisplayList*)layerNode->getDisplayList();
87 if (!displayList || displayList->isEmpty()) {
88 SkDEBUGF(("%p drawLayers(%s) : missing drawable", this, layerNode->getName()));
89 return;
90 }
91
92 const Rect& layerDamage = layers.entries()[i].damage;
93
94 SkCanvas* layerCanvas = layerNode->getLayerSurface()->getCanvas();
95
96 int saveCount = layerCanvas->save();
97 SkASSERT(saveCount == 1);
98
99 layerCanvas->clipRect(layerDamage.toSkRect(), SkRegion::kReplace_Op);
100
101 auto savedLightCenter = mLightCenter;
102 // map current light center into RenderNode's coordinate space
103 layerNode->getSkiaLayer()->inverseTransformInWindow.mapPoint3d(mLightCenter);
104
105 const RenderProperties& properties = layerNode->properties();
106 const SkRect bounds = SkRect::MakeWH(properties.getWidth(), properties.getHeight());
107 if (properties.getClipToBounds() && layerCanvas->quickReject(bounds)) {
108 return;
109 }
110
111 layerCanvas->clear(SK_ColorTRANSPARENT);
112
113 RenderNodeDrawable root(layerNode, layerCanvas, false);
114 root.forceDraw(layerCanvas);
115 layerCanvas->restoreToCount(saveCount);
116 layerCanvas->flush();
117 mLightCenter = savedLightCenter;
118 }
119 }
120}
121
122bool SkiaPipeline::createOrUpdateLayer(RenderNode* node,
123 const DamageAccumulator& damageAccumulator) {
124 SkSurface* layer = node->getLayerSurface();
125 if (!layer || layer->width() != node->getWidth() || layer->height() != node->getHeight()) {
126 SkImageInfo info = SkImageInfo::MakeN32Premul(node->getWidth(), node->getHeight());
127 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
128 SkASSERT(mRenderThread.getGrContext() != nullptr);
129 node->setLayerSurface(
130 SkSurface::MakeRenderTarget(mRenderThread.getGrContext(), SkBudgeted::kYes,
131 info, 0, &props));
132 if (node->getLayerSurface()) {
133 // update the transform in window of the layer to reset its origin wrt light source
134 // position
135 Matrix4 windowTransform;
136 damageAccumulator.computeCurrentTransform(&windowTransform);
137 node->getSkiaLayer()->inverseTransformInWindow = windowTransform;
138 }
139 return true;
140 }
141 return false;
142}
143
144void SkiaPipeline::destroyLayer(RenderNode* node) {
145 node->setLayerSurface(nullptr);
146}
147
148void SkiaPipeline::prepareToDraw(const RenderThread& thread, Bitmap* bitmap) {
149 GrContext* context = thread.getGrContext();
150 if (context) {
151 ATRACE_FORMAT("Bitmap#prepareToDraw %dx%d", bitmap->width(), bitmap->height());
152 SkBitmap skiaBitmap;
153 bitmap->getSkBitmap(&skiaBitmap);
154 sk_sp<SkImage> image = SkMakeImageFromRasterBitmap(skiaBitmap, kNever_SkCopyPixelsMode);
155 SkImage_pinAsTexture(image.get(), context);
156 SkImage_unpinAsTexture(image.get(), context);
157 }
158}
159
160// Encodes to PNG, unless there is already encoded data, in which case that gets
161// used.
162class PngPixelSerializer : public SkPixelSerializer {
163public:
164 bool onUseEncodedData(const void*, size_t) override { return true; }
165 SkData* onEncode(const SkPixmap& pixmap) override {
166 return SkImageEncoder::EncodeData(pixmap.info(), pixmap.addr(), pixmap.rowBytes(),
167 SkImageEncoder::kPNG_Type, 100);
168 }
169};
170
171void SkiaPipeline::renderFrame(const LayerUpdateQueue& layers, const SkRect& clip,
172 const std::vector<sp<RenderNode>>& nodes, bool opaque, const Rect &contentDrawBounds,
173 sk_sp<SkSurface> surface) {
174
Stan Iliev500a0c32016-10-26 10:30:09 -0400175 // draw all layers up front
176 renderLayersImpl(layers, opaque);
177
178 // initialize the canvas for the current frame
179 SkCanvas* canvas = surface->getCanvas();
180
181 std::unique_ptr<SkPictureRecorder> recorder;
182 bool recordingPicture = false;
183 char prop[PROPERTY_VALUE_MAX];
184 if (skpCaptureEnabled()) {
185 property_get("debug.hwui.capture_frame_as_skp", prop, "0");
186 recordingPicture = prop[0] != '0' && !sk_exists(prop);
187 if (recordingPicture) {
188 recorder.reset(new SkPictureRecorder());
189 canvas = recorder->beginRecording(surface->width(), surface->height(),
190 nullptr, SkPictureRecorder::kPlaybackDrawPicture_RecordFlag);
191 }
192 }
193
194 canvas->clipRect(clip, SkRegion::kReplace_Op);
195
196 if (!opaque) {
197 canvas->clear(SK_ColorTRANSPARENT);
198 }
199
200 // If there are multiple render nodes, they are laid out as follows:
201 // #0 - backdrop (content + caption)
202 // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds)
203 // #2 - additional overlay nodes
204 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While
205 // resizing however it might become partially visible. The following render loop will crop the
206 // backdrop against the content and draw the remaining part of it. It will then draw the content
207 // cropped to the backdrop (since that indicates a shrinking of the window).
208 //
209 // Additional nodes will be drawn on top with no particular clipping semantics.
210
211 // The bounds of the backdrop against which the content should be clipped.
212 Rect backdropBounds = contentDrawBounds;
213 // Usually the contents bounds should be mContentDrawBounds - however - we will
214 // move it towards the fixed edge to give it a more stable appearance (for the moment).
215 // If there is no content bounds we ignore the layering as stated above and start with 2.
216 int layer = (contentDrawBounds.isEmpty() || nodes.size() == 1) ? 2 : 0;
217
218 for (const sp<RenderNode>& node : nodes) {
219 if (node->nothingToDraw()) continue;
220
221 SkASSERT(node->getDisplayList()->isSkiaDL());
222
223 int count = canvas->save();
224
225 if (layer == 0) {
226 const RenderProperties& properties = node->properties();
227 Rect targetBounds(properties.getLeft(), properties.getTop(),
228 properties.getRight(), properties.getBottom());
229 // Move the content bounds towards the fixed corner of the backdrop.
230 const int x = targetBounds.left;
231 const int y = targetBounds.top;
232 // Remember the intersection of the target bounds and the intersection bounds against
233 // which we have to crop the content.
234 backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight());
235 backdropBounds.doIntersect(targetBounds);
236 } else if (layer == 1) {
237 // We shift and clip the content to match its final location in the window.
238 const SkRect clip = SkRect::MakeXYWH(contentDrawBounds.left, contentDrawBounds.top,
239 backdropBounds.getWidth(), backdropBounds.getHeight());
240 const float dx = backdropBounds.left - contentDrawBounds.left;
241 const float dy = backdropBounds.top - contentDrawBounds.top;
242 canvas->translate(dx, dy);
243 // It gets cropped against the bounds of the backdrop to stay inside.
244 canvas->clipRect(clip, SkRegion::kIntersect_Op);
245 }
246
247 RenderNodeDrawable root(node.get(), canvas);
248 root.draw(canvas);
249 canvas->restoreToCount(count);
250 layer++;
251 }
252
253 if (skpCaptureEnabled() && recordingPicture) {
254 sk_sp<SkPicture> picture = recorder->finishRecordingAsPicture();
255 if (picture->approximateOpCount() > 0) {
256 SkFILEWStream stream(prop);
257 if (stream.isValid()) {
258 PngPixelSerializer serializer;
259 picture->serialize(&stream, &serializer);
260 stream.flush();
261 SkDebugf("Captured Drawing Output (%d bytes) for frame. %s", stream.bytesWritten(), prop);
262 }
263 }
264 surface->getCanvas()->drawPicture(picture);
265 }
266
267 ATRACE_NAME("flush commands");
268 canvas->flush();
269}
270
Matt Sarett4bda6bf2016-11-07 15:43:41 -0500271void SkiaPipeline::dumpResourceCacheUsage() const {
272 int resources, maxResources;
273 size_t bytes, maxBytes;
274 mRenderThread.getGrContext()->getResourceCacheUsage(&resources, &bytes);
275 mRenderThread.getGrContext()->getResourceCacheLimits(&maxResources, &maxBytes);
276
277 SkString log("Resource Cache Usage:\n");
278 log.appendf("%8d items out of %d maximum items\n", resources, maxResources);
279 log.appendf("%8zu bytes (%.2f MB) out of %.2f MB maximum\n",
280 bytes, bytes * (1.0f / (1024.0f * 1024.0f)), maxBytes * (1.0f / (1024.0f * 1024.0f)));
281
282 ALOGD("%s", log.c_str());
283}
284
Stan Iliev500a0c32016-10-26 10:30:09 -0400285} /* namespace skiapipeline */
286} /* namespace uirenderer */
287} /* namespace android */