1/*
2 * Copyright 2010 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/gpu/SkGr.h"
9
10#include "include/core/SkCanvas.h"
11#include "include/core/SkColorFilter.h"
12#include "include/core/SkData.h"
13#include "include/core/SkPixelRef.h"
14#include "include/effects/SkRuntimeEffect.h"
15#include "include/gpu/GrContext.h"
16#include "include/gpu/GrTypes.h"
17#include "include/private/GrRecordingContext.h"
18#include "include/private/SkIDChangeListener.h"
19#include "include/private/SkImageInfoPriv.h"
20#include "include/private/SkTemplates.h"
21#include "src/core/SkAutoMalloc.h"
22#include "src/core/SkBlendModePriv.h"
23#include "src/core/SkColorSpacePriv.h"
24#include "src/core/SkImagePriv.h"
25#include "src/core/SkMaskFilterBase.h"
26#include "src/core/SkMessageBus.h"
27#include "src/core/SkMipMap.h"
28#include "src/core/SkPaintPriv.h"
29#include "src/core/SkResourceCache.h"
30#include "src/core/SkTraceEvent.h"
31#include "src/gpu/GrBitmapTextureMaker.h"
32#include "src/gpu/GrCaps.h"
33#include "src/gpu/GrColorSpaceXform.h"
34#include "src/gpu/GrContextPriv.h"
35#include "src/gpu/GrGpuResourcePriv.h"
36#include "src/gpu/GrPaint.h"
37#include "src/gpu/GrProxyProvider.h"
38#include "src/gpu/GrRecordingContextPriv.h"
39#include "src/gpu/GrTextureProxy.h"
40#include "src/gpu/GrXferProcessor.h"
41#include "src/gpu/effects/GrBicubicEffect.h"
42#include "src/gpu/effects/GrPorterDuffXferProcessor.h"
43#include "src/gpu/effects/GrSkSLFP.h"
44#include "src/gpu/effects/GrXfermodeFragmentProcessor.h"
45#include "src/gpu/effects/generated/GrClampFragmentProcessor.h"
46#include "src/gpu/effects/generated/GrConstColorProcessor.h"
47#include "src/image/SkImage_Base.h"
48#include "src/shaders/SkShaderBase.h"
49
50GR_FP_SRC_STRING SKSL_DITHER_SRC = R"(
51// This controls the range of values added to color channels
52in int rangeType;
53
54void main(float2 p, inout half4 color) {
55 half value;
56 half range;
57 @switch (rangeType) {
58 case 0:
59 range = 1.0 / 255.0;
60 break;
61 case 1:
62 range = 1.0 / 63.0;
63 break;
64 default:
65 // Experimentally this looks better than the expected value of 1/15.
66 range = 1.0 / 15.0;
67 break;
68 }
69 @if (sk_Caps.integerSupport) {
70 // This ordered-dither code is lifted from the cpu backend.
71 uint x = uint(p.x);
72 uint y = uint(p.y);
73 uint m = (y & 1) << 5 | (x & 1) << 4 |
74 (y & 2) << 2 | (x & 2) << 1 |
75 (y & 4) >> 1 | (x & 4) >> 2;
76 value = half(m) * 1.0 / 64.0 - 63.0 / 128.0;
77 } else {
78 // Simulate the integer effect used above using step/mod. For speed, simulates a 4x4
79 // dither pattern rather than an 8x8 one.
80 half4 modValues = mod(half4(half(p.x), half(p.y), half(p.x), half(p.y)), half4(2.0, 2.0, 4.0, 4.0));
81 half4 stepValues = step(modValues, half4(1.0, 1.0, 2.0, 2.0));
82 value = dot(stepValues, half4(8.0 / 16.0, 4.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0)) - 15.0 / 32.0;
83 }
84 // For each color channel, add the random offset to the channel value and then clamp
85 // between 0 and alpha to keep the color premultiplied.
86 color = half4(clamp(color.rgb + value * range, 0.0, color.a), color.a);
87}
88)";
89
90void GrMakeKeyFromImageID(GrUniqueKey* key, uint32_t imageID, const SkIRect& imageBounds) {
91 SkASSERT(key);
92 SkASSERT(imageID);
93 SkASSERT(!imageBounds.isEmpty());
94 static const GrUniqueKey::Domain kImageIDDomain = GrUniqueKey::GenerateDomain();
95 GrUniqueKey::Builder builder(key, kImageIDDomain, 5, "Image");
96 builder[0] = imageID;
97 builder[1] = imageBounds.fLeft;
98 builder[2] = imageBounds.fTop;
99 builder[3] = imageBounds.fRight;
100 builder[4] = imageBounds.fBottom;
101}
102
103////////////////////////////////////////////////////////////////////////////////
104
105sk_sp<SkIDChangeListener> GrMakeUniqueKeyInvalidationListener(GrUniqueKey* key,
106 uint32_t contextID) {
107 class Listener : public SkIDChangeListener {
108 public:
109 Listener(const GrUniqueKey& key, uint32_t contextUniqueID) : fMsg(key, contextUniqueID) {}
110
111 void changed() override { SkMessageBus<GrUniqueKeyInvalidatedMessage>::Post(fMsg); }
112
113 private:
114 GrUniqueKeyInvalidatedMessage fMsg;
115 };
116
117 auto listener = sk_make_sp<Listener>(*key, contextID);
118
119 // We stick a SkData on the key that calls invalidateListener in its destructor.
120 auto invalidateListener = [](const void* ptr, void* /*context*/) {
121 auto listener = reinterpret_cast<const sk_sp<Listener>*>(ptr);
122 (*listener)->markShouldDeregister();
123 delete listener;
124 };
125 auto data = SkData::MakeWithProc(new sk_sp<Listener>(listener),
126 sizeof(sk_sp<Listener>),
127 invalidateListener,
128 nullptr);
129 SkASSERT(!key->getCustomData());
130 key->setCustomData(std::move(data));
131 return std::move(listener);
132}
133
134sk_sp<GrSurfaceProxy> GrCopyBaseMipMapToTextureProxy(GrRecordingContext* ctx,
135 GrSurfaceProxy* baseProxy,
136 GrSurfaceOrigin origin,
137 SkBudgeted budgeted) {
138 SkASSERT(baseProxy);
139
140 if (!ctx->priv().caps()->isFormatCopyable(baseProxy->backendFormat())) {
141 return {};
142 }
143 auto copy = GrSurfaceProxy::Copy(ctx, baseProxy, origin, GrMipMapped::kYes,
144 SkBackingFit::kExact, budgeted);
145 if (!copy) {
146 return {};
147 }
148 SkASSERT(copy->asTextureProxy());
149 return copy;
150}
151
152GrSurfaceProxyView GrCopyBaseMipMapToView(GrRecordingContext* context,
153 GrSurfaceProxyView src,
154 SkBudgeted budgeted) {
155 auto origin = src.origin();
156 auto swizzle = src.swizzle();
157 auto* proxy = src.proxy();
158 return {GrCopyBaseMipMapToTextureProxy(context, proxy, origin, budgeted), origin, swizzle};
159}
160
161GrSurfaceProxyView GrRefCachedBitmapView(GrRecordingContext* ctx, const SkBitmap& bitmap,
162 GrMipMapped mipMapped) {
163 GrBitmapTextureMaker maker(ctx, bitmap, GrImageTexGenPolicy::kDraw);
164 return maker.view(mipMapped);
165}
166
167GrSurfaceProxyView GrMakeCachedBitmapProxyView(GrRecordingContext* context,
168 const SkBitmap& bitmap) {
169 if (!bitmap.peekPixels(nullptr)) {
170 return {};
171 }
172
173 GrBitmapTextureMaker maker(context, bitmap, GrImageTexGenPolicy::kDraw);
174 return maker.view(GrMipMapped::kNo);
175}
176
177///////////////////////////////////////////////////////////////////////////////
178
179SkPMColor4f SkColorToPMColor4f(SkColor c, const GrColorInfo& colorInfo) {
180 SkColor4f color = SkColor4f::FromColor(c);
181 if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
182 color = xform->apply(color);
183 }
184 return color.premul();
185}
186
187SkColor4f SkColor4fPrepForDst(SkColor4f color, const GrColorInfo& colorInfo) {
188 if (auto* xform = colorInfo.colorSpaceXformFromSRGB()) {
189 color = xform->apply(color);
190 }
191 return color;
192}
193
194///////////////////////////////////////////////////////////////////////////////
195
196static inline bool blend_requires_shader(const SkBlendMode mode) {
197 return SkBlendMode::kDst != mode;
198}
199
200#ifndef SK_IGNORE_GPU_DITHER
201static inline int32_t dither_range_type_for_config(GrColorType dstColorType) {
202 switch (dstColorType) {
203 case GrColorType::kUnknown:
204 case GrColorType::kGray_8:
205 case GrColorType::kRGBA_8888:
206 case GrColorType::kRGB_888x:
207 case GrColorType::kRG_88:
208 case GrColorType::kBGRA_8888:
209 case GrColorType::kRG_1616:
210 case GrColorType::kRGBA_16161616:
211 case GrColorType::kRG_F16:
212 case GrColorType::kRGBA_8888_SRGB:
213 case GrColorType::kRGBA_1010102:
214 case GrColorType::kAlpha_F16:
215 case GrColorType::kRGBA_F32:
216 case GrColorType::kRGBA_F16:
217 case GrColorType::kRGBA_F16_Clamped:
218 case GrColorType::kAlpha_8:
219 case GrColorType::kAlpha_8xxx:
220 case GrColorType::kAlpha_16:
221 case GrColorType::kAlpha_F32xxx:
222 case GrColorType::kGray_8xxx:
223 case GrColorType::kRGB_888:
224 case GrColorType::kR_8:
225 case GrColorType::kR_16:
226 case GrColorType::kR_F16:
227 case GrColorType::kGray_F16:
228 return 0;
229 case GrColorType::kBGR_565:
230 return 1;
231 case GrColorType::kABGR_4444:
232 return 2;
233 }
234 SkUNREACHABLE;
235}
236#endif
237
238static inline bool skpaint_to_grpaint_impl(GrRecordingContext* context,
239 const GrColorInfo& dstColorInfo,
240 const SkPaint& skPaint,
241 const SkMatrix& viewM,
242 std::unique_ptr<GrFragmentProcessor>* shaderProcessor,
243 SkBlendMode* primColorMode,
244 GrPaint* grPaint) {
245 // Convert SkPaint color to 4f format in the destination color space
246 SkColor4f origColor = SkColor4fPrepForDst(skPaint.getColor4f(), dstColorInfo);
247
248 GrFPArgs fpArgs(context, &viewM, skPaint.getFilterQuality(), &dstColorInfo);
249
250 // Setup the initial color considering the shader, the SkPaint color, and the presence or not
251 // of per-vertex colors.
252 std::unique_ptr<GrFragmentProcessor> shaderFP;
253 if (!primColorMode || blend_requires_shader(*primColorMode)) {
254 fpArgs.fInputColorIsOpaque = origColor.isOpaque();
255 if (shaderProcessor) {
256 shaderFP = std::move(*shaderProcessor);
257 } else if (const auto* shader = as_SB(skPaint.getShader())) {
258 shaderFP = shader->asFragmentProcessor(fpArgs);
259 if (!shaderFP) {
260 return false;
261 }
262 }
263 }
264
265 // Set this in below cases if the output of the shader/paint-color/paint-alpha/primXfermode is
266 // a known constant value. In that case we can simply apply a color filter during this
267 // conversion without converting the color filter to a GrFragmentProcessor.
268 bool applyColorFilterToPaintColor = false;
269 if (shaderFP) {
270 if (primColorMode) {
271 // There is a blend between the primitive color and the shader color. The shader sees
272 // the opaque paint color. The shader's output is blended using the provided mode by
273 // the primitive color. The blended color is then modulated by the paint's alpha.
274
275 // The geometry processor will insert the primitive color to start the color chain, so
276 // the GrPaint color will be ignored.
277
278 SkPMColor4f shaderInput = origColor.makeOpaque().premul();
279 shaderFP = GrFragmentProcessor::OverrideInput(std::move(shaderFP), shaderInput);
280 shaderFP = GrXfermodeFragmentProcessor::MakeFromSrcProcessor(std::move(shaderFP),
281 *primColorMode);
282
283 // The above may return null if compose results in a pass through of the prim color.
284 if (shaderFP) {
285 grPaint->addColorFragmentProcessor(std::move(shaderFP));
286 }
287
288 // We can ignore origColor here - alpha is unchanged by gamma
289 float paintAlpha = skPaint.getColor4f().fA;
290 if (1.0f != paintAlpha) {
291 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
292 // color channels. It's value should be treated as the same in ANY color space.
293 grPaint->addColorFragmentProcessor(GrConstColorProcessor::Make(
294 { paintAlpha, paintAlpha, paintAlpha, paintAlpha },
295 GrConstColorProcessor::InputMode::kModulateRGBA));
296 }
297 } else {
298 // The shader's FP sees the paint *unpremul* color
299 SkPMColor4f origColorAsPM = { origColor.fR, origColor.fG, origColor.fB, origColor.fA };
300 grPaint->setColor4f(origColorAsPM);
301 grPaint->addColorFragmentProcessor(std::move(shaderFP));
302 }
303 } else {
304 if (primColorMode) {
305 // There is a blend between the primitive color and the paint color. The blend considers
306 // the opaque paint color. The paint's alpha is applied to the post-blended color.
307 SkPMColor4f opaqueColor = origColor.makeOpaque().premul();
308 auto processor = GrConstColorProcessor::Make(opaqueColor,
309 GrConstColorProcessor::InputMode::kIgnore);
310 processor = GrXfermodeFragmentProcessor::MakeFromSrcProcessor(std::move(processor),
311 *primColorMode);
312 if (processor) {
313 grPaint->addColorFragmentProcessor(std::move(processor));
314 }
315
316 grPaint->setColor4f(opaqueColor);
317
318 // We can ignore origColor here - alpha is unchanged by gamma
319 float paintAlpha = skPaint.getColor4f().fA;
320 if (1.0f != paintAlpha) {
321 // No gamut conversion - paintAlpha is a (linear) alpha value, splatted to all
322 // color channels. It's value should be treated as the same in ANY color space.
323 grPaint->addColorFragmentProcessor(GrConstColorProcessor::Make(
324 { paintAlpha, paintAlpha, paintAlpha, paintAlpha },
325 GrConstColorProcessor::InputMode::kModulateRGBA));
326 }
327 } else {
328 // No shader, no primitive color.
329 grPaint->setColor4f(origColor.premul());
330 applyColorFilterToPaintColor = true;
331 }
332 }
333
334 SkColorFilter* colorFilter = skPaint.getColorFilter();
335 if (colorFilter) {
336 if (applyColorFilterToPaintColor) {
337 SkColorSpace* dstCS = dstColorInfo.colorSpace();
338 grPaint->setColor4f(colorFilter->filterColor4f(origColor, dstCS, dstCS).premul());
339 } else {
340 auto cfFP = colorFilter->asFragmentProcessor(context, dstColorInfo);
341 if (cfFP) {
342 grPaint->addColorFragmentProcessor(std::move(cfFP));
343 } else {
344 return false;
345 }
346 }
347 }
348
349 SkMaskFilterBase* maskFilter = as_MFB(skPaint.getMaskFilter());
350 if (maskFilter) {
351 // We may have set this before passing to the SkShader.
352 fpArgs.fInputColorIsOpaque = false;
353 if (auto mfFP = maskFilter->asFragmentProcessor(fpArgs)) {
354 grPaint->addCoverageFragmentProcessor(std::move(mfFP));
355 }
356 }
357
358 // When the xfermode is null on the SkPaint (meaning kSrcOver) we need the XPFactory field on
359 // the GrPaint to also be null (also kSrcOver).
360 SkASSERT(!grPaint->getXPFactory());
361 if (!skPaint.isSrcOver()) {
362 grPaint->setXPFactory(SkBlendMode_AsXPFactory(skPaint.getBlendMode()));
363 }
364
365#ifndef SK_IGNORE_GPU_DITHER
366 GrColorType ct = dstColorInfo.colorType();
367 if (SkPaintPriv::ShouldDither(skPaint, GrColorTypeToSkColorType(ct)) &&
368 grPaint->numColorFragmentProcessors() > 0) {
369 int32_t ditherRange = dither_range_type_for_config(ct);
370 if (ditherRange >= 0) {
371 static auto effect = std::get<0>(SkRuntimeEffect::Make(SkString(SKSL_DITHER_SRC)));
372 auto ditherFP = GrSkSLFP::Make(context, effect, "Dither",
373 SkData::MakeWithCopy(&ditherRange, sizeof(ditherRange)));
374 if (ditherFP) {
375 grPaint->addColorFragmentProcessor(std::move(ditherFP));
376 }
377 }
378 }
379#endif
380 if (GrColorTypeClampType(dstColorInfo.colorType()) == GrClampType::kManual) {
381 if (grPaint->numColorFragmentProcessors()) {
382 grPaint->addColorFragmentProcessor(GrClampFragmentProcessor::Make(false));
383 } else {
384 auto color = grPaint->getColor4f();
385 grPaint->setColor4f({SkTPin(color.fR, 0.f, 1.f),
386 SkTPin(color.fG, 0.f, 1.f),
387 SkTPin(color.fB, 0.f, 1.f),
388 SkTPin(color.fA, 0.f, 1.f)});
389 }
390 }
391 return true;
392}
393
394bool SkPaintToGrPaint(GrRecordingContext* context, const GrColorInfo& dstColorInfo,
395 const SkPaint& skPaint, const SkMatrix& viewM, GrPaint* grPaint) {
396 return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, viewM, nullptr, nullptr,
397 grPaint);
398}
399
400/** Replaces the SkShader (if any) on skPaint with the passed in GrFragmentProcessor. */
401bool SkPaintToGrPaintReplaceShader(GrRecordingContext* context,
402 const GrColorInfo& dstColorInfo,
403 const SkPaint& skPaint,
404 std::unique_ptr<GrFragmentProcessor> shaderFP,
405 GrPaint* grPaint) {
406 if (!shaderFP) {
407 return false;
408 }
409 return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, SkMatrix::I(), &shaderFP,
410 nullptr, grPaint);
411}
412
413/** Ignores the SkShader (if any) on skPaint. */
414bool SkPaintToGrPaintNoShader(GrRecordingContext* context,
415 const GrColorInfo& dstColorInfo,
416 const SkPaint& skPaint,
417 GrPaint* grPaint) {
418 // Use a ptr to a nullptr to to indicate that the SkShader is ignored and not replaced.
419 std::unique_ptr<GrFragmentProcessor> nullShaderFP(nullptr);
420 return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, SkMatrix::I(), &nullShaderFP,
421 nullptr, grPaint);
422}
423
424/** Blends the SkPaint's shader (or color if no shader) with a per-primitive color which must
425be setup as a vertex attribute using the specified SkBlendMode. */
426bool SkPaintToGrPaintWithXfermode(GrRecordingContext* context,
427 const GrColorInfo& dstColorInfo,
428 const SkPaint& skPaint,
429 const SkMatrix& viewM,
430 SkBlendMode primColorMode,
431 GrPaint* grPaint) {
432 return skpaint_to_grpaint_impl(context, dstColorInfo, skPaint, viewM, nullptr, &primColorMode,
433 grPaint);
434}
435
436bool SkPaintToGrPaintWithTexture(GrRecordingContext* context,
437 const GrColorInfo& dstColorInfo,
438 const SkPaint& paint,
439 const SkMatrix& viewM,
440 std::unique_ptr<GrFragmentProcessor> fp,
441 bool textureIsAlphaOnly,
442 GrPaint* grPaint) {
443 std::unique_ptr<GrFragmentProcessor> shaderFP;
444 if (textureIsAlphaOnly) {
445 if (const auto* shader = as_SB(paint.getShader())) {
446 shaderFP = shader->asFragmentProcessor(
447 GrFPArgs(context, &viewM, paint.getFilterQuality(), &dstColorInfo));
448 if (!shaderFP) {
449 return false;
450 }
451 std::unique_ptr<GrFragmentProcessor> fpSeries[] = { std::move(shaderFP), std::move(fp) };
452 shaderFP = GrFragmentProcessor::RunInSeries(fpSeries, 2);
453 } else {
454 shaderFP = GrFragmentProcessor::MakeInputPremulAndMulByOutput(std::move(fp));
455 }
456 } else {
457 if (paint.getColor4f().isOpaque()) {
458 shaderFP = GrFragmentProcessor::OverrideInput(std::move(fp), SK_PMColor4fWHITE, false);
459 } else {
460 shaderFP = GrFragmentProcessor::MulChildByInputAlpha(std::move(fp));
461 }
462 }
463
464 return SkPaintToGrPaintReplaceShader(context, dstColorInfo, paint, std::move(shaderFP),
465 grPaint);
466}
467
468////////////////////////////////////////////////////////////////////////////////////////////////
469
470GrSamplerState::Filter GrSkFilterQualityToGrFilterMode(int imageWidth, int imageHeight,
471 SkFilterQuality paintFilterQuality,
472 const SkMatrix& viewM,
473 const SkMatrix& localM,
474 bool sharpenMipmappedTextures,
475 bool* doBicubic) {
476 *doBicubic = false;
477 if (imageWidth <= 1 && imageHeight <= 1) {
478 return GrSamplerState::Filter::kNearest;
479 }
480 switch (paintFilterQuality) {
481 case kNone_SkFilterQuality:
482 return GrSamplerState::Filter::kNearest;
483 case kLow_SkFilterQuality:
484 return GrSamplerState::Filter::kBilerp;
485 case kMedium_SkFilterQuality: {
486 SkMatrix matrix;
487 matrix.setConcat(viewM, localM);
488 // With sharp mips, we bias lookups by -0.5. That means our final LOD is >= 0 until the
489 // computed LOD is >= 0.5. At what scale factor does a texture get an LOD of 0.5?
490 //
491 // Want: 0 = log2(1/s) - 0.5
492 // 0.5 = log2(1/s)
493 // 2^0.5 = 1/s
494 // 1/2^0.5 = s
495 // 2^0.5/2 = s
496 SkScalar mipScale = sharpenMipmappedTextures ? SK_ScalarRoot2Over2 : SK_Scalar1;
497 if (matrix.getMinScale() < mipScale) {
498 return GrSamplerState::Filter::kMipMap;
499 } else {
500 // Don't trigger MIP level generation unnecessarily.
501 return GrSamplerState::Filter::kBilerp;
502 }
503 }
504 case kHigh_SkFilterQuality: {
505 SkMatrix matrix;
506 matrix.setConcat(viewM, localM);
507 GrSamplerState::Filter textureFilterMode;
508 *doBicubic = GrBicubicEffect::ShouldUseBicubic(matrix, &textureFilterMode);
509 return textureFilterMode;
510 }
511 }
512 SkUNREACHABLE;
513}
514