blob: afedd48d40340585e0ed64c90c4a738880a7e169 [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 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//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Alec Mourib5777452020-09-28 11:32:42 -070022#include "SkiaGLRenderEngine.h"
John Reck67b1e2b2020-08-26 13:17:24 -070023
24#include <EGL/egl.h>
25#include <EGL/eglext.h>
26#include <GLES2/gl2.h>
John Reck67b1e2b2020-08-26 13:17:24 -070027#include <GrContextOptions.h>
John Reck67b1e2b2020-08-26 13:17:24 -070028#include <SkCanvas.h>
Alec Mourib5777452020-09-28 11:32:42 -070029#include <SkColorSpace.h>
John Reck67b1e2b2020-08-26 13:17:24 -070030#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070031#include <SkImageFilters.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070032#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070033#include <SkSurface.h>
Alec Mourib5777452020-09-28 11:32:42 -070034#include <gl/GrGLInterface.h>
35#include <sync/sync.h>
36#include <ui/GraphicBuffer.h>
37#include <utils/Trace.h>
38
39#include <cmath>
40
41#include "../gl/GLExtensions.h"
42#include "filters/BlurFilter.h"
John Reck67b1e2b2020-08-26 13:17:24 -070043
44extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
45
46bool checkGlError(const char* op, int lineNumber);
47
48namespace android {
49namespace renderengine {
50namespace skia {
51
52static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
53 EGLint wanted, EGLConfig* outConfig) {
54 EGLint numConfigs = -1, n = 0;
55 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
56 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
57 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
58 configs.resize(n);
59
60 if (!configs.empty()) {
61 if (attribute != EGL_NONE) {
62 for (EGLConfig config : configs) {
63 EGLint value = 0;
64 eglGetConfigAttrib(dpy, config, attribute, &value);
65 if (wanted == value) {
66 *outConfig = config;
67 return NO_ERROR;
68 }
69 }
70 } else {
71 // just pick the first one
72 *outConfig = configs[0];
73 return NO_ERROR;
74 }
75 }
76
77 return NAME_NOT_FOUND;
78}
79
80static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
81 EGLConfig* config) {
82 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
83 // it is to be used with WIFI displays
84 status_t err;
85 EGLint wantedAttribute;
86 EGLint wantedAttributeValue;
87
88 std::vector<EGLint> attribs;
89 if (renderableType) {
90 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
91 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
92
93 // Default to 8 bits per channel.
94 const EGLint tmpAttribs[] = {
95 EGL_RENDERABLE_TYPE,
96 renderableType,
97 EGL_RECORDABLE_ANDROID,
98 EGL_TRUE,
99 EGL_SURFACE_TYPE,
100 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
101 EGL_FRAMEBUFFER_TARGET_ANDROID,
102 EGL_TRUE,
103 EGL_RED_SIZE,
104 is1010102 ? 10 : 8,
105 EGL_GREEN_SIZE,
106 is1010102 ? 10 : 8,
107 EGL_BLUE_SIZE,
108 is1010102 ? 10 : 8,
109 EGL_ALPHA_SIZE,
110 is1010102 ? 2 : 8,
111 EGL_NONE,
112 };
113 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
114 std::back_inserter(attribs));
115 wantedAttribute = EGL_NONE;
116 wantedAttributeValue = EGL_NONE;
117 } else {
118 // if no renderable type specified, fallback to a simplified query
119 wantedAttribute = EGL_NATIVE_VISUAL_ID;
120 wantedAttributeValue = format;
121 }
122
123 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
124 config);
125 if (err == NO_ERROR) {
126 EGLint caveat;
127 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
128 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
129 }
130
131 return err;
132}
133
Alec Mourib5777452020-09-28 11:32:42 -0700134// Converts an android dataspace to a supported SkColorSpace
135// Supported dataspaces are
136// 1. sRGB
137// 2. Display P3
138// 3. BT2020 PQ
139// 4. BT2020 HLG
140// Unknown primaries are mapped to BT709, and unknown transfer functions
141// are mapped to sRGB.
142static sk_sp<SkColorSpace> toColorSpace(ui::Dataspace dataspace) {
143 skcms_Matrix3x3 gamut;
144 switch (dataspace & HAL_DATASPACE_STANDARD_MASK) {
145 case HAL_DATASPACE_STANDARD_BT709:
146 gamut = SkNamedGamut::kSRGB;
147 break;
148 case HAL_DATASPACE_STANDARD_BT2020:
149 gamut = SkNamedGamut::kRec2020;
150 break;
151 case HAL_DATASPACE_STANDARD_DCI_P3:
152 gamut = SkNamedGamut::kDisplayP3;
153 break;
154 default:
155 ALOGV("Unsupported Gamut: %d, defaulting to sRGB", dataspace);
156 gamut = SkNamedGamut::kSRGB;
157 break;
158 }
159
160 switch (dataspace & HAL_DATASPACE_TRANSFER_MASK) {
161 case HAL_DATASPACE_TRANSFER_LINEAR:
162 return SkColorSpace::MakeRGB(SkNamedTransferFn::kLinear, gamut);
163 case HAL_DATASPACE_TRANSFER_SRGB:
164 return SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, gamut);
165 case HAL_DATASPACE_TRANSFER_ST2084:
166 return SkColorSpace::MakeRGB(SkNamedTransferFn::kPQ, gamut);
167 case HAL_DATASPACE_TRANSFER_HLG:
168 return SkColorSpace::MakeRGB(SkNamedTransferFn::kHLG, gamut);
169 default:
170 ALOGV("Unsupported Gamma: %d, defaulting to sRGB transfer", dataspace);
171 return SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, gamut);
172 }
173}
174
John Reck67b1e2b2020-08-26 13:17:24 -0700175std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
176 const RenderEngineCreationArgs& args) {
177 // initialize EGL for the default display
178 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
179 if (!eglInitialize(display, nullptr, nullptr)) {
180 LOG_ALWAYS_FATAL("failed to initialize EGL");
181 }
182
183 const auto eglVersion = eglQueryStringImplementationANDROID(display, EGL_VERSION);
184 if (!eglVersion) {
185 checkGlError(__FUNCTION__, __LINE__);
186 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_VERSION) failed");
187 }
188
189 const auto eglExtensions = eglQueryStringImplementationANDROID(display, EGL_EXTENSIONS);
190 if (!eglExtensions) {
191 checkGlError(__FUNCTION__, __LINE__);
192 LOG_ALWAYS_FATAL("eglQueryStringImplementationANDROID(EGL_EXTENSIONS) failed");
193 }
194
195 auto& extensions = gl::GLExtensions::getInstance();
196 extensions.initWithEGLStrings(eglVersion, eglExtensions);
197
198 // The code assumes that ES2 or later is available if this extension is
199 // supported.
200 EGLConfig config = EGL_NO_CONFIG_KHR;
201 if (!extensions.hasNoConfigContext()) {
202 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
203 }
204
205 bool useContextPriority =
206 extensions.hasContextPriority() && args.contextPriority == ContextPriority::HIGH;
207 EGLContext protectedContext = EGL_NO_CONTEXT;
208 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
209 protectedContext = createEglContext(display, config, nullptr, useContextPriority,
210 Protection::PROTECTED);
211 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
212 }
213
214 EGLContext ctxt = createEglContext(display, config, protectedContext, useContextPriority,
215 Protection::UNPROTECTED);
216
217 // if can't create a GL context, we can only abort.
218 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
219
220 EGLSurface placeholder = EGL_NO_SURFACE;
221 if (!extensions.hasSurfacelessContext()) {
222 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
223 Protection::UNPROTECTED);
224 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
225 }
226 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
227 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
228 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
229 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
230
231 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
232 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
233 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
234 Protection::PROTECTED);
235 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
236 "can't create protected placeholder pbuffer");
237 }
238
239 // initialize the renderer while GL is current
240 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700241 std::make_unique<SkiaGLRenderEngine>(args, display, config, ctxt, placeholder,
John Reck67b1e2b2020-08-26 13:17:24 -0700242 protectedContext, protectedPlaceholder);
243
244 ALOGI("OpenGL ES informations:");
245 ALOGI("vendor : %s", extensions.getVendor());
246 ALOGI("renderer : %s", extensions.getRenderer());
247 ALOGI("version : %s", extensions.getVersion());
248 ALOGI("extensions: %s", extensions.getExtensions());
249 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
250 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
251
252 return engine;
253}
254
255EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
256 status_t err;
257 EGLConfig config;
258
259 // First try to get an ES3 config
260 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
261 if (err != NO_ERROR) {
262 // If ES3 fails, try to get an ES2 config
263 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
264 if (err != NO_ERROR) {
265 // If ES2 still doesn't work, probably because we're on the emulator.
266 // try a simplified query
267 ALOGW("no suitable EGLConfig found, trying a simpler query");
268 err = selectEGLConfig(display, format, 0, &config);
269 if (err != NO_ERROR) {
270 // this EGL is too lame for android
271 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
272 }
273 }
274 }
275
276 if (logConfig) {
277 // print some debugging info
278 EGLint r, g, b, a;
279 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
280 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
281 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
282 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
283 ALOGI("EGL information:");
284 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
285 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
286 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
287 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
288 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
289 }
290
291 return config;
292}
293
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700294SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
295 EGLConfig config, EGLContext ctxt, EGLSurface placeholder,
296 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri081be4c2020-09-16 10:24:47 -0700297 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700298 mEGLConfig(config),
299 mEGLContext(ctxt),
300 mPlaceholderSurface(placeholder),
301 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700302 mProtectedPlaceholderSurface(protectedPlaceholder),
303 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700304 // Suppress unused field warnings for things we definitely will need/use
305 // These EGL fields will all be needed for toggling between protected & unprotected contexts
306 // Or we need different RE instances for that
307 (void)mEGLDisplay;
308 (void)mEGLConfig;
309 (void)mEGLContext;
310 (void)mPlaceholderSurface;
311 (void)mProtectedEGLContext;
312 (void)mProtectedPlaceholderSurface;
313
314 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
315 LOG_ALWAYS_FATAL_IF(!glInterface.get());
316
317 GrContextOptions options;
318 options.fPreferExternalImagesOverES3 = true;
319 options.fDisableDistanceFieldPaths = true;
320 mGrContext = GrDirectContext::MakeGL(std::move(glInterface), options);
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700321
322 if (args.supportsBackgroundBlur) {
323 mBlurFilter = new BlurFilter();
324 }
John Reck67b1e2b2020-08-26 13:17:24 -0700325}
326
327base::unique_fd SkiaGLRenderEngine::flush() {
328 ATRACE_CALL();
329 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
330 return base::unique_fd();
331 }
332
333 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
334 if (sync == EGL_NO_SYNC_KHR) {
335 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
336 return base::unique_fd();
337 }
338
339 // native fence fd will not be populated until flush() is done.
340 glFlush();
341
342 // get the fence fd
343 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
344 eglDestroySyncKHR(mEGLDisplay, sync);
345 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
346 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
347 }
348
349 return fenceFd;
350}
351
352bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
353 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
354 !gl::GLExtensions::getInstance().hasWaitSync()) {
355 return false;
356 }
357
358 // release the fd and transfer the ownership to EGLSync
359 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
360 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
361 if (sync == EGL_NO_SYNC_KHR) {
362 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
363 return false;
364 }
365
366 // XXX: The spec draft is inconsistent as to whether this should return an
367 // EGLint or void. Ignore the return value for now, as it's not strictly
368 // needed.
369 eglWaitSyncKHR(mEGLDisplay, sync, 0);
370 EGLint error = eglGetError();
371 eglDestroySyncKHR(mEGLDisplay, sync);
372 if (error != EGL_SUCCESS) {
373 ALOGE("failed to wait for EGL native fence sync: %#x", error);
374 return false;
375 }
376
377 return true;
378}
379
380static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
381 return !!(desc.usage & usage);
382}
383
384void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
385 std::lock_guard<std::mutex> lock(mRenderingMutex);
386 mImageCache.erase(bufferId);
387}
388
389status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
390 const std::vector<const LayerSettings*>& layers,
391 const sp<GraphicBuffer>& buffer,
392 const bool useFramebufferCache,
393 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
394 ATRACE_NAME("SkiaGL::drawLayers");
395 std::lock_guard<std::mutex> lock(mRenderingMutex);
396 if (layers.empty()) {
397 ALOGV("Drawing empty layer stack");
398 return NO_ERROR;
399 }
400
401 if (bufferFence.get() >= 0) {
402 // Duplicate the fence for passing to waitFence.
403 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
404 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
405 ATRACE_NAME("Waiting before draw");
406 sync_wait(bufferFence.get(), -1);
407 }
408 }
409 if (buffer == nullptr) {
410 ALOGE("No output buffer provided. Aborting GPU composition.");
411 return BAD_VALUE;
412 }
413
414 AHardwareBuffer_Desc bufferDesc;
415 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
416
417 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
418 "missing usage");
419
420 sk_sp<SkSurface> surface;
421 if (useFramebufferCache) {
422 auto iter = mSurfaceCache.find(buffer->getId());
423 if (iter != mSurfaceCache.end()) {
424 ALOGV("Cache hit!");
425 surface = iter->second;
426 }
427 }
428 if (!surface) {
429 surface = SkSurface::MakeFromAHardwareBuffer(mGrContext.get(), buffer->toAHardwareBuffer(),
430 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
Alec Mourib5777452020-09-28 11:32:42 -0700431 mUseColorManagement
432 ? toColorSpace(display.outputDataspace)
433 : SkColorSpace::MakeSRGB(),
434 nullptr);
John Reck67b1e2b2020-08-26 13:17:24 -0700435 if (useFramebufferCache && surface) {
436 ALOGD("Adding to cache");
437 mSurfaceCache.insert({buffer->getId(), surface});
438 }
439 }
440 if (!surface) {
441 ALOGE("Failed to make surface");
442 return BAD_VALUE;
443 }
444 auto canvas = surface->getCanvas();
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700445 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700446
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700447 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
448 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
449 // displays might have different scaling when compared to the physical screen.
450 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
451 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
452 static_cast<SkScalar>(display.clip.width());
453 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
454 static_cast<SkScalar>(display.clip.height());
455 canvas->scale(scaleX, scaleY);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700456 canvas->clipRect(getSkRect(display.clip));
John Reck67b1e2b2020-08-26 13:17:24 -0700457 canvas->drawColor(0, SkBlendMode::kSrc);
458 for (const auto& layer : layers) {
Lucas Dupin21f348e2020-09-16 17:31:26 -0700459 SkPaint paint;
460 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700461 const auto dest = getSkRect(bounds);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700462
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700463 if (layer->backgroundBlurRadius > 0) {
464 ATRACE_NAME("BackgroundBlur");
465 mBlurFilter->draw(canvas, surface, layer->backgroundBlurRadius);
466 }
467
John Reck67b1e2b2020-08-26 13:17:24 -0700468 if (layer->source.buffer.buffer) {
469 ATRACE_NAME("DrawImage");
470 const auto& item = layer->source.buffer;
471 sk_sp<SkImage> image;
472 auto iter = mImageCache.find(item.buffer->getId());
473 if (iter != mImageCache.end()) {
474 image = iter->second;
475 } else {
476 image = SkImage::MakeFromAHardwareBuffer(item.buffer->toAHardwareBuffer(),
477 item.usePremultipliedAlpha
478 ? kPremul_SkAlphaType
Alec Mourib5777452020-09-28 11:32:42 -0700479 : kUnpremul_SkAlphaType,
480 mUseColorManagement
481 ? toColorSpace(
482 layer->sourceDataspace)
483 : SkColorSpace::MakeSRGB());
John Reck67b1e2b2020-08-26 13:17:24 -0700484 mImageCache.insert({item.buffer->getId(), image});
485 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700486
487 SkMatrix matrix;
488 if (layer->geometry.roundedCornersRadius > 0) {
489 const auto roundedRect = getRoundedRect(layer);
490 matrix.setTranslate(roundedRect.getBounds().left() - dest.left(),
491 roundedRect.getBounds().top() - dest.top());
492 } else {
493 matrix.setIdentity();
494 }
495 paint.setShader(image->makeShader(matrix));
John Reck67b1e2b2020-08-26 13:17:24 -0700496 } else {
497 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700498 const auto color = layer->source.solidColor;
499 paint.setColor(SkColor4f{.fR = color.r, .fG = color.g, .fB = color.b, layer->alpha});
500 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700501
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700502 // Layers have a local transform matrix that should be applied to them.
503 canvas->save();
504 canvas->concat(getSkM44(layer->geometry.positionTransform));
505
Lucas Dupin3f11e922020-09-22 17:31:04 -0700506 if (layer->shadow.length > 0) {
507 const auto rect = layer->geometry.roundedCornersRadius > 0
508 ? getSkRect(layer->geometry.roundedCornersCrop)
509 : dest;
510 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
511 }
512
Lucas Dupin21f348e2020-09-16 17:31:26 -0700513 if (layer->geometry.roundedCornersRadius > 0) {
514 canvas->drawRRect(getRoundedRect(layer), paint);
515 } else {
516 canvas->drawRect(dest, paint);
517 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700518 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700519 }
520 {
521 ATRACE_NAME("flush surface");
522 surface->flush();
523 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700524 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700525
526 if (drawFence != nullptr) {
527 *drawFence = flush();
528 }
529
530 // If flush failed or we don't support native fences, we need to force the
531 // gl command stream to be executed.
532 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
533 if (requireSync) {
534 ATRACE_BEGIN("Submit(sync=true)");
535 } else {
536 ATRACE_BEGIN("Submit(sync=false)");
537 }
538 bool success = mGrContext->submit(requireSync);
539 ATRACE_END();
540 if (!success) {
541 ALOGE("Failed to flush RenderEngine commands");
542 // Chances are, something illegal happened (either the caller passed
543 // us bad parameters, or we messed up our shader generation).
544 return INVALID_OPERATION;
545 }
546
547 // checkErrors();
548 return NO_ERROR;
549}
550
Lucas Dupin3f11e922020-09-22 17:31:04 -0700551inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
552 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
553}
554
555inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
556 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
557}
558
Lucas Dupin21f348e2020-09-16 17:31:26 -0700559inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Lucas Dupin3f11e922020-09-22 17:31:04 -0700560 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700561 const auto cornerRadius = layer->geometry.roundedCornersRadius;
562 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
563}
564
Lucas Dupin3f11e922020-09-22 17:31:04 -0700565inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
566 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
567}
568
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700569inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
570 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
571 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
572 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
573 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
574}
575
Lucas Dupin3f11e922020-09-22 17:31:04 -0700576inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
577 return SkPoint3::Make(vector.x, vector.y, vector.z);
578}
579
John Reck67b1e2b2020-08-26 13:17:24 -0700580size_t SkiaGLRenderEngine::getMaxTextureSize() const {
581 return mGrContext->maxTextureSize();
582}
583
584size_t SkiaGLRenderEngine::getMaxViewportDims() const {
585 return mGrContext->maxRenderTargetSize();
586}
587
Lucas Dupin3f11e922020-09-22 17:31:04 -0700588void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
589 const ShadowSettings& settings) {
590 ATRACE_CALL();
591 const float casterZ = settings.length / 2.0f;
592 const auto shadowShape = cornerRadius > 0
593 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
594 : SkPath::Rect(casterRect);
595 const auto flags =
596 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
597
598 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
599 getSkPoint3(settings.lightPos), settings.lightRadius,
600 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
601 flags);
602}
603
John Reck67b1e2b2020-08-26 13:17:24 -0700604EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
605 EGLContext shareContext, bool useContextPriority,
606 Protection protection) {
607 EGLint renderableType = 0;
608 if (config == EGL_NO_CONFIG_KHR) {
609 renderableType = EGL_OPENGL_ES3_BIT;
610 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
611 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
612 }
613 EGLint contextClientVersion = 0;
614 if (renderableType & EGL_OPENGL_ES3_BIT) {
615 contextClientVersion = 3;
616 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
617 contextClientVersion = 2;
618 } else if (renderableType & EGL_OPENGL_ES_BIT) {
619 contextClientVersion = 1;
620 } else {
621 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
622 }
623
624 std::vector<EGLint> contextAttributes;
625 contextAttributes.reserve(7);
626 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
627 contextAttributes.push_back(contextClientVersion);
628 if (useContextPriority) {
629 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
630 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
631 }
632 if (protection == Protection::PROTECTED) {
633 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
634 contextAttributes.push_back(EGL_TRUE);
635 }
636 contextAttributes.push_back(EGL_NONE);
637
638 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
639
640 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
641 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
642 // EGL_NO_CONTEXT so that we can abort.
643 if (config != EGL_NO_CONFIG_KHR) {
644 return context;
645 }
646 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
647 // should try to fall back to GLES 2.
648 contextAttributes[1] = 2;
649 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
650 }
651
652 return context;
653}
654
655EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
656 EGLConfig config, int hwcFormat,
657 Protection protection) {
658 EGLConfig placeholderConfig = config;
659 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
660 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
661 }
662 std::vector<EGLint> attributes;
663 attributes.reserve(7);
664 attributes.push_back(EGL_WIDTH);
665 attributes.push_back(1);
666 attributes.push_back(EGL_HEIGHT);
667 attributes.push_back(1);
668 if (protection == Protection::PROTECTED) {
669 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
670 attributes.push_back(EGL_TRUE);
671 }
672 attributes.push_back(EGL_NONE);
673
674 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
675}
676
677void SkiaGLRenderEngine::cleanFramebufferCache() {
678 mSurfaceCache.clear();
679}
680
681} // namespace skia
682} // namespace renderengine
683} // namespace android